原型模式 C++实现

2019-03-13  本文已影响0人  假程序员
//
//  main.cpp
//  prototype_pattern
//
//  Created by apple on 2019/3/13.
//  Copyright © 2019年 apple. All rights reserved.
//

#include <iostream>
#include <string>
using namespace std;

class IPrototype
{
public:
    virtual IPrototype *clone() = 0;
    virtual void test() = 0;
    virtual ~IPrototype() {}
};
class Prototype_A:public IPrototype
{
private:
    string name;
public:
    Prototype_A() {this->name = "";}
    Prototype_A(string name) {this->name = name;}
    IPrototype *clone()
    {
        Prototype_A *temp = new Prototype_A();
        *temp = *this;
        return temp;//此为原型模式的核心,想想为何要这么做!
        //首先new一个Prototype_A类型的实例,*this赋值给*temp
        //这样就会使这两个对象中各个属性以及方法的值相等
    }
    void test() {cout<<"Prototype_A:"<<this->name<<endl;}
};
class Prototype_B:public IPrototype
{
private:
    string name;
public:
    Prototype_B() {this->name = "";}
    Prototype_B(string name) {this->name = name;}
    IPrototype *clone()
    {
        Prototype_B *temp = new Prototype_B();
        *temp = *this;
        return temp;
    }
    void test() {cout<<"Prototype_B:"<<this->name<<endl;}
};
int main(int argc, const char * argv[]) {
    Prototype_A *tempA_a = new Prototype_A("A");
    tempA_a->test();
    
    Prototype_A *tempA_b = (Prototype_A *)tempA_a->clone();
    tempA_b->test();
    
    Prototype_B *tempB_a = new Prototype_B("B");
    tempB_a->test();
    
    Prototype_A *tempB_b = (Prototype_A *)tempB_a->clone();
    tempB_b->test();
    
    delete tempA_a;
    delete tempA_b;
    delete tempB_a;
    delete tempB_b;
    return 0;
}
Prototype_A:A
Prototype_A:A
Prototype_B:B
Prototype_B:B
Program ended with exit code: 0
上一篇下一篇

猜你喜欢

热点阅读