学习笔记——原型模式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 }
原文地址:https://www.cnblogs.com/dev2007/p/3557007.html