C # design Pattern Creation class Mode: Abstract Factory mode

Source: Internet
Author: User

Definition: Provides an interface that creates a series of related or interdependent objects without specifying their specific class.

Concept

To understand the abstract factory model, first understand a few concepts, one is the product hierarchy, the other is the product family.

The factory hierarchy is introduced in the factory method mode , which solves the problem that the factory class responsibilities are too heavy in the simple Factory mode, but because there is only one or a set of overloaded factory methods in each specific factory in the factory method pattern, the production of only one product can lead to a large number of factory classes in the system. is bound to increase the cost of the system, and sometimes may require a factory to provide a variety of product objects, rather than a single Product object, such as Haier Electric Company can produce Haier TV, Haier refrigerator, Haier washing machine, etc., the company or factory can produce a variety of products, rather than a single product. At this point, you can consider a number of related products to form a "product family", from the same factory to unify production, which is the basic idea of the abstract factory model that this chapter will learn. In order to better understand the abstract factory model, the following two concepts are introduced, namely product hierarchy and product family.

Product Hierarchy Structure: product hierarchy structure is the product's inheritance structure, for example, an abstract class is a television, its sub-class can be Haier TV, Hisense TV, Millet TV, the abstract TV and the specific brand of television formed a product hierarchy, abstract TV is the parent class, and the specific brand of television is its sub-category.

Product Family: in the abstract factory model, the product family refers to a group of products produced by the same factory and located in different product grade structures. For example, Haier TV, Haier refrigerator and Haier washing machine is the same product family, this product family from three different product grade structure, combined into a product family.

The product grade structure and product family are as follows:

In the different colors of a plurality of squares, circles and ovals constitute 3 different product hierarchy structure, and the same color of the square, the circle and ellipse constitute a product family, each Shape object is located in a product family, and belongs to a product hierarchy, a total of 5 product families, divided into 3 product hierarchy structure. This unique product can be determined by specifying the product family in which a product is located and the hierarchy to which he belongs.

Abstract Factory Mode Overview

Abstract Factory mode can be used when the specific product produced by the system is not a simple volume object, but a plurality of specific products that are located in different product grade structures and belong to different types. Abstract Factory mode is one of the most abstract and general forms of many forms of Factory mode. The biggest difference between the abstract factory model and the factory method pattern is that the factory approach model is for a single product structure, while the abstract factory model needs to face multiple product hierarchies. Abstract Factory mode is simpler and more efficient than the factory method mode when a factory hierarchy can create all objects in a product family that belong to different product hierarchy structures. The abstract factory pattern is as follows:

