Factory pattern is one of most used design pattern in Java, and it defines an interface to create the object without exposing the creation logic to the client, and has internal logic to decide which class to instantiate.
TrackingAgent interface
1 2 3 4 5 6 7 |
package net.tecbar.designpattern.factory; public interface TrackingAgent { void trackPackage(String trackingNo); } |
Concrete Tracking Agents
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.factory; public class DHLTrackingAgent implements TrackingAgent { @Override public void trackPackage(String trackingNo) { System.out.println("DHL agent tracks " + trackingNo); } } |
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.factory; public class FedexTrackingAgent implements TrackingAgent { @Override public void trackPackage(String trackingNo) { System.out.println("FedEx agent tracks " + trackingNo); } } |
1 2 3 4 5 6 7 8 9 10 11 |
package net.tecbar.designpattern.factory; public class UPSTrackingAgent implements TrackingAgent { @Override public void trackPackage(String trackingNo) { System.out.println("UPS agent tracks " + trackingNo); } } |
Factory Class
An application usually needs only one instance of the Factory class. This means that it is best to implement it as a Singleton or a class with static method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package net.tecbar.designpattern.factory; public class TrackingAgentFactory { public static TrackingAgent getTrackingAgent(String agent) { if("ups".equalsIgnoreCase(agent)) { return new UPSTrackingAgent(); } if("fedex".equalsIgnoreCase(agent)) { return new FedexTrackingAgent(); } if("dhl".equalsIgnoreCase(agent)) { return new DHLTrackingAgent(); } throw new RuntimeException("Not supported agent"); } } |
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package net.tecbar.designpattern.factory; public class FactoryDemo { public static void main(String[] args) { TrackingAgent agent = TrackingAgentFactory.getTrackingAgent("DHL"); agent.trackPackage("576954654"); agent = TrackingAgentFactory.getTrackingAgent("UPS"); agent.trackPackage("1Z657576954654"); agent = TrackingAgentFactory.getTrackingAgent("FedEx"); agent.trackPackage("679676576"); } } |
Output
DHL agent tracks 576954654
UPS agent tracks 1Z657576954654
FedEx agent tracks 679676576
Pingback: Software Design Patterns