Article source: www.jb51.net/article/558…

www.jb51.net/article/558… \

www.jb51.net/article/558… \

A, this article mainly introduces the C++ design pattern of simple factory model example, factory model has a very vivid description, the establishment of the object class is like a factory, and the object to be established is a product, need friends can refer to. \

Problem description

I made a Windows 8 reader for my company. First, you need to render the contents of an e-book onto the screen, and each page of an e-book contains a variety of contents, such as graphics, images, and text. Different contents are different objects; Before the different content can be rendered on the screen, the new operation is required to create the different objects and then paint them on the screen. At this time, a lot of new operations need to be carried out. New operations are distributed in different places of the code, which is very troublesome and messy to manage. When it comes to later expansion and maintenance, sometimes there are so many objects that developers do not know what the object is, which increases the difficulty. At the same time, the new operation, there will be corresponding exception handling, and finally, you will find that in the code, the new object, and then, there is an exception handling code, and then the code becomes very messy and bloated. So what do we do? How to do? At this point, we need a new class that is dedicated to creating and releasing objects, after which the object’s operations have nothing to do with this class. This specialized object creation class exposes the interface to create the object for external calls.

Factory mode has a very vivid description, the class of the object is like a factory, and the object to be established is a product; The people who process the product in the factory, the people who use the product, don’t care how the product was produced. From a software development perspective, this effectively reduces the coupling between modules.

UML class diagrams

The factory model can be divided into three categories:

1. Simple factory mode; 2. Factory method mode; 3. Abstract factory pattern.

The above three factory patterns are progressively abstracted from top to bottom and are more general. This post focuses on the simple factory model, which will be summarized in a later post.

\

ProductA, ProductB and ProductC inherit from the Product virtual class. The Show method is a self-description of different products. Factory relies on ProductA, ProductB, and ProductC, and Factory creates different Product objects based on different conditions.

Applicable occasions

1. In the program, a lot of objects need to be created, resulting in multiple and miscellaneous new operations of objects, need to use the simple factory mode; 2. Since we do not need to care about the object creation process, and we focus on the actual operation of the object, so we need to separate the object creation and operation of the two parts, so as to facilitate the later program expansion and maintenance.

Code implementation:

/* ** FileName : SimpleFactoryPatternDemo ** Author : Jelly Young ** Date : 2013/11/17 ** Description : More information */ #include

#include

using namespace std; typedef enum ProductTypeTag { TypeA, TypeB, TypeC }PRODUCTTYPE; // Here is the product class class Product { public: virtual void Show() = 0; }; class ProductA : public Product { public: void Show() { cout<<“I’m ProductA”<

CreateProduct(TypeA); if(productObjA ! = NULL) productObjA->Show(); Product *productObjB = ProductFactory->CreateProduct(TypeB); if(productObjB ! = NULL) productObjB->Show(); Product *productObjC = ProductFactory->CreateProduct(TypeC); if(productObjC ! = NULL) productObjC->Show(); deleteProductFactory; ProductFactory = NULL; delete productObjA; productObjA = NULL; delete productObjB; productObjB = NULL; delete productObjC; productObjC = NULL; return 0; } 2. Factory method pattern, which is an extension of the simple factory pattern
;>

Problem description

We talked about the C++ design mode — simple factory mode. Due to the limitations of simple factory mode, for example, the factory can now produce ProductA, ProductB and ProductC. At this point, it is necessary to increase the production of ProductD products. First, add a new product type identifier to the product enumeration type, and then modify the switch structure code in the Factory class. Yes, this kind of code modification, the original code change momentum is large, easy to produce coding errors (although very simple, if the project is big, mistakes are inevitable!!) . This modification of the code is the most primitive and savage modification, and cannot be called an extension of the code per se. At the same time, because of changes to existing functions, all previous tests will be invalid, all tests will need to be re-run, and all code will need to be re-covered. Such things, which increase costs and do not improve efficiency, are absolutely not allowed in the company (except for the stupid PM). For a variety of reasons, the simple factory pattern is rarely used in real projects. So what to do? What to do? Need to minimize the impact of the original code, while the original function can be extended.

