Abstract factory pattern (Java)
From LiteratePrograms
This program is under development.
Please help to debug it. When debugging
is complete, remove the {{develop}} tag.
The abstract factory pattern provides a client with an interface for creating related or dependent objects without specifying their concrete classes.
In the abstract factory pattern there are five roles:
- Abstract factory
- Concrete factory
- Abstract product
- Concrete product
- Client
The abstract factory declares the methods that create products.
<<AbstractFactory.java>>= public abstract class AbstractFactory { public abstract A createProductA(); public abstract B createProductB(); }
The concrete factory extends the abstract factory and implements the creation methods declared in the abstract factory
<<AbstractFactory.java>>= class ConcreteFactory extends AbstractFactory { public A createProductA() { return new ConcreteA(); } public B createProductB() { return new ConcreteB(); } }
We also have to declare the abstract products which we want the abstract factory to produce.
<<AbstractFactory.java>>= abstract class A { } abstract class B { }
The implementations of the abstract products are called concrete products, these are created by the concrete factories.
<<AbstractFactory.java>>= class ConcreteA extends A { } class ConcreteB extends B { }
To use all the above code we need a client which is hopefully interrested in our abstract products. Note that this is where we instantiate the factory with the concrete factory of our choice. If we later want another implementation of the abstract factory we only need to change one line of code.
<<AbstractFactory.java>>= class Client { public void init() { AbstractFactory factory = new ConcreteFactory(); A abstractA = factory.createProductA(); B abstractB = factory.createProductB(); // do something useful with {A,B} } }
TODO: Example with data access object creations where the client asks the abstract factory for a data access object implementation. There will be two different data access object classes, one using memory storage and one using the Java serialization to file abilities.