Undo it

We use many applications like text editors, drawing editors, IDEs, mail applications etc. One common feature of almost all of these applications is the undo operation (without which life would have been very difficult). Depending on the application you are using, this undo takes various forms.  In a text editor, the undo changes the paragraph text back to what it was. In case of a drawing editor like paint brush and UML tools, you can undo your drag-drops, new shapes etc.      

The most common way to implement the undo operation is using Command pattern (undo is just one aspect of Command pattern). A command object represents a complete set of information required to execute a particular request.  The system creates appropriate command object for each request, fills with required information and invokes execute() on it through a known interface (Command interface). The command object’s execute() method knows what to do. Supposing you are working on a drawing editor (UML editor for example), you might move a shape to a new position and make it little bigger. For the move operation, the editor creates an instance of MoveShapeCommand and populates it with shape id, originalX, originalY, destinationX and destinationY attributes. It invokes execute() method on this object whose implementation is to redraw the shape in the new (x,y) coordinates. It then pushes the command object to a stack. For the resize operation, it creates a ResizeShapeCommand object with shape id, originalLength, originalWidth, newLength and newWidth attributes stored in it. The editor framework then invokes execute() on it whose implementation is to  redraw the picture with new dimensions. It then pushes the command object to the stack. In essence, for each operation you perform, corresponding Command objects are created, populated with required information, execute() is invoked and are stacked.

You might probably have guessed the undo now. Each Command object also implements an unexecute() which does the opposite of execute. When you perform undo (Mostly Ctrl + z), the last command object is popped out and its unexecute() is invoked. In our example, when you undo, the ResizeShapeCommand is popped-out and unexecute() is invoked which draws the shape with its original dimensions. One more undo will pop-out MoveShapeCommand whose unexecute() will draw the shape in the original (x,y) coordinates. The popped-out objects can be stored in another stack in order to support redo operations. All you have to do is just pop-out the last object and invoke execute() again. Pressing Ctrl +Z and Ctrl + Y alternatively just requires invoking execute/unexecute on the last Command object and moving the same between stacks (or some other means). How about extending command pattern to Audit Trail or a Transaction commit/rollback?

Anyway, that’s half the story. I very well knew that undo/redo is achieved using Command pattern. While at work one day, one of my colleague did a ‘Find/Replace All’. I hadn’t had a thought before if/how the same Command pattern could be extended to do a group of operations. Another example is when you select multiple shapes and move them all together to new location? Both of these operations involve more than one operation and hence a group of Command objects are used together. After all, ‘Find and Replace All’  is just another operation except that it is composed of multiple small operations. So we should be able to undo/redo the entire ‘Find/Replace All’ the same way you do a character/text change, right? You should be able to have a FindAndReplaceAllCommand class that is composed of multiple TextChangeCommand objects, and the execute and unexecute methods of FindAndReplaceAllCommand would just invoke the same methods on each individual TextChangeCommand objects, right? That’s the beauty of Composite pattern.

I went back to the book to see if this is described . Not to my surprise, it is clearly mentioned as MacroCommand or Composite command. Once again I was dissappointed that the book didn’t miss anything (will tell you a similar experience later).

-Raj Radhakrishnan

Why ‘type’ matters?

It matters in OOP if you want to write a framework or develop a OO system that is truly extensible. Good news for new OO  programmers: a) It matters to you if you want to really understand and appreciate polymorphism b) It also helps you to answer the world famous interview question: What is the difference between an abstract class and an interface?

