Home  >  Article  >  Backend Development  >  A brief introduction to C++ design patterns and prototype pattern

A brief introduction to C++ design patterns and prototype pattern

黄舟
黄舟Original
2017-01-18 14:57:581326browse

Definition: Use prototype instances to specify the types of objects to be created, and create new objects by copying these prototypes.

The prototype pattern is actually to create another customizable object from an object without knowing any details of the creation.

The prototype mode mainly considers deep copy and shallow copy. In C++ class design, the copy constructor is a shallow copy, and when the assignment operator is overloaded, it is a deep copy.

Shallow copy: All variables of the copied object contain the same values ​​​​of the original object, and all references to other objects still point to the original object.

Deep copy: Point the variable of the reference object to the copied new object instead of the original referenced object.

Test case:

[code]int main(){
    //生成对象
    ConcretePrototype * conProA = new ConcretePrototype();
    //复制自身
    ConcretePrototype *conProB = conProA->Clone();   //先clone后调用拷贝构造函数, Output: clone constructor

    delete conProA;
    conProA = NULL;

    delete conProB;
    conProB = NULL;

    return 0;
}

Prototype implementation

[code]//接口
class Prototype{
public:
    Prototype(){}
    virtual ~Prototype(){}
    virtual Prototype *Clone() = 0;
};

//实现
class ConcretePrototype: public Prototype{
public:
    ConcretePrototype(): m_counter(0) {}
    virtual ~ConcretePrototype(){}
    //拷贝构造函数
    ConcretePrototype(const ConcretePrototype &rhs){
        std::cout << "constructor\n";
        m_counter = rhs.m_counter;
    }

    //复制自身
    virtual ConcretePrototype *Clone(){
        //调用拷构造函数
        std::cout << "clone\n";
        return new ConcretePrototype(*this);
    }

private:
    int m_counter;
};

The above is the content of the prototype mode of C++ design pattern. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn