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();
}
相关推荐
ha204289419436 分钟前
Linux操作系统学习之---基于环形队列的生产者消费者模型(毛坯版)
linux·c++·学习
你的人类朋友2 小时前
设计模式有哪几类?
前端·后端·设计模式
渡我白衣3 小时前
C++ 同名全局变量:当符号在链接器中“相遇”
开发语言·c++·人工智能·深度学习·microsoft·语言模型·人机交互
你的人类朋友3 小时前
适配器模式:适配就完事了bro!
前端·后端·设计模式
是那盏灯塔4 小时前
【算法】——动态规划之01背包问题
数据结构·c++·算法·动态规划
迷失的walker5 小时前
【Qt C++ QSerialPort】QSerialPort fQSerialPortInfo::availablePorts() 执行报错问题解决方案
数据库·c++·qt
南方的狮子先生7 小时前
【数据结构】(C++数据结构)查找算法与排序算法详解
数据结构·c++·学习·算法·排序算法·1024程序员节
紫荆鱼7 小时前
设计模式-适配器模式(Adapter)
c++·设计模式·适配器模式
报错小能手8 小时前
C++笔记(面向对象)详解单例模式
c++·笔记·单例模式
吗~喽9 小时前
【C++】内存管理
c++