Design Mode---Factory mode

Source: Internet
Author: User

看了些教程和相应的代码,网上又看了些博客,主要是想了解这种思想,下面从代码的演进来说明三种工厂模式.

The factory model is divided into three categories in Java and mode:
1) Simple Factory mode (simply Factory): not conducive to the production of products;

2) Factory method mode (Factory): Also known as the polymorphism plant;

3) Abstract Factory mode (abstract Factory): Also known as the toolbox, producing product families, but not conducive to the production of new products;
These three modes are progressively abstracted from top to bottom and more general.
In design mode, GOF divides the factory model into two categories: The Factory method Model (Factory) and the Abstract Factory mode (abstraction Factory). The simple Factory is seen as a special case of the factory method pattern, which is grouped into one category.

案例:pizza店有CheesePizza和GreekPizza,有一个PizzaStore,通过OrderPizza来销售这两种Pizza.
A. Simple Factory mode
简单来说就是定义实例,封装创建对象的代码,把不动的代码和会动的代码分开
//Simple factory code that encapsulates the creation of Orderpizza in this class Createpizza//The purpose of this is to separate the code that will be changed, such as the possibility of adding new types of pizza, which can be changed directly here. Public classsimplepizzafactory { PublicPizzaCreatepizza(String OrderType) {Pizza Pizza =NULL;if(Ordertype.equals ("Cheese") {Pizza =NewCheesepizza (); }Else if(Ordertype.equals ("Greek") {Pizza =NewGreekpizza (); }Else if(Ordertype.equals ("Pepper") {Pizza =NewPepperpizza (); }returnPizza }}

Encapsulated Orderpizza

//Inside the main package pizza production methods (This demo think pizza production method), through the factory class to achieve the creation of different pizza Public classOrderpizza {simplepizzafactory msimplepizzafactory; Public Orderpizza(Simplepizzafactory msimplepizzafactory)    {setfactory (msimplepizzafactory); } Public void setfactory(Simplepizzafactory msimplepizzafactory) {Pizza Pizza =NULL; String OrderType; This. msimplepizzafactory = Msimplepizzafactory; Do{OrderType = GetType (); Pizza = Msimplepizzafactory.createpizza (OrderType);if(Pizza! =NULL) {Pizza.prepare ();                Pizza.bake ();                Pizza.cut ();            Pizza.box (); }        } while(true); }PrivateStringGetType() {Try{BufferedReader Strin =NewBufferedReader (NewInputStreamReader (System.inch)); System. out. println ("Input Pizza type:"); String str = strin.readline ();returnStr }Catch(IOException e) {E.printstacktrace ();return ""; }    }}

Here's the pizzastore for a direct meal.

publicclass PizzaStroe {    publicstaticvoidmain(String[] args) {        SimplePizzaFactory mSimplePizzaFactory;        OrderPizza mOrderPizza;        mOrderPizza=new OrderPizza(new SimplePizzaFactory());    }}
目前扩大经营,需要在London开设分店,那么原程序就很难维护,几乎需要重写,所以引进工厂方法模式
Two. Factory method mode
定义创建对象的抽象方法,由子类决定要实例化的类

Set Orderpizza as an abstract class, Createpizza is set as an abstract method, so each branch inherits Orderpizza will create its own Createpizza method

//defined as abstract class Public Abstract classOrderpizza { Public Orderpizza() {Pizza Pizza =NULL; String OrderType; Do{OrderType = GetType ();            Pizza = Createpizza (OrderType);            Pizza.prepare ();            Pizza.bake ();            Pizza.cut ();        Pizza.box (); } while(true); }//This requires a subclass implementation of the abstract method    AbstractPizza Createpizza (String ordertype);PrivateStringGetType() {Try{BufferedReader Strin =NewBufferedReader (NewInputStreamReader (System.inch)); System. out. println ("Input Pizza type:"); String str = strin.readline ();returnStr }Catch(IOException e) {E.printstacktrace ();return ""; }    }}

The realization of Londonpizza

publicclass LDOrderPizza extends OrderPizza {    @Override    Pizza createPizza(String ordertype) {        null;        if (ordertype.equals("cheese")) {            new LDCheesePizza();        elseif (ordertype.equals("pepper")) {            new LDPepperPizza();        }        return pizza;    }}

Pizzastore

publicclass PizzaStroe {    publicstaticvoidmain(String[] args) {        OrderPizza mOrderPizza;        mOrderPizza=new NYOrderPizza();    }}
Three. Abstract Factory mode
定义一个接口,用于创建相关或有依赖关系的对象族,无需明确具体类.

Create abstract factories and abstract Createpizza.

publicinterface AbsFactory {    publicCreatePizza(String ordertype) ;}

Orderpizza the current abstract factory as an object, create a pizza

 Public classOrderpizza {absfactory mfactory; Public Orderpizza(Absfactory mfactory)    {setfactory (mfactory); } Public void setfactory(Absfactory mfactory) {Pizza Pizza =NULL; String OrderType; This. mfactory = mfactory; Do{OrderType = GetType (); Pizza = Mfactory.createpizza (OrderType);if(Pizza! =NULL) {Pizza.prepare ();                Pizza.bake ();                Pizza.cut ();            Pizza.box (); }        } while(true); }PrivateStringGetType() {Try{BufferedReader Strin =NewBufferedReader (NewInputStreamReader (System.inch)); System. out. println ("Input Pizza type:"); String str = strin.readline ();returnStr }Catch(IOException e) {E.printstacktrace ();return ""; }    }}

Specific to each pizza, it is necessary to implement an abstract factory interface

public   Class  ldfactory  implements  absfactory  {  @Override   Public  Pizza createpizza  (String ordertype) {Pizza Pizza = null ; if  (Ordertype.equals ( "cheese" )) {pizza = new  Ldcheesepizza (); } else  if  (ordertype.equals (" Pepper ")" {pizza = new  Ldpepperpizza (); } return  pizza; }}

Pizzastore directly Create

publicclass PizzaStroe {    publicstaticvoidmain(String[] args) {        OrderPizza mOrderPizza;        mOrderPizza=new OrderPizza(new LDFactory());    }}
Four. Summary
(1)简单工厂模式是由一个具体的类去创建其他类的实例,父类是相同的,父类是具体的。 (2)工厂方法模式是有一个抽象的父类定义公共接口,子类负责生成具体的对象,这样做的目的是将类的实例化操作延迟到子类中完成。 (3)抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无须指定他们具体的类。它针对的是有多个产品的等级结构。而工厂方法模式针对的是一个产品的等级结构。
Five. Supplement
依赖抽象原则1.变量不要持有具体类的引用,比如CheesePizza = new CheesePizza (),这样就不太好.2.不要让类继承自具体类,要继承抽象类或者接口,这个主要是便于维护.3.不要覆盖基类已实现的方法,基类实现的应该是程序的通性,覆盖的话会使其失去其意义

Of course, the specific situation of concrete treatment

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Design Mode---Factory mode

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.