Design Patterns: Factory
Today I will continue the articles from “Design Pattern: Java interpretation” series. A main hero of the post will be Factory pattern. It’s one of the most popular creational patterns. The main aim of the Factory pattern is creation instances of classes depending on passed argument.
Now I need to describe how actually the pattern works. All instances of classes which Factory can produce should be subclass of some class or implement one interface. As the result a client doesn’t need to know which instances can be produced by the Factory. The knowledge of parent class / interface will be enough to work with the Factory.
Let’s see the example of the Factory pattern:
public interface DataStorage { public void getStorageName(); }
Implementations of the DataStorage interface:
public class CDR implements DataStorage { @Override public void getStorageName() { System.out.println("This is CD-R"); } }
And
public class CDRW implements DataStorage { @Override public void getStorageName() { System.out.println("This is CD-RW"); } }
Class of the Factory:
public class DataStorageFactory { public DataStorage createDataStorage(String type) { if (type.equals("CDR")) return new CDR(); else return new CDRW(); } }
Let’s see how this code can work:
public class Testoid { public static void main(String[] args) { DataStorageFactory dsFactory = new DataStorageFactory(); DataStorage storage1 = dsFactory.createDataStorage("CDR"); DataStorage storage2 = dsFactory.createDataStorage("CDRW"); storage1.getStorageName(); storage2.getStorageName(); } }
The output will be like this:
This is CD-R This is CD-RW
The Factory pattern should be applied in that places where you need to encapsulate creation of instances. It can be useful when instantiation of object is too complicated to create it each time manually. This is one of the Factory advantages.