Factory pattern is creational pattern which hides object creation logic from user. We can see one example of factory patter for clear understanding. To execute your factory pattern use following steps:-
1. Create interface called Car as given below. It will be common reference to all Car objects that we are going to create.
public interface Car {
void myCar();
}
2. Now create one concreet class called Bmw. This class will be implementing interface Car.
public class Bmw implements Car {
public void myCar() {
System.out.print("\nBmw is my car.");
}
}
3. Now create another concreet class called Tata. This class will be implementing interface Car.
public class Tata implements Car {
public void myCar() {
System.out.print("\nTata is my car.");
}
}
4. Now create one more class called Maruti. Thisclass will be implementing interface Car.
public class Maruti implements Car {
public void myCar() {
System.out.print("\nMaruti is my car.");
}
}
5. Now you have to create one more class called CarFactory as given below.
public class CarFactory {
public Car getCar(String carName) {
if(carName.equalsIgnoreCase("Tata"))
return new Tata();
else if(carName.equalsIgnoreCase("Maruti"))
return new Maruti();
else if(carName.equalsIgnoreCase("Bmw"))
return new Bmw();
return null;
}
}
6. Now our pattern is ready. Let's write one class to implement this pattern.
public class CarShop {
public static void main(String args[]) {
CarFactory cf = new CarFactory();
Car c1 = cf.getCar("Tata");
c1.myCar();
c1 = cf.getCar("Maruti");
c1.myCar();
}
}
Here you are ready to execute your application.
Now you can see that if you want to add one more car to shop you just need to add one more class implementing Car interface and you are done. In this was this pattern provides flexibility and hides creational logic from user.
No comments:
Post a Comment