Ignore java interface for now. I mean the java syntax: public interface MyInterface{… (I wonder the optimism exhibited by authors who try to explain interfaces and polymorphism with MyInterface or XInterface).

Every object is of some type: Let me look around. A House is a type of Building. A Chair is a type of Furniture. A Wireless  keyboard is a type of Keyboard. A Keyboard is a type of interface (I mean Peripheral interface..just kidding). A cell phone is a  type of Phone (You just thought of a Phone super-class and CellPhone subclass, didn’t you?).

Type is a way to generalize the properties of one or more objects. For example, you can make and receive calls on any type of  Phone. You can type characters in a text editor using any type of Keyboard. When you check an object instanceof X in Java, you are truely checking if the object is typeof X. If the check returns true,  you can assign the object to a variable of type X (!) and invoke a method defined in X. The object accepts all requests for the  operations defined in X and it’s super types. So, a type essentially indicates a particular interface of an object. An object’s interface defines the set of operations that can be executed on it. OO books refer to the process of invoking an object’s method as ‘sending a  message’ or ‘sending a request’ . You can access/invoke an object only through it’s interface.  An object can be of many types  and many objects can be of same type (polymorphism and substitutability). A client object(caller) doesn’t know anything about an object itself but it’s interface.

If you look at the above paragraph carefully, we have already touched lot of the topics in OOP like Objects, Interfaces, Types,  Interface inheritance, Polymorphism – Dynamic Binding – Substitutability etc. We haven’t talked about the java interface yet. In  fact we haven’t talked about even classes yet. Many people think a class is the starting point of Object-Oriented Programming. Had that been true, it would have been called Class-Oriented Programming.

A class comes into picture only during implmentation of an object. An object’s class defines the template of how it’s object would look like –  by specifying the internal state and operations that could be invoked. How is an object’s class related to its type?

Thinking in Java (Bruce Eckel): Every object has a type. Using the parlance, each object is an instance of a class, in which “class” is synonymous with “type.”  The most important distinguishing characteristic of a class is “What messages can you send to it?”. All objects of a particular type can receive the same messages. An object has an interface. The requests you can make of an object are defined by its interface, and the type is what determines  the interface.

Design patterns (GoF): There’s a close relationship between class and type. Because a class defines the operations an object can perform, it also defines the object’s type. When we say that an object is an instance of a class, we imply that the object supports the interface defined by the class.

Type is important in OOP because that is what allows you to substitute an object with another of same type. The client objects (caller) access the object through the interface defined by its type. For example, a CellPhone and CordlessPhone are different types of Phone that use entirely different technologies. However you could use either of them the same way without having to know about their implementations because they both are of type Phone. You can use a cell phone in place of a cordless phone to make calls and vice versa.

You would be forming a hierarchy of types if you include the interface of one into another. This is known as sub-typing. A wireless keyboard is a type of  keyboard which is in turn a type of peripheral device. In this case, the wireless keyboard includes the interface of Keyboard  which includes the interface of PeripheralDevice type. Remember only the interface (set of operations) is included, not the implementation. That is,  there could be different implementations of PeripheralDevice (mouse, UBS hard-drive etc). Similarly there could be different  implementations of Keyboard (diff brands, standard/internet keyboards, Japanese etc) and wireless keyboard. The wireless keyboard  supports all operations defined by it’s own type + Keyboard type + PeripheralDevice type. This is interface-inheritance with which we inherit only the interface defined by the super type.

Now comes the question of how to define a type in Java. As we have seen earlier, an object’s own class itself defines its type.  When you extend a class from another, that is with class-inheritance, you are actually inheriting both the type and implementation of the super class.  An object of the new class obviously supports the operations defined in its super class . Take the classic  java.lang.Object.toString() method. Every object in Java supports this method because it is a type of java.lang.Object. A button  object can receive mouse events through a listener because it is a type of java.awt.Component. It can be added to a Frame because it is a type of Window which is a type of Container. “abc” is an object which is a type of String so you could invoke length() operation. It is also a type of java.lang.Object so a thread could wait() on it. It is also a type of Comparable so you can  compare it with “def”…Isn’t Comparable a java interface?

Java allows you to define types as pure interfaces (now we are talking about java interfaces). A pure interface defines only the  operations and no implementation. It just defines a type so that any object that implements the interface can be treated the same way. A pure abstract class is exactly same as an interface because it too just forms a type. The difference between an abstract class  and interface makes sense only when the class is partially abstract in which case one or more of its methods are concrete. A subclass in this case inherits the implementation concrete methods defined in the super class. Let’s stop here: When a class implements an interface, you are doing interface-inheritance.  You are making the class of the interface type. When a class extends another class, you are doing both class-inheritance (or implementation inheritance) and interface-inheritance.

You can mix and match these features however you like. For example, if you ever written an applet, you extend from  java.awt.Applet. And, if you want to start a thread (normally a scrolling ticker:) you make your class implement  java.lang.Runnable. In this case, your class has two types: Applet and Runnable. The applet container knows your applet object  through Applet interface whereas the Runnable interface is used in turn by the Thread object you start. Or considering a simple class MyThread class extending Thread, Thread is a type of Runnable and MyThread is a type of Thread. In  the former case we inherit only the interface defined by the type (run() method) whereas in the latter we inherit interfaces of both Thread  and Runnable + implementation of Thread class. Or considering an instance of ArrayList, it is a type of List (as with LinkedList), a type of Collection (as with HashSet), a  type of Serializable (as with String). By extending AbstractList, it inherits the interfaces defined by List and Collection in  addition to lot of functionality (implementation inheritance).

When people say “Program to interface, not implementation”, they mean the interface defined by the object’s type, not an equivalent java interface. You program to an object’s interface as long as your assigned type is a super-type that can potentially have multiple implementations. This allows you to configure or choose respective implementation at runtime.

InputStream is = …;
int data = is.read();

Connection c = …;
Statement s = c.createStatement();

In the first example, we use the interface defined by the abstract class java.io.InputStream. You can use FileInputStream or ByteArrayInputStream or any other types of InputStream the same way. In the second example, we use the interface defined by the java interface java.sql.Connection. You could use OracleConnection or SQLServerConnection or any other types of Connection the same way. This substitutability is a key feature of any OO system.

Let’s check on some common statements made about abstract classes and interfaces.

  1. A class can extend only one abstract class whereas it can implement multiple interfaces: This statement doesn’t tell anything about what’s there in the abstract class. People normally mean partially implemented abstract class here in which case, it is both type and class (implementation) inheritance. If it is a pure abstract class, then it is a pure interface inheritance. By implementing multiple interfaces, we make the object of multiple types. Without the notion of type or object’s interface, this statement is unclear.
  2. Java doesn’t support multiple-inheritance, hence we have interfaces: Again, by multiple-inheritance, people mean ‘class-inheritance’. However there is no reuse of implementation when you implement an interface. I think it has to read “A java interface is the best candidate to represent a type. In order to design a class that can have many types, we make it implement multiple interfaces”. Example: ArrayList class and Collection and Serializable interfaces.

So, what type are you?

Note: I will try to improve the content of this post after some time. I would like to have a fresh look.

-Raj Radhakrishnan

25000 and 1 Billion

My wife presented me an iPhone 3G as my birthday gift last month. I’m still playing with it to uncover all of it’s features. The multi-touch screen, built-in iPod, 3G Internet, GPS etc do make it a revolutionary phone.  I won’t be surprised if my spell checker skips the word iPhone in the near future. 

However I have to say that I am personally impressed more with the iPhone Apps compared to all the other features. I firmly believe App Store is the place where people spend most of their time. At the time of this writing, there are about 25,000 iPhone applications available and the download count is going to hit a billion. The iPhone website says ‘There’s an app for just about anything’. It’s true.

It has not been even 2 years yet since iPhone was released and you already have 25,000 applications. Remember they are just phone applications (the word ‘just’ will soon become inappropriate considering the increasing usage of mobile applications). You need an iMac computer to use the SDK and probably iPhone Developer Program enrolment ($99 for standard program and $299 for enterprise program). People who have been writing these apps range from just-for-fun developers to serious entrepreneurs. Also, my experience with the quality of the applications so far is simply excellent.

Apple’s cut on app price is 30%. More apps + more downloads = more money. From the perspective of iPhone app development, though the primary motivation of  most developers is to make money as well (business opportunity), the ease of development is paramount in keeping the let-me-write-one- app spirit up among developers. I don’t know much details about the SDK/API yet. However if I have to buy a special iPhone  development adapter hardware and configure it, read a 548 page nuts-and-bolts development and troubleshooting guide, off-the-standard syntax and unclear examples, advanced  debugger tools and, confusing configuration and complex packaging in order to write a simple touch-application, I bet we wouldn’t have seen 25,000 number today. Had they got  crappier (poor performance, being erroneous etc), not many people would have downloaded and, we wouldn’t have seen 1 billion number either.

I always believe in things that are Simple, Elegant and Working. Apple just made my belief stronger.

Update: It is 25,000 and 1 billion in just 9 months (not 2 years).

-Raj Radhakrishnan

Protected: Funny Confessions of a Java Programmer

This content is password protected. To view it please enter your password below:

Excellence and Self-satisfaction

Ok, This one is little off my stream.  

As with most of you, I too receive lot of forward emails and ignore most of them. However the one I received few days back impressed me a lot and I felt a desire to post it. 

A man once visited a temple under construction where he saw a sculptor making an idol of God. Suddenly he noticed a similar idol lying nearby. Surprised, he asked the sculptor, “Do you need two statues of the same idol?” “No,” said the sculptor without looking up, “We need only one, but the first one got damaged at the last stage.” The gentleman examined the idol and found no apparent damage. “Where is the damage?” he asked. “There is a scratch on the nose of the idol.” said the sculptor, still busy with his work. “Where are you going to install the idol?” The sculptor replied that it would be installed on a pillar twenty feet high. “If the idol is that far, who is going to know that there is a scratch on the nose?” the gentleman asked.

The sculptor stopped his work, looked up at the gentleman, smiled and said, “I will know it.”

The desire to excel is exclusive of the fact whether someone else appreciates it or not. “Excellence” is a drive from inside, not outside. Excellence is not for someone else to notice but for your own satisfaction and excellence.

In simple terms, you should be satisfied of your work in the first place..how true? I received it from one of my best and brilliant friend Vijayakumar Neelakandan. Thanks for sending such a nice story Vijay.

-Raj Radhakrishnan

Design Patterns myths and what people mean…

I have read many jokes titled ‘What people say and what they mean”. I felt I too can come with something on my yesterday’s post “Design Patterns myths you know of..” . Here we go..

What people say and what they mean…

1.What they say – Design patterns are all about some Graphical editor frameworks.
What they mean – I too tried reading the design patterns book and gave up
(As I said earlier, it is really sad. I too wish the book had better examples. I have browsed James Cooper and was disappointed with that too.)

2.What they say – We don’t need design patterns in our project.
What they mean – I know it’s out there; Not sure if we need them really
(It’s not a technology or choice of API to choose between. Patterns are natural parts of an OO system.)

3.What they say – We have to use design patterns in our project.
What they mean – I have started reading design patterns. I want to practice.
(Almost all programmers do this in order to make their resume more attractive (hands-on experience!!). True with other technologies/APIs as well.)

4.What they say – Design patterns are meant only for software frameworks, not applications.
What they mean – I want to stay away as much as possible.
(The flexibility in software is you can always write a working program.)

5.What they say – Come on, we use patterns every day. I just don’t know the names.
What they mean – Please don’t make me read.
(Same as above.)

6.What they say – Singleton is the most important pattern of all.
What they mean – Yes, I can explain the private constructor, static instance and getInstance method.

7.What they say – Classic OO (GoF) and J2EE patterns are same.
What they mean – I can explain Transfer Object (a.k.a Value Object) design pattern.


Design Patterns myths you know of…

  1. Design patterns are all about some Graphical editor frameworks  – This is really sad.
  2. We don’t need design patterns in our project – One school of thought.
  3. We have to use design patterns in our project – Another school of thought.
  4. Design patterns are meant only for software frameworks, not applications.
  5. Come on, we use patterns every day. I just don’t know the names.
  6. Singleton is the most important pattern of all.
  7. Classic OO (GoF) and J2EE patterns are same.

-Raj Radhakrishnan

If the following conditions are met…

Conditions:

  1. You have a software  application that looks like a comprehensive example of ‘then-current’ technologies and buzzwords (at the time it was developed).
  2. It has more than 2 pages of setup instructions. It has more than 2 pages of deployment instructions (excluding external dependencies).
  3. You couldn’t set it up on your machine in 1 hour with no or little changes (ok…..2 hours).
  4. You couldn’t build/run/test/debug its complete functionality on your local machine (even with mock  services/objects) due to various limitations.
  5. The application has configuration information in all possible ASCII forms: properties file, XML, database, environment variables (and some probably custom syntax as well). 
  6. It is very much extensible but no one really has extended it. It is very much configurable but the initial configuration never changed. It is very much reusable but it is being used only by its sole instance. 
  7. You can’t afford to just scrap your current workspace and set it up again. Your workspace is so stable now and you don’t want to touch it.

 Assumptions:

  1. Application size: small to medium
  2. Application domain: Anything but rocket science.

Conclusion:

  1. Thanks to the developers. They have already created job for some future software engineers.
  2. Not only that, they have contributed to #2 and #7 of Lehman’s laws of software evolution.
  3. Question: If there was one thing you wished all J2EE developers understood completely, what would it be? Read Rod Johnson’s wish here.

I will keep adding more conditions as I find them qualified.

-Raj Radhakrishnan

OO beginner and the Shape example

I hope every OO programmer would have come across the very famous Shape example. They are found in almost all OO books under ‘polymorphism’. Honestly I didn’t get it when I started learning C++/Java many years ago.

There are two reasons why Shape didn’t impress me.

  1. Lack of assumption of prior knowledge: The Shapes are normally part of some graphical editor frameworks that are used to build specific applications(CAD, UML editors etc). I wasn’t familiar with any graphical editor frameworks. I had no idea of what shapes and drawing they were talking about.
  2. Problem with the type of example itself: The problem is two-way:  Without having context of graphical editor frameworks, you can’t understand Shape. Without understanding Shape,  you can’t understand frameworks.

The examples had an abstract Shape and concrete Circle and Square classes with a overridden methods printing “I’m circle” and “I’m square”. The main program would look something like below.

Shape s = new Circle();
s.draw();
s = new Square();
s.draw();

There are many things involved here: Inheritance, Assignability of subclass objects to a super type reference, overriding, abstraction, interface, polymorphism etc.  To a beginner, it is nothing but “we created a Circle, so it printed something; and then we created Square, so it printed something else..what’s the big deal here?”.  Nothing more. The total point is missed entirely. So there is no way one can use this as a classic example.

To add more confusion, they show the assignment of Circle immediately followed by Square. In real world, these different objects are never created one after the other in a sequence. In fact most of the times you don’t even know how they are created.

I think the beginner example should be taught using some real-world but simple objects. It should use a real-world object and interface. It should explain by itself the relationship between an object and it’s interface. Let me try something new.

Stop..!! Don’t rush to see the  java code.  And, don’t just stop with the example.

Consider an electrical swith. It is an interface used to control the electrical appliances we have at home. The switch doesn’t give you a clue about the connected device but you can’t operate the device without using the switch. A switch has two operations: on and off. All the electrical devices are accessed using the same switch interface but they implement the operations differently. When you switch it on, you might see your room getting filled with light or cold air or music, depending on whether you have connected a lamp or fan or a music player to the switch (Don’t go too deep arguing what is the electrical socket and plug etc..:-) ).

