C + + design pattern [one] Factory mode __c++

Source: Internet
Author: User

Always want to learn a good design pattern, finally found a familiar and understandable C + + design pattern explanation, recently a little lazy, and then most of the content to master the turn over, some of them added to the comments, there are any errors, please correct me, thank you.

===========================================================================================================

For the implementation of the middle code and most of the content is owned by the author, only for reference learning, for the article is reproduced or original questions, please forgive, have their own written are divided into original

This column, all reproduced as reproduced in this column

============================================================================================================


First look at these patterns:

Create pattern

Simple factory Model: What kind of product is decided by the factory, and what kind of product is produced "is not a design mode"

Factory method Pattern: Define the factory interface and decide what products to produce by the specific factory

Abstract Factory Pattern: Provides an interface to create a series of related or independent objects without specifying the specific classes of those objects

Singleton mode: Only one instance of an object exists throughout the system

Builder Model: Create different instances using the same build process

Prototype mode: Create a new object by cloning/replicating an existing instance

Structure pattern

Adapter Mode: Converts an object with a interface appearance to an object with a B interface appearance, but still performs the underlying operation by a type object

Bridging mode: Separating behavior from action so that it can be changed independently

Combination mode: Treats a group of objects as an object, executes the combined method, and the method of the group object is called

Decorator mode: Dynamically adding functionality to an object

Appearance mode: Wrapping a set of behaviors to simplify external calls

The element mode: the common use of things extracted

Agent mode: A class that serves as an interface for other classes for the client to call

Behavioral patterns

Responsibility Chain mode: encapsulate responsibilities, chain into chains and define their turnover behavior, and can dynamically expand responsibilities

Command mode: Encapsulates the behavior into a command to make it look uniform, facilitating unified invocation execution

Interpreter Mode: Use abstract representation instead of detailed description

Iterator pattern: Encapsulates the traversal method of different sets to give it a unified look

Mediation Mode: Use mediation objects to interact with objects, avoid inline interactions, and reduce coupling

Memo mode: Similar to the closure function, save the details of the object without disrupting the object's encapsulation so that it can be restored to that state

Observer pattern: Changes in one object affect other objects

State mode: Select a different state class to process the corresponding business logic based on the transition of the State

Policy patterns: Define algorithm families, encapsulate them separately, so that they can be replaced directly, so that the changes in the algorithm are independent of the client using the algorithm

Template method Pattern: Similar to the factory method pattern, the same kind of objects in the same operation to extract, different operations for abstraction, by the specific class to implement

Visitor mode: Defines a new action for these elements without changing the class of elements

=====================================================================

The first is the factory model;

The factory pattern has a very vivid description, the class that builds the object is like a factory, but the object that needs to be built is a product; the person who processes the product in the factory, uses the product, does not care about how the product is produced. From the perspective of software development, this effectively reduces the coupling between modules. UML class Diagram

For the factory model, the specific can be divided into three categories: Simple factory model, factory method model, abstract factory model.

