zoukankan      html  css  js  c++  java
  • 学习笔记——原型模式Prototype

    原型模式,简单说就是具有一个克隆方法,外部可以直接使用此方法得到相应对象的拷贝对象。

    比如哆啦A梦的复制镜,一照,就把物品拷贝了一份(虽然是镜子复制是相反的,这里就忽略这个细节了)

    C++中依靠拷贝构造函数来得到拷贝。

    IPrototype* CPrototype::Clone() const
    {
        return new CPrototype(*this);
    }

    C#中浅拷贝依靠MemberwiseClone来实现,深拷贝需要自己实现,依靠 [Serializable]、MemoryStream或者简单的new新对象,然后复制值。

            public CPrototype Clone()
            {
                return this.MemberwiseClone() as CPrototype;
            }

    C++示例

    IPrototype.h

    1 #pragma once
    2 class IPrototype
    3 {
    4 public:
    5     IPrototype(void);
    6     virtual ~IPrototype(void);
    7 public:
    8     virtual IPrototype* Clone() const = 0;
    9 };

    IPrototype.cpp

     1 #include "IPrototype.h"
     2 
     3 
     4 IPrototype::IPrototype(void)
     5 {
     6 }
     7 
     8 
     9 IPrototype::~IPrototype(void)
    10 {
    11 }

    Prototype.h

     1 #pragma once
     2 #include "iprototype.h"
     3 class CPrototype :
     4     public IPrototype
     5 {
     6 public:
     7     CPrototype(void);
     8     CPrototype(const CPrototype& cp);
     9     CPrototype operator =(const CPrototype& cp);
    10     ~CPrototype(void);
    11 public:
    12     IPrototype* Clone() const;
    13 private:
    14     int a;
    15 };

    Prototype.cpp

     1 #include "Prototype.h"
     2 
     3 
     4 CPrototype::CPrototype(void)
     5 {
     6 }
     7 
     8 
     9 CPrototype::~CPrototype(void)
    10 {
    11 }
    12 
    13 CPrototype::CPrototype(const CPrototype& cp)
    14 {
    15     this->a = cp.a;
    16 }
    17 
    18 CPrototype CPrototype::operator=(const CPrototype& cp)
    19 {
    20     this->a = cp.a;
    21     return *this;
    22 }
    23 
    24 IPrototype* CPrototype::Clone() const
    25 {
    26     return new CPrototype(*this);
    27 }

    main.cpp

    1 #include "Prototype.h"
    2 #include <iostream>
    3 
    4 int main()
    5 {
    6     IPrototype* p1 = new CPrototype();
    7     IPrototype* p2 = p1->Clone();
    8     return 0;
    9 }
  • 相关阅读:
    程序员是脑力劳动还是体力劳动
    我理解的技术管理的核心工作----搭班子和带团队
    Ubuntu系统下在PyCharm里用virtualenv集成TensorFlow
    我理解的技术管理的核心工作----定战略
    数据分析师岗位的一点理解
    python中读写excel并存入mysql
    mac里用PyCharm中引用MySqlDB始末
    贝叶斯网络的通俗解读
    将sqlserver导出的csv数据导入到ubuntu和mac上的mysql
    Java之Spring Cloud概念介绍(非原创)
  • 原文地址:https://www.cnblogs.com/dev2007/p/3557007.html
Copyright © 2011-2022 走看看