C++二十三种设计模式之原型模式

C++二十三种设计模式之原型模式

一、组成

抽象原型类 :声明克隆接口。
具体原型类:实现克隆接口。

二、特点

1、通过具体原型类克隆的对象只是部分属性值不同。

2、克隆函数内部可用拷贝构造函数赋值。

三、目的

通过已有对象来复制新对象,不同对象之间仅部分属性有差异。

四、缺点

1、场景限制问题,如果对象内部存在循环引用或动态分配的资源会比较麻烦。

2、深拷贝和浅拷贝问题,对象有嵌套结构则需要复杂的深拷贝逻辑。

五、示例代码

javascript 复制代码
#include<iostream>
#include <vector>
#include <list>
#include <string>
#include <mutex>
#include <map>
#include<stack>

using namespace std;

class Prototype;//抽象原型类
class BaseCharacter;//抽象类
class Player;//具体原型类
class Enemy;//具体原型类

class Prototype {
public:
	Prototype() {}
	virtual shared_ptr<Prototype> clone() = 0;
	virtual void setHealth(int health) = 0;
	virtual void setAttack(int attack) = 0;
	virtual void setDefense(int defense) = 0;
	virtual void setName(string name) = 0;
	virtual void print() = 0;
};

class BaseCharacter : public Prototype {
public:
	BaseCharacter() {}
	BaseCharacter(string name, int health, int attack, int defense) :m_name(name), m_health(health), m_attack(attack), m_defense(defense) {};
	void setHealth(int health) {
		m_health = health;
	};
	void setAttack(int attack) {
		m_attack = attack;
	};
	void setDefense(int defense) {
		m_defense = defense;
	};
	void setName(string name) {
		m_name = name;
	};
	void print() {
		cout << "name:" << m_name << ",health:" << m_health << endl;
	}
protected:
	int m_health;
	int m_attack;
	int m_defense;
	string m_name;
};

class Player : public BaseCharacter {
public:
	Player(string name, int health, int attack, int defense) : BaseCharacter(name, health, attack, defense) {};

	~Player() {
		cout << "~Player " << m_name << endl;
	}
	shared_ptr<Prototype> clone() {
		return make_shared<Player>(*this);
	};
};

class Enemy : public BaseCharacter {
public:
	Enemy(string name, int health, int attack, int defense) : BaseCharacter(name, health, attack, defense) {};
	~Enemy() {
		cout << "~Enemy " << m_name << endl;
	}

	shared_ptr<Prototype> clone() {
		return make_shared<Enemy>(*this);
	};
};
void test() {

	auto player1 = make_shared<Player>("Player1", 1, 2, 3);
	player1->setHealth(100);
	auto player2 = player1->clone();
	player2->setName("Player2");
	player1->setHealth(1000);

	player2->print();
	player1->print();
}
int main() {
	test();
}
相关推荐
从零开始的代码生活_13 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
aaPIXa62214 小时前
C++ 用 13 条规则让模型写出安全现代 C++
java·c++·安全
枕星而眠15 小时前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
2601_9498177215 小时前
C++指针与引用深度精讲:底层原理、差异对比与高阶实战陷阱
java·jvm·c++
烟锁池塘柳017 小时前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
zh路西法17 小时前
【10天速通Navigation2】(九):LQR最优控制器的原理推导与Nav2插件实现
c++·ros2·最优控制·lqr·navigation2
粘稠的浆糊17 小时前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
誰能久伴不乏17 小时前
C++11 随机数生成——告别 rand()
开发语言·c++
KouFiee18 小时前
同名隐藏基础
开发语言·c++
从零开始的代码生活_18 小时前
C++ string 详解:常用接口、字符串算法与深拷贝实现
开发语言·c++·后端·学习·算法