C++學習經歷(十四)建造者模式
建造者模式
將產品的內部表象和產品的生產過程分割開來,從而使一個建造過程生成具有不同的內部表象的產品物件。建造者模式使得產品內部表象可以獨立的變化,客戶不必知道產品內部實現的細節。建造者模式可以強制實行一種分步驟進行的建造過程。
例子:一個房子(House)有門(Door)和牆(Wall),建造者(Builder)在建造屋子的時候需要造門和牆,但是我們並不需要知道如何建造門和牆、我們只需要派遣建造者去造屋子就可以了,不同的建造者自己就會建造出不同的屋子。我們通過設計者(Designer)選擇不同的建造者,直接造出屋子,並不需要知道具體的內部實現過程。
#include <iostream>
using namespace std;
class House
{
private:
string m_Wall;
string m_Door;
public:
void set_wall(string w)
{
m_Wall = w;
}
void set_door(string d)
{
m_Door = d;
}
string get_wall()
{
return m_Wall;
}
string get_door()
{
return m_Door;
}
};
class Builder
{
protected:
House *house;
public:
virtual void Constructor() = 0;
virtual House *get_house() = 0;
virtual void builder_wall(string w) = 0;
virtual void builder_door(string d) = 0;
};
class CommonBuilder : public Builder
{
public:
CommonBuilder()
{
house = new House;
}
void Constructor()
{
builder_wall("COMMONWALL");
builder_door("COMMOONDOOR");
}
House *get_house()
{
return house;
}
private:
void builder_wall(string w)
{
house -> set_wall(w);
}
void builder_door(string d)
{
house -> set_door(d);
}
};
class VillaBuilder : public Builder
{
public:
VillaBuilder()
{
house = new House;
}
void Constructor()
{
builder_wall("VILLAWALL");
builder_door("VILLADOOR");
}
House *get_house()
{
return house;
}
private:
void builder_wall(string w)
{
house -> set_wall(w);
}
void builder_door(string d)
{
house -> set_door(d);
}
};
class Designer
{
private:
Builder *builder;
public:
void set_builder(Builder *b)
{
builder = b;
}
void Constructor()
{
builder -> Constructor();
}
};
int main(int argc, char **argv)
{
House *house = NULL;
Builder *builder = NULL;
Designer *designer = new Designer;
builder = new CommonBuilder;
designer -> set_builder(builder);
designer -> Constructor();
house = builder -> get_house();
cout << house -> get_wall() << endl;
cout << house -> get_door() << endl;
return 0;
}