C++设计模式实现--原型模式(高屋建瓴)

例一
原网址:https://lcxing.blog.csdn.net/article/details/79521841
参考网址:https://blog.csdn.net/lin_duo/article/details/84888766

#include <iostream>
using namespace std;
class Sheep {
  friend ostream& operator<<(ostream&, Sheep& sheep);
 public:
  Sheep(char* name, int age) {
    age_ = age;
    name_ = new char[strlen(name)+1];
    strcpy(name_, name);
  }
  Sheep(const Sheep& sheep) {
    age_ = sheep.age_;
    name_ =  new char[strlen(sheep.name_)+1];
    strcpy(name_, sheep.name_);
  }
  ~Sheep() {
    if (name_ != NULL) {
      delete name_;
    }
  }
  Sheep& operator=(const Sheep& sheep) {
    if (this == &sheep) {
      return *this;
    }
    if (name_ != NULL) {
      delete name_;
      name_ = NULL;
    }
    age_ = sheep.age_;
    name_ = new char[strlen(sheep.name_)+1];
    strcpy(name_, sheep.name_);
  }
  Sheep* Clone() {
    return new Sheep(*this);
  }
  char* GetName() {
    return name_;
  }
  void SetName(char* name) {
    if (name_ != NULL) {
      delete name_;
      name_ = NULL;
    }
  }
  int GetAge() {
    return age_;
  }
  void SetAge(int age) {
    age_ = age;
  }
 private:
  char *name_;
  int age_;
};
ostream& operator<<(ostream&, Sheep& sheep) {
  cout << "[name = " << sheep.name_<< ", age = " << sheep.age_ << "]";
  return cout;
}
int main() {
  Sheep* sheep1 = new Sheep("douli", 0);
  Sheep* sheep2 = sheep1->Clone();
  cout<<"sheep1:"<<*sheep1<<endl;
  cout << "sheep2:" << *sheep2 << endl;
  cout << "shanchu clone yuanxin sheep1" << endl;
  delete sheep1;
  cout << "sheep2:" << *sheep2 << endl;
  return 0;
}
运行结果:
sheep1:[name = douli, age = 0]
sheep2:[name = douli, age = 0]
shanchu clone yuanxin sheep1
sheep2:[name = douli, age = 0]

留意:
ostream& operator<<(ostream&, Sheep& sheep)

例二:
原网址:https://blog.csdn.net/CoderAldrich/article/details/83115203

#include <iostream>
using namespace std;
//接口
class Prototype {
 public:
  Prototype() {}
  virtual ~Prototype() {}
  virtual Prototype * Clone() = 0;
};
//实现
class ConcretePrototype : public Prototype {
 public:
  ConcretePrototype():counter_(0) {}
  virtual ~ConcretePrototype() {}

  //拷贝构造函数
  ConcretePrototype(const ConcretePrototype& rhs) {
   counter_ = rhs.counter_;
  }
  //复制自身
  virtual ConcretePrototype * Clone(){
    //调用拷贝构造函数
    return new ConcretePrototype (*this );
  }
  int counter_;
};

int main(){
  //生成对像
  ConcretePrototype * conProA = new ConcretePrototype ();
  //复制自身
  ConcretePrototype * conProB = conProA->Clone();
  cout << conProB->counter_ << endl;
  conProB->counter_ = 1;
  cout << conProB->counter_ << endl;
  delete conProA;
  conProA = NULL ;
  delete conProB;
  conProB = NULL ;
  return 0;
}

运行结果:
0
1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值