Thursday, November 1, 2007

Example of the Adapter Pattern

The adapter pattern was another pattern that I felt I've seen before, the first thing that came to mind were event listeners. I then searched through the Java 1.5 API and found a class that works as an adapter, WindowAdapter. The point of the adapter pattern is to convert the interface of a class into another interface that the client expects. In the case of WindowAdapter, WindowAdapter would be the adapter with an interface the client expects. Within WindowAdapter, there are various methods such as windowClosed and windowOpened, these are the methods that make calls to the Adaptee. So the client makes a call where the adapter then calls the method of the adaptee. This way you can use an existing class when its interface doesn't match the class that is needed.

Example of the Factory Method Pattern

After reading about the factory method pattern, nothing that I have done in the past really jumped out at me so I decided to look through the Java 1.5 API and found an example of a class that follows the factory method pattern. This class wasn't to hard to find since the name has "Factory" in it, ObjectFactory. The actual method in the ObjectFactory class that follows the factory method pattern is getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment), which returns an object. The point of the factory method pattern is to create objects without specifying the exact class of object that will be created. This method is used to allow subclasses to choose which type of object to create.