实例讲解C++编程中对设计模式中的原型模式的使用

2020-01-06 14:38:31于丽
易采站长站为您分析C++编程中对设计模式中的原型模式的使用实例,包括原型模式中对C++的深拷贝和浅拷贝的处理,需要的朋友可以参考下  

原型模式的实现完整代码示例(code):原型模式的实现很简单,这里为了方便初学者的学习和参考,将给出完整的实现代码(所有代码采用 C++实现,并在 VC 6.0 下测试运行)。

代码片断 1:Prototype.h


//Prototype.h
#ifndef _PROTOTYPE_H_
#define _PROTOTYPE_H_
class Prototype{
 public:
 virtual ~Prototype();
 virtual Prototype* Clone() const = 0;
 protected:
 Prototype();
 private:
};
class ConcretePrototype:public Prototype{
 public:
 ConcretePrototype();
 ConcretePrototype(const ConcretePrototype& cp);
 ~ConcretePrototype();
 Prototype* Clone() const;
 protected:
 private:
};
#endif //~_PROTOTYPE_H_

代码片断 2:Prototype.cpp


//Prototype.cpp
#include "Prototype.h"
#include <iostream>
using namespace std;
Prototype::Prototype(){
}
Prototype::~Prototype(){
}
Prototype* Prototype::Clone() const{
 return 0;
}
ConcretePrototype::ConcretePrototype(){
}
ConcretePrototype::~ConcretePrototype(){
}
ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp){
 cout<<"ConcretePrototype copy ..."<<endl;
}
Prototype* ConcretePrototype::Clone() const{
 return new ConcretePrototype(*this);
}

代码片断 3:main.cpp


//main.cpp
#include "Prototype.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[]){
 Prototype* p = new ConcretePrototype();
 Prototype* p1 = p->Clone();
 return 0;
}

代码说明:原型模式的结构和实现都很简单,其关键就是(C++中)拷贝构造函数的实现方式,这也是 C++实现技术层面上的事情。由于在示例代码中不涉及到深层拷贝(主要指有指针、复合对象的情况),因此我们通过编译器提供的默认的拷贝构造函数(按位拷贝)的方式进行实现。说明的是这一切只是为了实现简单起见,也因为本文档的重点不在拷贝构造函数的实现技术,而在原型模式本身的思想。

另一个实例

我们再来看一个具体项目的例子:


namespace Prototype_DesignPattern
{
 using System;

 // Objects which are to work as prototypes must be based on classes which 
 // are derived from the abstract prototype class
 abstract class AbstractPrototype 
 {
  abstract public AbstractPrototype CloneYourself();
 }

 // This is a sample object
 class MyPrototype : AbstractPrototype 
 {
  override public AbstractPrototype CloneYourself()
  {
   return ((AbstractPrototype)MemberwiseClone());
  }
  // lots of other functions go here!
 }

 // This is the client piece of code which instantiate objects
 // based on a prototype. 
 class Demo 
 {
  private AbstractPrototype internalPrototype;

  public void SetPrototype(AbstractPrototype thePrototype)
  {
   internalPrototype = thePrototype;   
  }

  public void SomeImportantOperation()
  {
   // During Some important operation, imagine we need
   // to instantiate an object - but we do not know which. We use
   // the predefined prototype object, and ask it to clone itself. 

   AbstractPrototype x;
   x = internalPrototype.CloneYourself();
   // now we have two instances of the class which as as a prototype
  }
 }

 /// <summary>
 /// Summary description for Client.
 /// </summary>
 public class Client
 {
  public static int Main(string[] args)
  {      
   Demo demo = new Demo();
   MyPrototype clientPrototype = new MyPrototype();
   demo.SetPrototype(clientPrototype);
   demo.SomeImportantOperation();

   return 0;
  }
 }
}