c++23种设计模式之原型模式

#include <stdio.h>

////c++ 23种设计模式之原型模式
//适用情况:1、请求一个原型克隆自身
namespace DesignPattern_Prototype
{
	class Prototype
	{

	public:
		virtual Prototype * Clone()=0;
		virtual void showInfo()=0;

	};
	class ConcretePrototype1:public Prototype
	{

	public:
		virtual Prototype *Clone()
		{

			ConcretePrototype1 *p=new ConcretePrototype1;
			*p=*this;//复制对象
			return p;
		}
		void showInfo()
		{

			printf("我是 ConcretePrototype1 \n");
		}
	};
	class ConcretePrototype2:public Prototype
	{

	public:
		virtual Prototype* Clone()
		{

			ConcretePrototype2 *p=new ConcretePrototype2;
			*p=*this;
			return p;
		}
		void showInfo()
		{
			
			printf("我是 ConcretePrototype2 \n");
		}

	};

}

void main()
{
	using namespace DesignPattern_Prototype;
	 ConcretePrototype1 *obj1=new ConcretePrototype1;
	 ConcretePrototype2 *obj2=new ConcretePrototype2();
	 Prototype *newobj1=obj1->Clone();
	 Prototype *newobj2=obj2->Clone();

	 newobj1->showInfo();
	 newobj2->showInfo();

}

你可能感兴趣的:(c++23种设计模式之原型模式)