Factory
pattern comes under creational pattern as this pattern provides one
of the best ways to create an object. Factories handles the details
of object creation.
Factory
pattern encapsulate object creation logic which makes it easy to
change it later when you change how object gets created or you can
even introduce new object with just change in one class. Factories
handle the details of object creation.
Lets
say we have a car factory, where depends on your user requirements,
you build car models like small, Large, Luxury car etc.,
public interface Car { void buildCar(); }
public class SmallCar implements Car{ public void buildCar(){ System.out.println("Building small car"); } }
public class MidsizeCar implements Car{ public void buildCar(){ System.out.println("Building Midsize car"); } }
public class LargeCar implements Car{ public void buildCar(){ System.out.println("Building Large car"); } }
public class LuxuryCar implements Car{ public void buildCar(){ System.out.println("Building Luxury car"); } }
public class SportsCar implements Car{ public void buildCar(){ System.out.println("Building Sports car"); } }
public class CarFactory { public Car getCar(String type){ switch (type) { case "small": return new SmallCar(); case "midsize": return new MidsizeCar(); case "large": return new LargeCar(); case "luxury": return new LuxuryCar(); case "sports": return new SportsCar(); default: return null; } } }
public class FactoryPatternDemo { public static void main(String args[]){ CarFactory factory = new CarFactory(); Car myCar = factory.getCar("small"); myCar.buildCar(); myCar = factory.getCar("sports"); myCar.buildCar(); } }
Output
Building small car Building Sports car
Advantages
- If you code for an interface, then it will work with any new classes implementing this interface through Polymorphism.
- We can use getCar method of CarFactory class in number of places like may be you car factory may have many clients, they can simply use this class.
- Even change to add new cars, are remove old cars only reflects changes in one class, I.e, ' CarFactory' class.
- You can make the ' getCar' method of 'CarFactory' as static, but one disadvantage is that you can't sub class and change the behavior of 'getCar' method.
No comments:
Post a Comment