Design Mode Reading Notes-workshop method mode

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.