⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 factory.cpp

📁 自己写的c++实现的headfirst中的设计模式
💻 CPP
字号:
/* *工厂模式
 */

#include <iostream>
#include <string>

using namespace std;

//产品基类
class VirtualProduct	//共用可修改public:cost() display()
{
protected:
	string name;
	double size;
	double price;
	
public:
	virtual void display()	//不用virtual 后面的clampizza的display将无法覆盖此方法
	//不用virtual将保护原成员!无法复写!
	{
		cout <<"Name:"+name<<endl
			<<"Size:"<<size<<endl
			<<"Cost:"<<price<<endl;
	}
	
	virtual void cost()
	{
		cout << "cost -"<<price<<" from the account!"<<endl; 
	}
	
};
	
//工厂基类
class VirtualFactory	//共用可修改public:buy()
{
protected:
	string factoryName;
	VirtualProduct* prt;
	virtual VirtualProduct* ProductSelector(string)=0;
	
public:
	virtual void buy(string n)
	{
		prt=ProductSelector(n);
		prt->display();
		prt->cost();
	}
	
};

//生成产品!
class CheesPizza:public VirtualProduct
{
public:
	CheesPizza()
	{
		name="CheesPizza";
		size=12;
		price=35;
	}
};

class CheesPizzaOnsale:public VirtualProduct  //重写cost()
{
public:
	CheesPizzaOnsale()
	{
		name="CheesPizza On sale!";
		size=12;
		price=35;
	}
	
	void cost()
	{
		cout << "cost -"<<price/2<<" from the account!"<<endl;
	}
};

class ClamPizza:public VirtualProduct	//续写display()
{
public:
	ClamPizza()
	{
		name="ClamPizza";
		size=10;
		price=28;
	}
	
	void display()
	{
		VirtualProduct::display();
		cout << "Italy flaver~!"<<endl;
	}
};

// Virtual Book //protected将永远protected之下继续继承仍可修改!
// 重写display() for books
class Book:public VirtualProduct
{
	virtual void display()
	{
		cout <<"Name:"+name<<endl
		<<"Cost:"<<price<<endl;
	}
};

class HarryPorter:public Book
{
public:
	HarryPorter()
	{
		//protected 将永远是protected!
		name="HarryPorter";		//还能为祖父级的protected赋值!
		price=88;
	}
	
};

class RainMan:public Book	//重写祖父类cost()
{
public:
	RainMan()
	{
		name="RainMan";
		price=64.5;
	}
	
	void cost()
	{
		cout << "this free for you!"<<endl;
	}
};

//生成工厂!		//主要实例化ProductSelector方法
class PizzaFactory:public VirtualFactory
{
private:
	VirtualProduct* ProductSelector(string n)
	{
		if (n=="CheesPizza") return new CheesPizza;
		else if(n=="CheesPizzaOnsale")return new CheesPizzaOnsale;
		else if(n=="ClamPizza")return new ClamPizza();
		else return NULL;
	}
};

class BookFactory:public VirtualFactory		//续写buy()
{
private:
	VirtualProduct* ProductSelector(string n)
	{
		if(n=="HarryPorter") return new HarryPorter;
		else if(n=="RainMan") return new RainMan;
		else return NULL;
	}

public:
	void buy(string n)
	{
		VirtualFactory::buy(n);
		cout << "Wellcome Back Again ,We'll Give you an price off!"<<endl;
	}
};

void factory_main()
{
	PizzaFactory pf;
	pf.buy("CheesPizza");
	pf.buy("CheesPizzaOnsale");
	pf.buy("ClamPizza");
	
	cout <<endl;
	
	BookFactory bf;
	bf.buy("HarryPorter");
	bf.buy("RainMan");
	//bf.buy(""); 异常!

}

	

	
	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -