// buliderpattern.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Food
{
private:
vector<double> m_vecFoodPrice;
vector<string> m_vecFoodName;
public:
void Add(double dFoodPrice, const string &strFoodName)
{
m_vecFoodPrice.push_back(dFoodPrice);
m_vecFoodName.push_back(strFoodName);
}
void DisPlay()
{
cout << "food list" << endl;
cout << "................." << endl;
for (int i = 0; i < m_vecFoodName.size(); ++i)
{
cout << m_vecFoodName[i] << ":" << m_vecFoodPrice[i] << endl;
}
}
};
class Builder
{
public:
virtual Food* getFood() { return NULL; }
virtual void buildNoodle() {}
virtual void buildDrink() {}
virtual void buildRice() {}
};
class BuilderA : public Builder
{
private:
Food* m_food;
public:
BuilderA() { m_food = new Food(); }
virtual void buildNoodle()
{
m_food->Add(10.1, "NoodleA");
}
virtual void buildDrink()
{
m_food->Add(10.2, "DrinkA");
}
virtual void buildRice()
{
m_food->Add(10.3, "RiceA");
}
virtual Food* getFood()
{
return m_food;
}
};
class BuilderB : public Builder
{
private:
Food* m_food;
public:
BuilderB() { m_food = new Food(); }
virtual void buildNoodle()
{
m_food->Add(20.1, "NoodleB");
}
virtual void buildDrink()
{
m_food->Add(20.2, "DrinkB");
}
virtual void buildRice()
{
m_food->Add(20.3, "RiceB");
}
virtual Food* getFood()
{
return m_food;
}
};
class FoodManger
{
private:
Builder* m_Builder;
public:
FoodManger(Builder* Builder) { m_Builder = Builder;}
void Construct()
{
m_Builder->buildDrink();
m_Builder->buildNoodle();
m_Builder->buildRice();
}
};
int main()
{
Builder* p2b = new Builder();
cout << "input A or B" << endl;
char ch;
cin >> ch;
if (ch == 'A')
p2b = new BuilderA();
else if (ch == 'B')
p2b = new BuilderB();
FoodManger* p2fm = new FoodManger(p2b);
p2fm->Construct();
Food* food = p2b->getFood();
food->DisPlay();
return 0;
}
建造者模式 - C++实现
最新推荐文章于 2024-08-18 17:42:33 发布