, each specific plant can produce all products on a product family, such as squares, circles, and ellipses with the same color. These products are classified into three different product hierarchy structures. If you want to use the simple factory model to do, only to design a factory class, in which to write 15 ways to create different products, the responsibility is too heavy, if you want to write in factory method mode, write 15 different physical factories and three different abstract factories (factory method mode is for a single product hierarchy, So to write three different abstract factories representing each product hierarchy, the number of classes in the system increases exponentially, and the system overhead and complexity are increased; the best approach so far is to use the abstract factory model, and simply create an abstract factory class for the product family of different product hierarchies. and five entity factories that produce different product families respectively. It can be seen that the abstract factory greatly reduces the number of classes in the system. The following is a list of the various components of the abstract factory pattern mentioned above:

①abstractfactory (Abstract Factory): It defines a set of methods for creating a family of products, each of which corresponds to a product.
②concretefactory (Factory specific): it inherits or implements an abstract factory, which implements the abstract factory-defined method to produce a specific family of product classes by implementing its own unique behavior.
③abstractproduct (abstract product): It declares the interface for each product and declares the business method that each product does.
④concreteproduct (Specific product): Defines a specific product object that implements or inherits the business methods defined in the abstract product.

Class diagram for abstract Factory mode:

Implementation of the abstract factory model

Code for a typical abstract factory

Abstract class abstractfactory{publicabstract// factory method One publicAbstract  // factory method two ...}

Typical factory-specific code

class concretefactory1:abstractfactory{     // factory Method A publicoverride  Abstractproducta createproducta () {    returnnew  ConcreteProductA1 ();} // Factory Method Two  Public Override ABSTRACTPRODUCTB CREATEPRODUCTB () {    returnnew  ConcreteProductB1 ();} ...}
Application examples of abstract factories Example Description

A software company to develop a set of interface skin Library, can be based on the. NET platform desktop software to beautify the interface. Users can use the menu to select the skin, different skins will provide visual effects of different buttons, text boxes, combo boxes and other interface elements, such as spring (Spring)-style skin will provide a light green button, green border text box and green border combo box, and Summer (Summer) The style skin is provided with a light blue button, a blue border text box, and a blue border combo box, as shown in the following structure:

The skin library needs to be flexible and scalable, and users are free to choose different skins, and developers can add new skins without modifying existing code.
The interface Skin Library is now designed using abstract Factory mode.

Instance class diagram

Through analysis, the organization diagram of this example is as follows:

, Skinfactory acts as an abstract interface whose subclasses spingskinfactory and Summerskinfactory act as concrete factories, interface buttons, TextField, and ComboBox as abstract products, Its sub-class Springbuttong, Spingtextfield, etc. act as a specific product.

Instance Code

①button: Button interface, acting as abstract product

Interface Button    {        void  Display ();    }

②springbutton:springbutton Button class to act as a specific product

class Springbutton:button     {        publicvoid display ()         {            Console.WriteLine ("displays the light green button.) ");        }    }

③summerbutton: Serving as a specific product

class Summerbutton:button     {        publicvoid  Display ()         {           Console.WriteLine (" Displays the light blue button. ");        }        }

④textfield: Text box interface, acting as abstract product

Interface TextField    {        void  Display ();    }

⑤springtextfield: Specific Products

class Springtextfield:textfield     {        publicvoid  Display ()         {            Console.WriteLine (" displays a green border text box. ");        }    }

⑥summertextfield: Concrete Class

class Summertextfield:textfield     {        publicvoid display ()         {            Console.WriteLine (" displays a blue border text box.) ");        }        }

⑦combobox: Abstract Products

Interface ComboBox    {        void  Display ();    }

⑧springcombobox: Specific Products

class Springcombobox:combobox     {        publicvoid display ()         {            Console.WriteLine (" displays a green border combo box. ");        }    }

⑨summercombobox: Specific Products

class Summercombobox:combobox     {        publicvoid  Display ()         {            Console.WriteLine (" displays a blue border combo box. ");        }        }

⑩skinfactory: Interface Skin Factory interface, acting as abstract factory

Interface skinfactory    {        Button Createbutton ();        TextField Createtextfield ();        ComboBox Createcombobox ();    }

(11) Springskinfactory: A specific skin factory

 class   Springskinfactory:skinfactory { /span>public   button Createbutton () { /span>return  new          Springbutton ();          public   TextField Createtextfield () { return  new   Springtextfield ();          public   ComboBox Createcombobox () { return  new   Springcombobox (); }    }

(summerskinfactory): Specific skin factory

class summerskinfactory:skinfactory     {        public  Button Createbutton ()         {            returnnew  Summerbutton ();        }          Public TextField Createtextfield ()         {            returnnew  Summertextfield ();        }          Public ComboBox Createcombobox ()         {            returnnew  summercombobox ();        }    }

(13) Client calls:

Static voidMain (string[] args) {            //using the abstraction layer definitionSkinfactory Factory;            Button BT;            TextField TF;            ComboBox CB; //reading configuration Files            stringFactorytype = configurationmanager.appsettings["Factory"]; //Reflection-generated objectsFactory = (skinfactory) assembly.load ("Abstractfactorysample").            CreateInstance (Factorytype); BT=Factory.            Createbutton (); TF=Factory.            Createtextfield (); CB=Factory.            Createcombobox (); Bt.            Display (); Tf.            Display (); Cb.            Display ();        Console.read (); }

The client calls or uses the configuration file and reflection to do some closing work that conforms to the open and closed principle. In this system, if you want to replace the skin interface, you only need to modify the configuration file.

Inclination of opening and closing principle

The above example actually has a very serious problem, that is, if at the beginning of the design to ignore some of the details, it will be very difficult to expand later, for example, we now want to add a radio button box, because in the abstract factory class has been written dead, to increase the radio button box, If in the factory method model directly add abstract product class + specific product class + abstract Factory + specific factory to expand the system, in line with the open and closed principle, and in the abstract Factory mode is not done, because the logic in the abstract factory class has been written dead, in this case, the abstract factory class only defines the button Createbutton (); TextField Createtextfield (); ComboBox Createcombobox (); These three methods, if the new radio button, then the source code must be modified, in violation of the opening and closing principle.

In the abstract factory model, the new product family is very convenient, directly add a specific factory and a family of specific products can, but if the new product hierarchy structure, it will be very troublesome, need to modify the source code, which violates the open and closed principle.

The advantages and disadvantages of the abstract factory model and the applicable environment

Abstract Factory mode is a further extension of the factory method pattern, as it provides a more powerful factory class and has a good scalability, widely used in software development, especially in some frameworks and class libraries. It is one of the most commonly used design patterns.

Abstract Factory Mode Benefits

① isolate the generation of specific classes so that clients do not need to know what is being created
② when multiple objects in a product family are designed to work together, it ensures that the client always uses only objects from the same product family
③ Add new product family is very convenient, no need to modify the existing system, in line with the opening and shutting principle

Abstract Factory mode drawbacks

Add new product grade structure trouble, need to make large changes to the original system, and even need to modify the abstraction layer code, which will obviously bring greater inconvenience, contrary to the opening and closing principle

Abstract Factory model applicable environment

① a system should not rely on the details of how a product class instance is created, composed, and expressed
There are more than one product family in the ② system, but only one of the product families is used at a time
③ products belonging to the same product family will be used together, this constraint must be reflected in the design of the system
④ product grade structure is stable, after the design is completed, will not add new product grade structure to the system or delete the existing product hierarchy structure

C # design Pattern Creation class Mode: Abstract Factory mode

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.