public interface Switch{
   public void on();
   public void off();

}

We want to implement Lamp and Fan. They implement Switch interface because that’s the only way to operate them.

public class Lamp implements Switch{
   public void on(){
      System.out.println(“Bright”);
}
   public void off(){
      System.out.println(“Dark”);
   }
}

public class Fan implements Switch{
   public void on(){
      System.out.println(“Run”);
   }
   public void off(){
      System.out.println(“Stop”);
   }
}

  1. Switch s = ……………..;//we get the object somehow
  2. s.on();
  3. s.off();

I have intentionally left the RHS of line# 1  blank to illustrate that We don’t know the assigned object and we don’t care. The line numbers 1 to 5 don’t have any knowledge about the actual object that is being pointed to by the variable ‘s’. We don’t have to know if the assigned object is a Lamp or Fan as long as we can use the Switch interface to switch it on or off. This is the key to understanding runtime polymorphism.

The above example also illustrates one more important thing: Separation of  interface and implementation. The calling code (line 1-5)  uses only the Switch interface without a static binding to any particular object type (That ‘blank’ code could invoke some other method that reads from a configuration file whether to instantiate a Lamp or Fan etc – Creational Design Patterns).  This is what allows substitutability of objects. This is what we strive to achieve with polymorphism, not just printing different things.

