Factory method
The factory method uses inheritance. The object creation is delegated to the subclass, And the subclass determines which one to instantiate.
Put the same method together.
Abstract Product factoryMethod (String type)
Factory methods are abstract;
A product object must be returned;
You must input a type to determine which object to create;
This method is implemented after the class is inherited.
Example of modifying the factory method in the workshop method mode:
Put createPizza back in PizzaStore, but declare it as an abstract method, implemented by a specific inherited class.
The modified PizzaStore class:
Public abstract class PizzaStore {
Abstract Pizza createPizza (String item );
Public Pizza orderPizza (String type ){
Pizza pizza = createPizza (type );
System. out. println ("--- Making a" + pizza. getName () + "---");
Pizza. prepare ();
Pizza. bake ();
Pizza. cut ();
Pizza. box ();
Return pizza;
}
}
Inherit the PizzaStore class, implement the createPizza class, and return the specific Pizza.
Public class ChicagoPizzaStore extends PizzaStore {
Pizza createPizza (String item ){
If (item. equals ("cheese ")){
Return new chicagstylecheesepizza ();
} Else if (item. equals ("veggie ")){
Return new chicagstyleveggiepizza ();
} Else if (item. equals ("clam ")){
Return new chicagstyleclampizza ();
} Else if (item. equals ("pepperoni ")){
Return new chicagstylepepperonipizza ();
} Else return null;
}
}
The factory method is to create a class by sub-class and build a platform between the product and the product creator.
It is different from a simple factory. A simple factory is a method for encapsulating the creation class. You cannot change the product you are creating. The factory method provides a framework that dynamically determines how to create a product by subclass.
The factory method is more suitable for more product categories, and each category has different types. The product to be instantiated has different features.