The Zen Factory method pattern of design pattern

Source: Internet
Author: User
Tags getcolor

Definition of a factory method pattern: Defines an interface for creating an object, letting subclasses decide which class to instantiate. The factory method defers the instantiation of a class to a subclass

Example: Nu wa through the gossip stove made white, yellow, black people.
See Code:

//工厂要生产的人的接口publicinterface Human{//有两个方法    publicvoidgetColor();    publicvoidtalk();}
//blacks   Public  class   Blackhuman  implements  human  { Span class= "hljs-annotation" > @Override  public  void  getcolor     () {System.out.println ( "Black skin is Dark" ); }  @Override  public  void  talk  () {System.out.println ("; }}
//blacks   Public  class   Yellowhuman  implements  human  { Span class= "hljs-annotation" > @Override  public  void  getcolor     () {System.out.println ("); }  @Override  public  void  talk  () {System.out.println ("; }}
//白种人publicclass WhiteHuman implements Human {    @Override    publicvoidgetColor() {        System.out.println("白种人的皮肤是白色的");    }    @Override    publicvoidtalk() {        System.out.println("白种人人会说话,一般说的都是单子节");    }}

The following code uses the generic

//抽象人类创建工厂,泛型限定了输入参数必须是Class类型、必须是Human的实现类publicabstractclass AbstractHumanFactory {    publicabstractcreatHuman(Class<T> c);}
//Human creation factory Public  class humanfactory extends abstracthumanfactory {    @Override     Public<t extends Human> TCreathuman(class<t> c) {//TODO auto-generated method stubHuman Human =NULL;Try{human = (human) class.forname (C.getname ()). Newinstance (); }Catch(Exception e) {System.out.println ("Human production error");        E.printstacktrace (); }return(T) Human; }}

OK, now let's think about Nu WA will give the gossip stove what kind of production orders? Should be "Give me a yellow race", and not "give me to produce a will walk, will run, speak, the skin is yellow person", because such orders increase the cost of communication, as a production manager, as long as the production of what can be, and do not need to make the specific information of the error.

Now Nu WA is working.

The following code uses the reflection mechanism. I wrote the reflection mechanism of the blog was deleted by me ... But this code is quite simple and understandable. The reflection mechanism here is also a very important application of reflection.

public class Nvwa {public static void main (string[] args) {abstracthumanfactory Yinyanglu = new Humanfactory ();System. out. println("--the first people to make a white race.");Human Whitehuman = Yinyanglu. Createhuman(Whitehuman. Class);Whitehuman. GetColor();Whitehuman. Talk();System. out. println("--the second group of people created is black race.");Human Blackhuman = Yinyanglu. Createhuman(Blackhuman. Class);Blackhuman. GetColor();Blackhuman. Talk();System. out. println("--the first people who made the yellow race.");Human Yellowhuman = Yinyanglu. Createhuman(Yellowhuman. Class);Yellowhuman. GetColor();Yellowhuman. Talk();}}

What, is not spicy ash often simple ~
The following is a more practical, easy-to-expand framework for the factory model, which allows readers to expand according to the actual project needs.

//Abstract Product class   Public  abstract  class  product{public  void  method1  () {//business logic processing } //abstract method  public  abstract  void  method2  ();}  
//specific product class   Public  class   ConcreteProduct01  extends  product  {  public  void   Method2  () {//business logic Processing }}----------public class  concreteproduct02  extends  product  { public  void  method2  () { Span class= "hljs-comment" >//business logic Processing }}  
//抽象工厂类publicabstractclass Creator{    /*    *创建一个产品对象,其输入参数类型可以自行设置    *通常为String、Enum、Class等,当然也可以为空    /*    //输入参数类型是Class,用的反射机制    public abstract <T extends Product> T createProduct(Class<T> c);    /*    *为了让大家知道为什么用反射机制,这里添加一种输入类型是String的比较一下    pubic abstract <T extends Product> T creatProduct(String productname);    */}
//Specific factory class Public  class contretecreator extends Creator{     Public<t extends Product> Tcreateproduct(class<t> c) {Product Product =NULL;Try{Product = (product) class.forname (C.getname ()). Newinstance (); }Catch(Exception e) {System.out.println ("Product creation failed.");        E.printstacktrance (); }    }/*public <t extends product> T createproduct (String ProductName) {product Product = NULL; try{//Reflection mechanisms can avoid these tedious judgments.            And if you write this, you have a new product class, you also need to modify the code, poor evaluation ~ if (ProductName = = "PRODUCTNAME01") Product = new ConcreteProduct01 ();        else if (ProductName = = "Productname02") Product = new ConcreteProduct02 ();            }catch (Exception e) {System.out.println ("Product creation failed");        E.printstacktrance (); }    }    */}
//场景类publicclass Client{    publicstaticvoidmain(String[] args){        new ConcreteCreator();        Product product = creator.createProduct(ConcreteProduct1.class);    }}

The basic code of the factory method pattern is these, let's take a look at its advantages

1, first, good packaging, code structure is clear. A caller needs a specific product object, as long as it knows the product's class name (or the string you use).
2. The encapsulation of the factory method pattern is excellent. In the case of adding a product class, "embrace change" can be accomplished as long as the specific factory class is modified appropriately (without modification by the reflection mechanism) or extended to a factory class.
3, shielding products category. Product class How to change, as long as the product interface is not the same as we have no relationship.
4. Finally, the Factory mode method is a typical decoupling framework. The high-level module only needs to know the product abstract class, other does not care, conforms to the Dimitri Law. Relies on the abstraction of the product class only, conforming to the dependency inversion principle. The product subclass is used to replace the product parent class, which also conforms to the Richter replacement principle.

It's not over!

Workers

Expansion of plant method model
1, reduced to simple Factory mode. If there is only one factory, then we do not need the abstract factory, the product class does not need to change, and this unique factory method is set to static

publicclass HumanFactory{    //这里是    publicstaticcreateHuman(Class<T> c){    null;        try{            human = (Human)Class.forName(c.getName()).newInstance();        }catch(Exception e){            System.out.println("人类生产错误");            e.printStackTrace();        }        return (T)human;}}

2. Upgrade to multiple factory classes
When we are working on a more complex project, we often encounter an effort to initialize an object, and all product classes are initialized in a factory method, and the code structure is not clear. For example, if a product class has 5 implementations, the initialization of each implementation class (not just new, but also setting the initial value of the object) is not the same, and if written in a factory method, it is bound to cause the method class to be extremely large.

What do we do?

Each product has its own factory and initializes itself in its own factory. The meaning is relatively simple, no longer add code, try it yourself ~

The Zen Factory method pattern of design pattern

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.