You may have noticed that Shape is normally an abstract class in the examples whereas I have used Switch as an interface. Ignore Switch.java, Lamp.java and Fan.java. Look at the following code snippets that could use ‘Switch’ in various contexts:

  • Switch s;  (or)
  • public void operate(Switch s){…}  (or)
  • public Switch getControl(){…}

You cannot tell whether ‘Switch’ is a concrete class or abstract class or an interface. All my above explaination still holds true except different coding constructs. This is the key to understanding interfaces. I will write about it in detail in the near future.

Now it’s time to take a look at some real-world Java/J2EE.

Servlet Container:

String servletClassName = readFromWebXML();
Class servletClass = Class.forName(servletClassName);
Servlet s = servletClass.newInstance();
s.init(..);

s.service(…);

s.destroy();

 If you have programmed a Servlet,  this example should make more sense to you from the Servlet Container perspective. It’s nothing but a framework. It doesn’t know which class you have written or what you have written within it’s service() method. All it does is to load the class, instantiate and invoke the methods appropriately.

To understand these concepts and examples, you should perceive from two opposite angles: The interface side (caller) and the implementation side (callee). You should think of these two things being developed by two different sets of people (like Switches and Lamps are manufactured by two different companies. Or Universal remote controls are manufactured by Logitech whereas Sony makes TV, DVD player and home theater systems).  Tomcat,  Weblogic and Websphere all write the servlet containers and we write the Servlets. They write EJB Containers and we write EJBs. They write JMS implementations and we write Message Listeners. And finally, open source community writes Eclipse framework (Shape) and IBM Rational Software Modeler team writes ClassShape or InterfaceShape or SolidArrowShape or DottedArrowShape that would override a paint() method. I still don’t know it exactly!!.

