Simple factory, factory method and abstract factory

Source: Internet
Author: User

Simple Factory, factory method and abstract factory are all design pattern creation type, strictly the simple factory does not belong to one of the design patterns (contrary to the opening and shutting principle), this article in order to fully describe the three plant evolution process, The three factories were summarized and studied, and their advantages and disadvantages were summed up by comparing the characteristics of the three.

First, simple factory:

Before the factory, everyone is self-sufficient, the production of a car or other tools are to complete their own, with the factory, tell it needs will come out of the corresponding products, but the level of production is low, the factory division of labor is not clear, the community only a factory, whether the truck or the bus is done by it, Equivalent to a factory of multiple production lines.

Class Diagram:


Code:

/**********************************************************************************     * Developer: 李立平     * Development Group:     * Class Description: Simple factory class for the production of various cars     * Development time: 2015/8/20 16:05:29     * Development version: V4.0.0    ************************************ /using system;using system.collections.generic;using System.Linq; Using System.text;namespace simplefactory{    class carfactory    {public        static Car Createcar (String type)        {            car car = null;            Switch (type)            {case                "bus":                    car=new Bus ();                    break;                Case "Truck":                    car=new Truck ();                    break;            }            return car;}}}    
/****************************************************************************** * Developer: Li Liping * Development Group: * Class Description: Car abstract class, there are buses, trucks, etc., there is the virtual method of production vehicles * Development time: 2015/8/20 16:06:03 * Development: V4.0.0 * * * * * /using system;using System.collections.generic;using system.linq;using system.text;namespace simplefactory{public class Car {pub Lic virtual void Getcar () {}}} 
/**********************************************************************************     * Developer: 李立平     * Development Group:     * Class Description: One of the specific classes of cars, bus     * Development time: 2015/8/20 16:06:39     * Development version: V4.0.0    *************************************** /using system;using system.collections.generic;using system.linq;using System.text;namespace simplefactory{    Public  class Bus:car    {public        override void Getcar ()        {            Console.WriteLine ("Produce a bus! ");        }    }}
Using system;using system.collections.generic;using system.linq;using system.text;namespace SimpleFactory{    Class Client    {        static void Main (string[] args)        {            car car;            Car = Carfactory.createcar ("Bus");//need to produce bus            car. Getcar ();}}}    

Benefits: The factory class contains logical judgments, based on the client instantiation of the relevant classes, to remove the dependency on the specific product, the client regardless of which class instances, the requirements to the factory, the factory to create a separate instance. Is the advantage is also insufficient.

Insufficient: If you add a product, you need to modify the factory class, violating the open/closed principle. The emergence of factory methods solves this confusion ...

Second, the factory method:

With the increase of specialization, the factory division of labor became clear, each factory production of their own products, bus factories to produce buses, trucks factory is responsible for the production of trucks, so if there is a new product demand, directly add the corresponding product class and corresponding factory class can be.

Class Diagram:


Code: Unlike a simple factory, there is an abstract factory interface, and the specific factory class implements it. The client also instantiates the specific factory class (which is the parent class at the time of declaration).

Using system;using system.collections.generic;using system.linq;using system.text;namespace AbstractFactory{    Interface Ifactory    {        Car createcar ();}    }
/**********************************************************************************     * Developer: 李立平     * Development Group:     * Class Description: Bus Factory     * Development time: 2015/8/20 16:25:07     * Development version: V4.0.0    ****************************************** /using system;using system.collections.generic;using system.linq;using System.text;namespace abstractfactory{    class busfactory:ifactory     {public        Car Createcar ()        {            return new Bus ();}}    
/**********************************************************************************     * Developer: 李立平     * Development Group:     * Class Description: Client, e.g. need a bus     * Development time: 2015/8/20 16:06:39     * Development version: V4.0.0    ************************************* /using system;using system.collections.generic;using System.Linq; Using System.text;namespace abstractfactory{    class Client    {        static void Main (string[] args)        {            Ifactory factory = new Busfactory ();//instantiation of bus factory            car car = factory. Createcar ();   The bus factory created the bus            car. Getcar ();}}}    

Benefits: Adhere to the open and close principle, directly add specific product classes and corresponding factory classes, instantiate which factory is placed on the client

Insufficient: First: Add a product will add a product factory class, additional development, second: the Simple factory internal logic to move to the client, so before modifying the factory class, now modify the client, the problem is still there, the emergence of the abstract factory ...

Three, abstract factory:

The factory method solves the problem that the simple factory violates the open and close principle, but it each factory can produce only one kind of product, for the series of products expresses helpless, and everybody sees the factory can benefit, with the factory increases, the user's demand, then has the brand concept, for example wants the BMW truck, the Mercedes-Benz bus and so on.

Class Diagram:


Code:

/**********************************************************************************     * Developer: 李立平     * Development Group:     * Class Description: Car abstract class, there are buses, trucks, etc., there is the virtual method of production vehicles     * Development time: 2015/8/20 16:06:03     * Development version: V4.0.0    ************************* /using system;using system.collections.generic;using system.linq;using system.text;namespace abstractfactory{Public    class Bus    {public        virtual void Getcar ()        {        }    }}
/****************************************************************************** * Developer: Li Liping * Development Group: * Class Description: One of the specific classes of cars, Mercedes-Benz Bus * Development time: 2015/8/20 16:06:39 * Development version: V4.0.0 **************** /using system;using System.Collections.Generic ; using system.linq;using system.text;namespace abstractfactory{public class Benzbus:bus {public override void Getcar () {Console.WriteLine ("Produce a Mercedes-Benz bus!        "); }    }}
******************************************************************************* * Developer: Li Liping * Development Group: * Class Description: Mercedes Benz factory, production Mercedes Benz Bus and Mercedes Benz Truck * Development time: 2015/8/20 16:25:07 * Development version: V4.0.0 ************** /using system;using System.collections.generic;using system.linq;using system.text;namespace abstractfactory{public class BenzFactory:        ifactory {public bus Createbus ()//production of Mercedes-Benz bus {return new Benzbus ();        } public Truck Createtruck ()//production of Mercedes Benz truck {return new Benztruck (); }    }}
/**********************************************************************************     * Developer: 李立平     * Development Group:     * Class Description: Client, need Mercedes Benz bus and BMW Truck     * Development time: 2015/8/20 16:06:39     * Development version: V4.0.0    *********************************** /using system;using system.collections.generic;using System.Linq; Using System.text;namespace abstractfactory{    class Client    {        static void Main (string[] args)        {             Bus BB = new Benzbus ();//declared as parent class            ifactory bf = new Benzfactory ();  Create a Mercedes            -Benz Factory BB = bf. Createbus (); Production of Benz Bus            BB. Getcar ();                Truck BT = new Bmwtruck ();//declared as parent class            ifactory tf = new bmwfactory ();//create BMW factory            BT = TF. Createtruck ();//production of BMW truck            BT. Getcar ();}}}    

Benefits: can solve the factory method each factory can only produce a single product of the factory, according to product requirements to further abstract a factory class abstract class, so for the abstract factory. by changing the specific plant to use different product configurations, the second: the concrete creation process and the client separation, the client through the abstract interface to manipulate the instance,

Insufficient: The addition of new products, such as Volkswagen's sedan, will add car abstract class, and the following Volkswagen sedan, Volkswagen truck, and so on, as well as modify the abstract factory, and specific factories, such as the need to add the mass of the specific factory, to modify the place too much, then it looks bad, However, abstract factories can be improved through simple factories.

Abstract Factory Improvements (problem with database replacement):

Simple Factory Improvement Abstract Factory: aDatabaseclass, you can createIuserand theidepartmentof theSQLand theAccessproduct, if need to replaceOracleWhat about the database? Also need inDatabasemodified in CaseBranch, addingOracleDatabase Branch Judgment, contrary to open and close principle, not good maintenance, at this time the database as a string out, reflect the appearance.

        Reflection+Abstract Factory:Assembly.Load( Assembly).CreateInstance(Namespace.to instantiate the class name), the original written dead in the program, now the string to be instantiated objects (variables can be replaced), the database using theDBdecide to removeDatabaseinSwitchbut you need to change the procedure.DBvalue, imperfect, there is no way to modify the program, of course, you can read the configuration file AH.

         configuration file + reflection: True to meet the open and close principle, read the file to db sql access database There's no need to change.

Iv. comparison:

Comparison: Simple factory: Production of any product of the same grade, a factory multi-production line;

Factory method: Fixed product of same grade structure, multiple factories;

Abstract Factory: The production of different series of all products, to add new products powerless.

Each model has its own advantages and disadvantages, only the most suitable for its scene, there is no best time, as long as the satisfaction of their own needs is the best.


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

Simple factory, factory method and abstract factory

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.