Intent of factory method :
Define an interface for creating an object, but let subclasses decide which class
to instantiate. Factory Method lets a class defer instantiation to subclasses.
Assume an online banking system using two different sms gateway to deliver mobile banking notification to it's valued customers.System need to resolve which gateway will use by cell number assume hear gateway type. Based on category or need system need to create or return object/instance of a gateway. Hear is the practical example :
Gateway type enumeration :
package com.thinktank.rnd.se.pattern.factorymethod; public enum GatewayType { ONE(1), TWO(2); private int value; private GatewayType(int value) { this.value = value; } };Gateway interface :
package com.thinktank.rnd.se.pattern.factorymethod; public interface GateWay { public int connectToGateWay(); }Implementation of gateway interface :
package com.thinktank.rnd.se.pattern.factorymethod; public class SmsGatewayOne implements GateWay { public int connectToGateWay() { System.out.println("Connection Established With Gateway One"); return 1; } }Another implementation of gateway interface :
package com.thinktank.rnd.se.pattern.factorymethod; public class SmsGatewayTwo implements GateWay { public int connectToGateWay() { System.out.println("Connection Established to Gateway Two"); return 1; } }Gateway factory class :
package com.thinktank.rnd.se.pattern.factorymethod; public class GatewayFactory { public GateWay getGateway(GatewayType gatewayType) { switch (gatewayType) { case ONE: return new SmsGatewayOne(); case TWO: return new SmsGatewayTwo(); } return null; } }Main class for our factory method demo :
package com.thinktank.rnd.se.pattern.factorymethod; public class DemoFactoryMethod { public static void main(String args[]) { GatewayFactory gatewayFactory = new GatewayFactory(); GateWay gateWay = gatewayFactory.getGateway(GatewayType.TWO); gateWay.connectToGateWay(); } }
Use the Factory Method pattern when
· a class can't anticipate the class of objects it must create.
· a class wants its subclasses to specify the objects it creates.
· classes delegate responsibility to one of several helper subclasses, and
you want to localize the knowledge of which helper subclass is the delegate.
Reference :
Design-patterns-elements-reusable-object-oriented
http://en.wikipedia.org/wiki/Design_Patterns
http://java.dzone.com/articles/design-patterns-factory
http://javapapers.com/design-patterns/factory-method-pattern/
http://en.wikipedia.org/wiki/Factory_method_pattern