Creating Objects Using a Factory


The Factory pattern is a solution to the problem of not having to use the new keyword. You use the Factory pattern when you want to create an instance of an interface or abstract class using patterns. A helper class will instantiate an object for you, saving you the trouble of instantiating it yourself. The helper class creates an implicit instantiation where the consumer simply uses the helper class and expects everything to work properly. In the simplest case, the indirection would appear similar to Listing 3.4.

Listing 3.4
start example
 class SharedFactory { public static InterfaceToBeShared createObject() { return new SomeFunctionality(); } } 
end example
 

In Listing 3.4, the class SharedFactory has a static method createObject that instantiates the specific object and then returns the supported interface. Rewriting Listing 3.3 to use the factory would result in Listing 3.5.

Listing 3.5
start example
 InterfaceToBeShared interf =  SharedFactory.createObject(); interf.availability(); 
end example
 

In Listing 3.5, to get an interface instance the consumer of the interface InterfaceToBeShared would only need to use the shared class SharedFactory and then call the method createObject . We now ask ourselves if we have achieved anything. In Java programming terms, nothing much has changed. The class SomeFunctionality has been replaced with the class SharedFactory , which means a hard reference still exists. However, complexity has been added because there is now an intermediate class. In a way, we might think that it's no longer possible to maintain the code.

The code is not more complex, but simpler. The reason is related to the fact that, in terms of linkage change, the class SharedFactory will be written once and will never change again. In the implementation of SharedFactory , a different implementation may be instantiated , but the client code does not care about this. The client that uses the classes cares only that the linkage changes as little as possible. Listing 3.5 is an illustration of when the linkage changes very little, even though the implementation does change. As you will remember from Chapter 2, the key to good code is to be able to separate the linkage from the implementation, as demonstrated by the Commons Bridge best practice.




Applied Software Engineering Using Apache Jakarta Commons
Applied Software Engineering Using Apache Jakarta Commons (Charles River Media Computer Engineering)
ISBN: 1584502460
EAN: 2147483647
Year: 2002
Pages: 109

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net