-Raj Radhakrishnan

 

 

 

Singleton(s)

Often considered to be a ‘basic’ or ‘essential’ or ‘simple’ design pattern, I believe Singleton is the most widely used design pattern of all. There could  hardly be any OO programmer that has not worked with Singleton. Singleton in generally known as Singleton = the special private constructor + static  getInstance() method.

We know that the intent of Singleton is to have only one instance of a class (hence it’s instance variables) and provide global access to it. The static ‘instance’ ensures  the single instance within the application (/class loader). The private constructor prevents instantiation of the class from outside. The static getInstance() method provides access to the singleton instance. Normally this getInstance() the only static method defined in the class.

Ever wondered why can’t a static class (all members and methods are static) be Singleton?

Let’s say your application sends messages over a socket connection and you don’t want to keep creating connection in every part of your application per request.

public class SocketMessageSender{

private static Socket clientSocket;
private
SocketMessageSender(){}

public static void sendMessage(Message m) {….code to write into clientSocket..}

}

Client code:

SocketMessageSender.sendMessage(new Message(“Hello World”));

You can’t instantiate this class because of the private constructor. There could be only one copy of ‘clientSocket’ as it is static. There is no need for getInstance() method as all the methods can be accessed without an instance. In fact, there is no  Singleton object in this case at all. But, why aren’t Singletons implemented this way?

