// 设计模式测试.cpp : 定义控制台应用程序的入口点。
// 工厂方法模式
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
#include <list>
using namespace std;
/*********************工厂方法模式之Pizza示例*************************************/
//披萨产品基类
class Pizza
{
protected:
string name;
string dough;
string sauce;
public:
void prepare(){
cout << "pizza is prepared" << endl;
}
void bake() {
cout << "pizza is baked" << endl;
}
void cut() {
cout << "pizza is cut" << endl;
}
void box() {
cout << "pizza is boxed" << endl;
}
string getName() {
return name;
}
};
class FirstPizza:public Pizza
{
public:
FirstPizza() {
name = "First Pizza";
dough = "Thin Crust Dough";
sauce = "First Sauce";
}
};
class SecondPizza :public Pizza
{
public:
SecondPizza() {
name = "Second Pizza";
dough = "Crust Dough";
sauce = "Second Sauce";
}
};
class ThirdPizza :public Pizza
{
public:
ThirdPizza() {
name = "Third Pizza";
dough = "Command Dough";
sauce = "Command Sauce";
}
};
class FourthPizza :public Pizza
{
public:
FourthPizza() {
name = "Fourth Pizza";
dough = "Command Dough";
sauce = "Command Sauce";
}
};
class CommandPizza :public Pizza
{
public:
CommandPizza() {
name = "Command Pizza";
dough = "Command Dough";
sauce = "Command Sauce";
}
};
//披萨工厂
class PizzaStore
{
protected:
virtual Pizza* createPizza(string type)=0;
public:
Pizza* OrderPizza(string type) {
Pizza *pizza;
pizza = createPizza(type);
pizza->prepare();
pizza->bake();
pizza->cut();
pizza->box();
return pizza;
}
};
class APizzaStore:public PizzaStore
{
public:
Pizza* createPizza(string type) {
if (type == "1") {
return new FirstPizza();
}
else if (type == "3"){
return new ThirdPizza();
}
else {
return new FourthPizza();
}
};
};
class BPizzaStore :public PizzaStore
{
public:
Pizza* createPizza(string type) {
if (type == "2") {
return new SecondPizza();
}
else if (type == "3") {
return new ThirdPizza();
}
else {
return new CommandPizza();
}
};
};
//主函数
int main()
{
PizzaStore *aStore = new APizzaStore();
PizzaStore *bStore = new BPizzaStore();
Pizza *pizza = aStore->OrderPizza("1");
cout << "get a " << pizza->getName() << " from " << "aStore" << endl;
pizza = aStore->OrderPizza("3");
cout << "get a " << pizza->getName() << " from " << "aStore" << endl;
pizza = bStore->OrderPizza("2");
cout << "get a " << pizza->getName() << " from " << "bStore" << endl;
pizza = bStore->OrderPizza("1");
cout << "get a " << pizza->getName() << " from " << "bStore" << endl;
system("Pause");
return 0;
}
C++:设计模式之工厂方法模式(例子)
最新推荐文章于 2024-06-11 10:14:48 发布