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();
}
相关推荐
·薯条大王4 小时前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
用户938515635075 小时前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformer.js 全链路实战
前端·设计模式·typescript
hansang_IR9 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
东东最爱敲键盘9 小时前
day7.c++继承
c++
AI人工智能+电脑小能手10 小时前
大白话说Java设计模式-04-工厂方法模式(业务实战篇)
java·设计模式·工厂方法模式·架构设计·代码解耦
沫璃染墨10 小时前
《从零入门Linux系统篇(十五):系统工具篇·六——GDB调试器详解:从程序执行控制到高级调试技巧》
linux·运维·服务器·c语言·c++
吃着火锅x唱着歌10 小时前
Effective C++ 学习笔记 条款40 明智而审慎地使用多重继承
c++·笔记·学习
醉城夜风~11 小时前
(超详细)C++ STL list容器详解:从使用方法到双向链表底层原理全面解析
c++·windows
烟花落o11 小时前
C++ 从 C 到进阶 ②:引用、inline 、nullptr
c++·引用·inline·nullptr·c++入门
liulilittle11 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm