美文网首页
原型模式 C++实现

原型模式 C++实现

作者: 假程序员 | 来源:发表于2019-03-13 23:43 被阅读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

相关文章

  • 原型模式 C++实现

  • JavaScript 中几个重要的工具函数

    实现原型继承的extend函数 单体模式通用函数 实现原型继承的extend函数 单体模式通用函数

  • 设计模式:原型

    原型模式基本介绍原型模式的实现源码中的原型模式记录 原型模式基本介绍 定义:用原型实例指定创建对象的种类,并通过复...

  • 设计模式-原型模式

    原型模式介绍 原型模式(Prototype Pattern)是创建型模式的一种。这种模式是实现了一个原型接口,该接...

  • php设计模式(七)原型模式

    原型模式 与工厂模式类似 与工厂模式实现不同,原型模式时先创建好一个原型对象,然后通过clone原型对象来创建新对...

  • 原型模式

    模式介绍 模式的定义 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。 模式的内图 模式实现 原型模...

  • C++设计模式-第二篇 (Boolan)

    C++设计模式-第二篇 (Boolan) 本章内容:1 工厂方法模式2 抽象工厂模式3 原型模式4 构建器模式5 ...

  • Android设计模式:原型设计模式

    用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。 (1)原型模式实现 实现Cloneable接口;重...

  • 模式设计之 原型模式

    定义 原型模式:原型模式用于创建重复的对象,实现对象的拷贝。这种模式类似于创建型模式,提供了创建对象的最佳模式。 ...

  • JavaScript 设计模式

    创建型模式工厂 (Factory)构造函数模式 (Constructor)原型 (Prototype) - 实现对...

网友评论

      本文标题:原型模式 C++实现

      本文链接:https://www.haomeiwen.com/subject/jmffmqtx.html