For the three factory models above, abstraction is gradual from top to bottom and more general. This article is mainly about the simple factory model.
ProductA, PRODUCTB, and PRODUCTC inherit from the product virtual class, and show methods are self-describing for different products; factory depend on ProductA, PRODUCTB, and PRODUCTC, Factory creates different product objects based on different conditions. applicable occasions in the program, there are many objects that need to be created, resulting in a lot of new operations and miscellaneous objects, the need to use a simple factory pattern; Since the object is created in a way that we don't need to care about, and we focus on the actual operation of the object, we need to separate the creation and operation of the object. This facilitates later program expansion and maintenance.

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
Class Product
{public
:
	virtual void use () {};
};
Class Concreteproducta:p ublic Product
{public
:
	void using ()
	{
		cout << "Use a" << Endl;
	};
Class Concreteproductb:public Product
{public
:
	void using ()
	{
		cout << "Use B" << Endl;
	};
Class Factory
{public
:
	product* factory::createproduct (string proname) {
		if ("A" = = Proname)
		{return
			new concreteproducta ();
		}
		else if ("B" = = Proname)
		{return
			new CONCRETEPRODUCTB ();
		}
		return  NULL;
	}
;
int main ()
{
	Product *p = NULL;
	Product *q = NULL;
	Factory F;
	P=f.createproduct ("A");
	Q = F.createproduct ("B");
	P->use ();
	Q->use ();
	return 0;
}


Due to the limitations of the simple factory model, such as: The factory can now produce producta, PRODUCTB and PRODUCTC three kinds of products, at this time, the need to increase production PRODUCTD products; So, first you need to add a new product type ID to the product enumeration type, and then, Modify the switch structure code in the factory class. Yes, this modification of the code, the original code changes large, easy to produce coding errors (although very simple, if the project is big, error is inevitable ... )。 This modification of the code is the most primitive, most barbaric modification, which is essentially not an extension of the code. At the same time, since the existing functions have been modified, the previous tests will be invalid, all tests will need to be restarted, all the code needs to be overwritten. This, increased costs, can not improve the efficiency of things in the company is absolutely not allowed (unless the fatuous pm). For a variety of reasons, the simple factory pattern is less used in actual projects. Then what should be done. How to do it. The need to minimize the impact of the original code, while the original functionality can be extended. UML class Diagram

The factory method pattern is to the simple factory pattern expansion, in Gof's introduction, they are merges together, but I is separately carries on the explanation, is in order to differentiate the pros and cons of the two, for everybody in the actual project to carry on the better grasp and the application. The factory method model adds an abstraction layer to the factory based on the simple factory pattern. Abstract the common action of the factory as an abstract class, and the specific behavior is implemented by subclasses themselves, so that subclasses decide what products to produce.

As pictured, Factorya is responsible for production PRODUCTA,FACTORYB concentration is responsible for the production of Productb,factorya and Factoryb there is no relationship between; if later, if you need to produce PRODUCTC, We can create a FACTORYC factory class that is focused on producing PRODUCTC products. Since there is no relationship between Factorya, Factoryb, and Factoryc, when joining FACTORYC joins, there is no effect on Factorya and factoryb work, when the code is tested, The need for unit testing of FACTORYC and PRODUCTC alone, while Factorya and Factoryb do not have to be tested, can save a lot of uninteresting and tasteless testing work. applicable occasions

The meaning of the factory method pattern is to define a factory interface that creates the product objects, deferring the actual creation to the subclass. The Core factory class is no longer responsible for the creation of the product, so the core class becomes an abstract factory role that is responsible only for the interfaces that must be implemented by the specific factory subclass, so the benefit of further abstraction is that the factory method model allows the system to introduce new products without modifying the specific factory role. In the early stages of design, the factory method model can be used in the case that the product will be expanded at a later stage and the product structure is more complex.

Because design patterns are used in detailed design, you need to make a decision, so you need to weigh a number of factors and not use design patterns for design patterns.

#include "stdafx.h" #include <iostream> #include <vector> using namespace std;

Class Product {public:virtual void show () = 0;};
	Class Producta:public Product {public:void Show () {cout << "I ' m producta" << Endl;

}
};
	Class Productb:public Product {public:void Show () {cout << "I ' m PRODUCTB" << Endl;

}
};

Class Factory {public:virtual Product *createproduct () = 0;};
	Class Factorya:public Factory {public:product *createproduct () {return new producta ();

}
};
	Class Factoryb:public Factory {public:product *createproduct () {return new PRODUCTB ();

}
};
	int main (int argc, char *argv[]) {Factory *factorya = new Factorya ();
	Product *producta = Factorya->createproduct ();

	Producta->show ();
	Factory *factoryb = new Factoryb ();
	Product *PRODUCTB = Factoryb->createproduct ();

	Productb->show ();
		if (Factorya!= NULL) {delete Factorya;
	Factorya = NULL; } if (ProductA!= NULL) {DeleteProductA;
	ProductA = NULL;
		} if (Factoryb!= NULL) {delete factoryb;
	Factoryb = NULL;
		} if (PRODUCTB!= NULL) {delete productb;
	PRODUCTB = NULL;
return 0; }
Later products will become more and more, the establishment of the factory will be more and more, the factory has grown, the factory has become messy and difficult to manage; Because the factory method pattern creates objects that inherit from product, each factory can only create a single type of product in the factory method pattern. When you need to produce a brand new product (not inherited from product), the factory approach is found to be powerless.

For example: A display circuit board manufacturer, its display circuit board types are not liquid crystal and liquid crystal; At this time, the manufacturer built two factories, factory A is responsible for the production of 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 found that the direct production of the rest of the display is also very lucrative, so the general manager decided to set up two more plants C and d;c responsible for the production of the remaining parts of the LCD, D responsible for the production of the rest of the liquid crystal display. At this point, the man beside the staff said, manager, this is not good, we can directly in the factory A to add a production of the remaining parts of the non-LCD display line, in the factory B to add a production of the rest of the LCD display line, so you can not increase the plant, only to expand the existing plant, At the same time also facilitate the management of the factory, but also the production of LCD circuit board technicians on the rest of the LCD display of the production of the role of guidance, the production of liquid crystal display circuit board is the same. The general manager found this to be a good idea.

Back to the process of software development, the factory A and B are previously said C + + design mode-the factory method model; The general manager set up the factory C and D again, is duplicate C + + design mode--factory method mode, just produce different products. The disadvantage of this is that, as the staff said, increased management costs and human costs. In the process of object-oriented development, the object management and maintenance is very important, the more objects you have, the more difficult it is to manage and maintain; If the number of factories is too large, then the cost of management and maintenance will increase greatly; Although the production of different products, but can be a subtle relationship between the two, as the staff said, Some technical experience of technicians can be used, which is equivalent to the different objects in the same class, where some resources can be shared. Then, adding an assembly line and expanding the plant is, of course, the best idea.

The actual problem has been solved, so how to use the design pattern to simulate the actual problem. That is the abstract factory model that follows. UML class Diagram

The abstract factory model that we are talking about now is the extension and extension of the factory method pattern, but the abstract factory model is more general and representative, it has the advantage of the factory method, and also increases the ability to solve the practical problems.

As shown in the illustration, the abstract factory pattern is like the superposition of two factory method patterns. An abstract factory creates a series of related objects in which the implementation is actually the factory method pattern used. In the factory factory each method, is like is a production line, but the production line actually needs to produce what kind of product, this is decided by the Factory1 and the Factory2, thus delayed the concrete subclass the instantiation, simultaneously centralized the production line management, saved the resource waste. applicable occasions

The factory method model is suitable for the single occasion of the product type structure, provides an interface for a class of products, whereas an abstract factory approach applies to situations where the product is structured in a way that is primarily used to create a set of related products (with multiple categories), providing an interface for creation; When you have multiple abstract roles, Abstract factories can be useful.

#include "stdafx.h" #include <iostream> #include <vector> 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-&GT;CREATEPRODUCTB ();
	Productobja1->show ();

	Productobjb1->show ();
	Factory *factoryobj2 = new Factory2 ();
	ProductA *productobja2 = Factoryobj2->createproducta ();

	PRODUCTB *productobjb2 = FACTORYOBJ2-&GT;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;
 }
}


 

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.