Prototype (c++ design mode)

Interviewer: Please talk about the prototype model


Prototype model prototype example specifies the type of object to be created, and to create new objects by copying this prototype

Model advantages

  • Simplify the creation of objects
  • Good scalability
  • Provides a simple creation structure
  • The state of the object can be saved in a deep clone

Model disadvantages

  • Each class needs to be equipped with a clone method, and the method is located inside a class. When the existing class is modified, the source code needs to be modified, which violates the principle of opening and closing
  • Need to write more complex code when implementing deep cloning

Applicable environment

  • Creating a new object is expensive
  • The system needs to save the state of the object, and the state of the object changes very little
  • Need to avoid using hierarchical factory classes to create objects
  • Ctrl+C、Ctrl+V

Prototype code

/*
 * @ Description: C++ Design Patterns___Prototype
 * @ version: v1.0
 * @ Author: WeissxJ
 */
#include<iostream>
#include<string>

class Prototype
{
    
    
    public:
        virtual ~Prototype() {
    
    }

        virtual Prototype* clone()=0;
        virtual std::string type()=0;
        // ...
};

class ConcretePrototypeA : public Prototype
{
    
    
    public:
        ~ConcretePrototypeA() {
    
    }
        
        Prototype* clone(){
    
    
            return new ConcretePrototypeA();
        }
        std::string type(){
    
    
            return "type A";
        }
        // ...
};

class ConcretePrototypeB : public Prototype
{
    
    
    public:
        ~ConcretePrototypeB() {
    
    }
        
        Prototype* clone(){
    
    
            return new ConcretePrototypeB();
        }
        std::string type(){
    
    
            return "type B";
        }
        // ...
};

class Client
{
    
    
    private:
        static Prototype* types[2];
        static int n_types;
    public:
        static void init(){
    
    
            types[0]=new ConcretePrototypeA();
            types[1]=new ConcretePrototypeB();
        }

        static void remove(){
    
    
            delete types[0];
            delete types[1];
        }

        static Prototype* make(const int index){
    
    
            if(index>=n_types){
    
    
                return nullptr;
            }
            return types[index]->clone();
        }
        // ...
}; 

Prototype* Client::types[2];
int Client::n_types=2;

int main(){
    
    
    Client::init();

    Prototype* prototype1=Client::make(0);
    std::cout<<"Prototype: "<<prototype1->type()<<std::endl;
    delete prototype1;

    Prototype* prototype2=Client::make(1);
    std::cout<<"Prototype: "<<prototype2->type()<<std::endl;
    delete prototype2;

    Client::remove();

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/111681151