Because, static methods cannot form an interface; they can not be overridden; and hence, they can’t be polymorphic.

You know that to be able to substitute ‘objects’ (as opposed to classes), you need to program to interfaces i.e. there has to be an interface in the first place (again, I don’t just mean java ‘interface’ construct). Consequently the methods will be non-static.

What this simply means is you cannot easily change SocketMessageSender with a new MQMessageSender. You have to find/replace all the code that uses this  SocketMessageSender to MQMessageSender. Even if you want to extend SocketMessageSender and override sendMessage(), it’s not possible since the method is static.

Programming to a Singleton’s interface promotes substitutability of objects that implement it. There can be multiple implementations of a Singleton interface. The interface could be provided by an abstract or concrete class or, an interface (now I mean language construct) itself. Instead of returning it’s own object, it can return it’s subtype objects. What we are talking about here is nothing but programming to an interface while keeping the implementaton to be a Singleton.

The Singleton implementations I have seen are always concrete classes that just return their own objects. Nothing more, nothing less. It’s like a standard template…even if subclassing in the future is required (That’s fine, We can change the code when required!!).

Following is a possible implementation of a generic MessageSender (not yet Singleton).

public class MessageSender{

private static MessageSender sender;

protected MessageSender(){}

public static MessageSender getInstance(){ return sender;}

public void sendMessage(Message m){..default implementation – do nothing or throw exception..etc..}

}

