Design Patterns 5: factory)

Source: Internet
Author: User

When implementing a software system, we often encounter the situation of adding new types. Developers without experience in design patterns will adopt a direct method to define a class, introduce the header file of this class in the module of this class, use the new operator to allocate an object from the stack, and call delete when not needed to delete the object and reclaim the memory. With the increasing number of types, the operation of such allocation objects is spread across various modules of the Code. Once the class definition changes, especially when new interfaces are modified or added, you must check and modify the code everywhere, when the system is too large, it may even omit some places that need to be modified, leading to unexpected results.

The factory mode is used to solve the above problem. It encapsulates object creation so that object creation is concentrated in one place. To add a new type, you only need to change this place, the new type is applied to the system, and even modules of the new type do not know what type is being used.

When you find that new types need to be added to a system, the best practice is to create a common interface for these new types using the polymorphism mechanism. This method can be used to separate the remaining code in the system from the newly added code of a specific type. adding a new type does not disturb the existing code.

Since every object-oriented application needs to create objects, and we often add new types to extend the application, the factory mode may be one of the most useful modes in all design patterns. By forcibly using the factory mode, the code of the created object is transferred to the factory for execution. All you need to do when adding a new type is to modify the factory. This will greatly reduce the code maintenance work caused by the increase of types.

This article introduces the simple factory model. The following is an example of the factory model in volume 2 of C ++ programming ideology (excluding Exception Handling ):

class Shape{public:    virtual void draw() = 0;    virtual void erase() = 0;        static Shape * factory(const string& type);};class Circle : public Shape {    Circle(){}    friend class Shape;public:    void draw(){ cout << "Circle::draw" << endl;}    void erase(){ cout << "Circle::erase" << endl;}    ~Circle(){ cout << "Circle::~Circle" << endl;}};class Square : public Shape{    Square(){}    friend class Shape;public:    void draw() { cout << "Square::draw" << endl; }    void erase() { cout << "Square::erase" << endl; }    ~Square(){ cout << "Square::~Square" << endl; }};Shape * Shape::factory(const string& type){    if(type == "Circle")    {        return new Circle();    }    if(type == "Square")    {        return new Square();    }        return NULL;}char* g_sl[] = { "Circle", "Square", "Square",    "Square","Circle","Square"};    int main(){    vector
 
   shapes;    for(int i = 0; i < sizeof(g_sl)/sizeof(g_sl[0]); i++)        shapes.push_back(Shape::factory(g_sl[i]));    for(int i = 0; i < shapes.size(); i++)    {        shapes[i]->draw();        shapes[i]->erase();    }    return 0;}
 

The factory () function allows a parameter to determine the type of shape to be created. When adding a new Shape type, the function factory () is the only place to be modified. However, this implementation-the basic class Shape must understand the details of each derived class-violates an object-oriented design principle: the base class does not need to understand the derived class.

This design is clumsy, because the base class must be updated once the new type is added to this hierarchy, which is very inappropriate for the structure framework or class library.

Some policies can be used to avoid this situation. Next time, I will provide a more elaborate implementation. Using the class constructor in C ++, I will register the method for creating a function, implement a factory mode for creating Objects Based on keywords. This factory mode separates the process of creating factories, products, and products. The factory does not need to know how to create products, effectively isolating the impact of adding new types on the factory-the factory does not need to be changed, in the end, to add a new type, you only need to add code where the new type is implemented. Other places in the software-even the factory-do not need to be changed.

Review the previous articles in the Design Pattern series (the following factory pattern implementation will use the singleton and command modes ):

One of the design patterns: Overview of design patterns 2: Singleton design patterns 3: command design patterns 4: Template Methods) 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.