UML class diagrams

So the factory method mode introduced today is on grand stage. It is just an extension of the simple factory model. In the introduction of GOF, they are combined together, and I will explain them separately, in order to distinguish the advantages and disadvantages of the two, so that you can better grasp and apply them in actual projects. The factory method pattern adds an abstraction layer to the “factory” on top of the simple factory pattern. The common actions of factories are abstracted out as abstract classes, and the concrete actions are implemented by the subclasses themselves, letting them decide what products to produce.

\

As shown in the figure, FactoryA concentrates on producing ProductA and FactoryB concentrates on producing ProductB. There is no relationship between FactoryA and FactoryB. At a later stage, if we need to produce ProductC, we can create a FactoryC factory class that is solely responsible for producing ProductC products. Since FactoryA, FactoryB, and FactoryC are not related to each other, FactoryC does not have any effect on the work of FactoryA and FactoryB when FactoryC is added. FactoryC and ProductC need to be separately unit tested, while FactoryA and FactoryB need not be tested, thus saving a lot of boring testing work.

Applicable occasions

The point of the factory method pattern is to define a factory interface to create product objects, deferring the actual creation to subclasses. The core factory class is no longer responsible for the creation of products, so that the core class becomes an abstract factory role, only responsible for the interfaces that the concrete factory subclasses must implement. The benefit of this further abstraction is that the factory method pattern enables the system to introduce new products without modifying the concrete factory role.

1. At the early stage of design, considering that the product will be expanded in the later stage, the factory method mode can be used;

2. In the case of complex product structure, factory method mode can be used;

Because the use of design patterns is a decision that needs to be made at detailed design time, many factors need to be weighed, rather than design patterns for the sake of using them.

Code implementation:

/* ** FileName : FactoryMethodPatternDemo ** Author : Jelly Young ** Date : 2013/11/18 ** Description : More information, please go to www.jb51.net */ #include

