现在的位置: 首页 > 综合 > 正文

设计模式–简单工厂

2013年10月08日 ⁄ 综合 ⁄ 共 1050字 ⁄ 字号 评论关闭
#include <Windows.h>
#include <iostream>
#include <atlstr.h>
using namespace std;
class Pizza{
public:
	virtual void Prepare() = 0;
	virtual void Bake() = 0;
	virtual void Cut() = 0;
	virtual void Box() = 0;
};
class CheesePizza : public Pizza{
public:
	void Prepare(){}
	void Bake() {}
	void Cut(){}
	void Box() {}
};
class ClamPizza : public Pizza{
public:
	void Prepare(){}
	void Bake() {}
	void Cut(){}
	void Box() {}
};

class PizzaFactory{
public:
	Pizza* CreateInstance( CString strType ){
		Pizza* pPizza = NULL;
		if( strType == TEXT("cheese") ){
			pPizza = new CheesePizza;
		}
		else if( strType == TEXT("clam") ){
			pPizza  = new ClamPizza;
		}
		//...
		return pPizza;
	}
};
class PizzaStore{
private:
	PizzaFactory* m_pPizzaFactory;
public:
	PizzaStore( PizzaFactory* pPizzaFactory ) : m_pPizzaFactory( pPizzaFactory ){  }
	Pizza* orderPizza( CString strType ){
		if( m_pPizzaFactory == NULL )
			return NULL;

		Pizza *pPizza = m_pPizzaFactory->CreateInstance( strType );
		if( pPizza != NULL )
		{
			pPizza->Prepare();
			pPizza->Bake();
			pPizza->Cut();
			pPizza->Box();
		}
		return pPizza;
	}
};
void main()
{
	PizzaFactory* pPF = new PizzaFactory();
	PizzaStore *pStore = new PizzaStore( pPF );
	Pizza *pPizza = pStore->orderPizza( TEXT("...") );

	system("pause");
	return;
}

【上篇】
【下篇】

抱歉!评论已关闭.