代码实现:
#include <iostream>
#include <string>
using namespace std;
class House
{
public:
void setDoor(string door)
{
this->door = door;
}
void setWall(string wall)
{
this->wall = wall;
}
void setWindow(string window)
{
this->window = window;
}
string getDoor()
{
return this->door;
}
string getWall()
{
return this->wall;
}
string getWindow()
{
return this->window;
}
private:
};string door;
string wall;
string window;
class Builder {
public:
virtual House* getHouse() = 0;
virtual void buildDoor() = 0;
virtual void buildWall() = 0;
virtual void buildWindow() = 0;
};
class FlatBuilder :public Builder
{
public:
private :FlatBuilder()
{
house = new House;
}
House* getHouse()
{
return house;
}
void buildDoor()
{
this->house -> setDoor("flat door");
}
void buildWall()
{
this->house->setWall("flat wall");
}
void buildWindow()
{
this->house->setWindow("flat window");
}
House* house;
};
class VillaBuilder :public Builder
{
public:
VillaBuilder()
{
house = new House;
}
House* getHouse()
{
return house;
}
void buildDoor()
{
this->house->setDoor("villa door");
}
void buildWall()
{
this->house->setWall("villa wall");
}
void buildWindow()
{
this->house->setWindow("villa window");
}
private:
House* house;
};
class Director
{
public:
Director(Builder* builder)
{
this->builder = builder;
}
void construct()
{
builder->buildDoor();
builder->buildWall();
builder->buildWindow();
}
private:
Builder* builder;
};
void main() {
}Builder* builder = NULL;
Director* director = NULL;
House* house = NULL;
builder = new FlatBuilder;
director = new Director(builder);
director->construct();
house = builder->getHouse();
cout << house->getDoor() << endl;
cout << house->getWall() << endl;
cout << house->getWindow() << endl;
delete house;
delete builder;
delete director;
builder = new VillaBuilder;
director = new Director(builder);
director->construct();
house = builder->getHouse();
cout << house->getDoor() << endl;
cout << house->getWall() << endl;
cout << house->getWindow() << endl;
delete house;
delete builder;
delete director;