using namespace std; class Product { public: virtual void Show() = 0; }; class ProductA : public Product { public: void Show() { cout<< “I’m ProductA”<

CreateProduct(); productA->Show(); Factory *factoryB = new FactoryB (); Product *productB = factoryB->CreateProduct(); productB->Show(); if (factoryA ! = NULL) { delete factoryA; factoryA = NULL; } if (productA ! = NULL) { delete productA; productA = NULL; } if (factoryB ! = NULL) { delete factoryB; factoryB = NULL; } if (productB ! = NULL) { delete productB; productB = NULL; } return 0; \
;>

}

\

Thirdly, abstract factory mode is the extension and extension of factory method mode

Problem description

When we talked about the C++ design pattern — factory method pattern, we may think that there will be more and more products in the later stage, and more and more factories will be built. As the factories grow, the factories will become messy and difficult to manage. Since the objects created by the factory method pattern are inherited from Product, each factory can only create a single type of Product in the factory method pattern. When it comes to producing a brand new Product (not inherited from Product), the factory method is found to be unable to do so.

For example: a display circuit board manufacturer, its display circuit board types are non-liquid crystal and liquid crystal; At this time, the manufacturer builds two factories, factory A is responsible for the production of non-LCD circuit board, factory B is responsible for the production of LCD circuit board; The factory has been running like this. One day, the general manager realized that it would be profitable to produce the rest of the display directly, so he decided to build two more factories C and D. C is responsible for the production of the rest of the non-LCD components, and D is responsible for the production of the rest of the LCD components. At this time, next to the staff of the people said, manager, this is no good, we can directly in the factory A to add A responsible for the production of liquid crystal display parts production line, adding A B in the factory production of the rest of the liquid crystal display parts production line, this can need not increase the building, only will be to expand the existing factory building, and convenient management of the factory, And the technicians who produce the non-LCD circuit board have a guiding role in the production of the rest of the non-LCD components, and the same is true for the LCD circuit board. The general manager found it a good idea.

Back in the software development process, factory A and B are the C++ design pattern — factory method pattern. The general manager builds factories C and D again, repeating the C++ design pattern — the factory method pattern, but producing different products. The downside of this, as the staff said, is that it increases administrative costs and human costs. In the process of object-oriented development, object management and maintenance are very important. The more objects, the more difficult it is to manage and maintain; If there are too many factories, the cost of management and maintenance will increase greatly; Although different products are produced, there is a subtle relationship between the two. As the staff said, some technical experience of technical personnel can be used for reference, which is equivalent to different objects in the same class, which can share some resources. Well, adding an assembly line and expanding the factory is certainly the best idea.

The real problem has been solved, so how do you use design patterns to simulate this real problem? That is the abstract factory pattern.

UML class diagrams

Now to talk about abstract factory pattern, is the factory method pattern extension and extension, but abstract factory pattern, more general and representative; It has the advantages of the factory approach, as well as the added ability to solve practical problems.

\

As shown, the abstract factory pattern is like the superposition of two factory method patterns. An abstract factory creates a set of related objects in which the implementation is essentially the factory method pattern adopted. Factory1 and Factory2 decide what kind of product the Factory1 and Factory2 actually need to produce. This delays instantiation of concrete subclasses. At the same time, centralized production line management, saving the waste of resources.

Applicable occasions

The factory method pattern is suitable for the occasion of single product category structure and provides the interface to create a class of products. The abstract factory method is suitable for the situation of multiple product types and structures. It is mainly used to create a group of related products (with multiple types) and provide interfaces for them to create. Abstract factories come in handy when you have multiple abstract roles.

Code implementation

/*

** FileName   : AbstractFactoryPatternDemo

** Author    : Jelly Young

** Date     : 2013/11/19

** Description : More information

*/



#include <iostream>

using namespace std;



// Product A

class ProductA

{

public:

virtual void Show() = 0;

};



class ProductA1 : public ProductA

{

public:

void Show()

{

cout<<“I’m ProductA1″<<endl;

}

};



class ProductA2 : public ProductA

{

public:

void Show()

{

cout<<“I’m ProductA2″<<endl;

}

};



// Product B

class ProductB

{

public:

virtual void Show() = 0;

};



class ProductB1 : public ProductB

{

public:

void Show()

{

cout<<“I’m ProductB1″<<endl;

}

};



class ProductB2 : public ProductB

{

public:

void Show()

{

cout<<“I’m ProductB2″<<endl;

}

};



// Factory

class Factory

{

public:

virtual ProductA *CreateProductA() = 0;

virtual ProductB *CreateProductB() = 0;

};



class Factory1 : public Factory

{

public:

ProductA *CreateProductA()

{

return new ProductA1();

}



ProductB *CreateProductB()

{

return new ProductB1();

}

};



class Factory2 : public Factory

{

ProductA *CreateProductA()

{

return new ProductA2();

}



ProductB *CreateProductB()

{

return new ProductB2();

}

};



int main(int argc, char *argv[])

{

Factory *factoryObj1 = new Factory1();

ProductA *productObjA1 = factoryObj1->CreateProductA();

ProductB *productObjB1 = factoryObj1->CreateProductB();



productObjA1->Show();

productObjB1->Show();



Factory *factoryObj2 = new Factory2();

ProductA *productObjA2 = factoryObj2->CreateProductA();

ProductB *productObjB2 = factoryObj2->CreateProductB();



productObjA2->Show();

productObjB2->Show();



if (factoryObj1 != NULL)

{

delete factoryObj1;

factoryObj1 = NULL;

}



if (productObjA1 != NULL)

{

delete productObjA1;

productObjA1= NULL;

}



if (productObjB1 != NULL)

{

delete productObjB1;

productObjB1 = NULL;

}



if (factoryObj2 != NULL)

{

delete factoryObj2;

factoryObj2 = NULL;

}



if (productObjA2 != NULL)

{

delete productObjA2;

productObjA2 = NULL;

}



if (productObjB2 != NULL)

{

delete productObjB2;

productObjB2 = NULL;

}

}\

?