The above class serves two purposes:

  1. It provides an interface with sendMessage() – as mentioned earlier, this can be an abstract or concrete class or a pure interface as well.
  2. It stores a Singleton instance of any class that that is of its own type.

Note the constructor is declared protected to allow sub-classing.

The following are example implementations of MessageSenders.

public class SocketMessageSender extends MessageSender{
     private Socket clientSocket;
     protected SocketMessageSender (){…//initialize clientSocket..}
  
     public void sendMessage(Message m) {….clientSocket.write(…)..}
}

public class MQMessageSender extends MessageSender{
     private MessageQueue queue;
     protected MQMessageSender (){…//initialize queue connections..}

     public void sendMessage(Message m) {….queue.send(…)..}
}
 

The clients need to invoke getInstance() method on MessageSender class.

MessageSender sender = MessageSender.getInstance();//we don’t know the type of current object and we don’t care
sender.sendMessage(new Message(“Hello world!”));//polymorphic
 

The clients dont’ actually know whether the messages are sent using sockets or message queues. All they know is only the MessageSender’s interface. Without affecting them, you can always swap between SocketMessageSender to MQMessageSender and vice versa.

This allows us to implement polymorphic Singletons.

But where is the code that instantiates the appropriate class? How is the instance assigned to sender variable of MessageSender class?

  • Singleton super class responsibility:

The MessageSender provides a static method to configure the singleton instance.

public static void register(MessageSender s){
    sender = s;
}

  • Implementation class responsibility

The concrete classes can register their own instance with MessageSender. This is the only approach if SocketMessageSender’s constructor is private.

SocketMessageSender:

static{
SocketMessageSender s = new SocketMessageSender();
MessageSender.register(s);}
}

  • Alternatively, there could be a separate class that reads from a configuration file the name of the implementation class (during startup), instantiates it and configures it with MessageSender. This class should be part of the same package as the implementation class if the constructor is protected.

If you really notice, MessageSender acts as a Registry of MessageSender concrete implementations. It can be even made more generic to hold references of different Singletons like MessageSender, EmailSender, AlertSender etc whose instances are configured by respective classes or a ConfigurationManager class. The idea is still be extended to have a common registry of all Singletons – yes, now you recall JNDI – the bind() and lookup() calls!!!

This is what happens with the following line I mentioned in my earlier post – What I like about the 3 lines Java XML parsing?

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

I believe now you too really start liking the 3 lines..Not only that…we have seen many more examples like that.

  • What do you think that happens when you say Class.forName(“jdbc.odbc…..”)? You cause the static block intialization of the driver class so that it registers it’s own object with DriverManager.
  • DocumentBuilderFactory.newInstance() returns system’s default parser factory. If in case a different parser is specified through system properties, it returns an object of that.
  • All your InitialContext.lookup(“DataSource or JMSConnectionFactory…”) – you acquire a reference to Singletons from registry and you access them through their interfaces. These are instantiated and configured into the registry by the Server start up classes.

Yes, our Singleton guy is little more than just a private constructor…

-Raj Radhakrishnan