标签:创建型 创建型模式 没有 创建 strong col RKE void set
一共涉及到三个类:产品类,建造者类,用户类
优点:将一个复杂对象的构造和它的表示分离。这样易于扩展。
缺点:如果构建发生变化,所有的建造者都要变化。
//产品类,果汁
class Juice{
public:
Juice(){}
void setVolume(double v){
m_volume = v;
}
void setColor(string color){
m_color = color;
}
private:
double m_volume;
string m_color;
}
//建造者抽象类
class Maker{
public:
Maker():p_juice(NULL){}
void createJuice(){
if(p_juice==NULL)
p_juice = new Juice();
}
Juice* getJuice(){
return p_juice;
}
virtual void squeezeVolume() = 0;
virtual void mixColor() = 0;
private:
Juice* p_juice;
}
class GrapeJuiceMaker : public Maker{
public:
void squeezeVolome(){
p_juice->setVolume(1000);
}
void mixColor(){
p_juice->setColor("Purple");
}
}
class AppleJuiceMaker: public Maker{
public:
void squeezeVolome(){
if(p_juice!=NULL)
p_juice->setVolume(500);
}
void mixColor(string color){
if(p_juice!=NULL)
p_juice->setColor("Green");
}
}
//用户类
class Worker{
public:
Worker():m_maker(NULL){}
void setMaker(Maker* m){
m_maker = m;
}
Juice* makeJuice{
if(m_maker==NULL)
return NULL;
m_maker->createJuice();
m_maker->squeezeVolume();
m_maker->mixColor();
pjuice = m_maker->getJuice();
return pjuice;
}
private:
Maker* m_maker;
}
int main(){
Worker* w = new Worker(); //定义工人
AppleJuiceMaker* maker1 = new AppleJuiceMaker(); //定义机器
Juice* a1 = w.makeJuice(); //就能直接得到果汁
}
本文参考
标签:创建型 创建型模式 没有 创建 strong col RKE void set
原文地址:https://www.cnblogs.com/corineru/p/12000934.html