【1】什么是建造者模式?
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
【2】建造者模式代码示例:
代码示例1:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Person
{
public:
virtual void createHead() = 0;
virtual void createHand() = 0;
virtual void createBody() = 0;
virtual void createFoot() = 0;
};
class ThinPerson : public Person
{
void createHead()
{
cout << "thin head" << endl;
}
void createHand()
{
cout << "thin hand" << endl;
}
void createBody()
{
cout << "thin body" << endl;
}
void createFoot()
{
cout << "thin foot" << endl;
}
};
class FatPerson : public Person
{
void createHead()
{
cout << "fat head" << endl;
}
void createHand()
{
cout << "fat hand" << endl;
}
void createBody()
{
cout << "fat body" << endl;
}
void createFoot()
{
cout << "fat foot" << endl;
}
};
class Director
{
private:
Person *p;
public:
Director(Person *temp)
{
p = temp;
}
void create()
{
p->createHead();
p->createHand();
p->createBody();
p->createFoot();
}
};
//客户端代码:
int main()
{
Person *p = new FatPerson();
Person *b = new ThinPerson();
Director *d = new Director(p);
Director *s = new Director(b);
d->create();
s->create();
delete d;
delete p;
delete s;
delete b;
return 0;
}
代码示例2:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Product
{
private:
vector<string> product;
public:
void add(string str)
{
product.push_back(str);
}
void show()
{
vector<string>::iterator iter = product.begin();
while (iter != product.end())
{
cout << *iter << " ";
++iter;
}
cout << endl;
}
};
class Builder
{
public:
virtual void builderA() = 0;
virtual void builderB() = 0;
virtual Product *getResult() = 0;
};
class ConcreteBuilder1 : public Builder
{
private:
Product *product;
public:
ConcreteBuilder1()
{
product = new Product();
}
virtual void builderA()
{
product->add("one");
}
virtual void builderB()
{
product->add("two");
}
virtual Product *getResult()
{
return product;
}
};
class ConcreteBuilder2 : public Builder
{
private:
Product *product;
public:
ConcreteBuilder2()
{
product = new Product();
}
virtual void builderA()
{
product->add("A");
}
virtual void builderB()
{
product->add("B");
}
virtual Product *getResult()
{
return product;
}
};
class Director
{
private:
Product *p;
public:
void construct(Builder *bd)
{
bd->builderA();
bd->builderB();
p = bd->getResult();
}
Product *getResult()
{
return p;
}
};
int main()
{
Director *director = new Director();
Builder *bd1 = new ConcreteBuilder1();
director->construct(bd1);
Product *pbd1 = director->getResult();
pbd1->show();
return 0;
}