例一:
#include
#include
#include
using namespace std;
//最终的产品类
class Product
{
private:
vector m_product;
public:
void Add(string stremp)
{
m_product.push_back(stremp);
}
void Show()
{
vector::iterator p = m_product.begin();
while(p != m_product.end())
{
cout << *p << endl;
p++;
}
}
};
//建造者基类
class Builder
{
public:
virtual void BuilderA()=0;
virtual void BuilderB()=0;
virtual Product* GetResult()=0;
};
//第一类建造方式
class ConcreteBuilder1 : public Builder
{
private:
Product* m_product;
public:
ConcreteBuilder1()
{
m_product = new Product();
}
virtual void BuilderA()
{
m_product->Add("one");
}
virtual void BuilderB()
{
m_product->Add("two");
}
virtual Product* GetResult()
{
return m_product;
}
};
//第二类建造方式
class ConcreteBuilder2 : public Builder
{
private:
Product* m_product;
public:
ConcreteBuilder2()
{
m_product = new Product();
}
virtual void BuilderA()
{
m_product->Add("A");
}
virtual void BuilderB()
{
m_product->Add("B");
}
virtual Product* GetResult()
{
return m_product;
}
};
//指挥者类
class Direct
{
public:
void Construct(Builder* temp)
{
temp->BuilderA();
temp->BuilderB();
}
};
//客户端
int main()
{
Direct* p = new Direct();
Builder* b1 = new ConcreteBuilder1();
Builder* b2 = new ConcreteBuilder2();
p->Construct(b1); //调用第一种方式
Product* pb1 = b1->GetResult();
pb1->Show();
p->Construct(b2); //调用第二种方式
Product* pb2 = b2->GetResult();
pb2->Show();
return 0;
}
#include
#include
#include
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
{
public:
virtual void CreateHead()
{
cout << "this head" << endl;
}
virtual void CreateHand()
{
cout << "this hand" << endl;
}
virtual void CreateBody()
{
cout << "this body" << endl;
}
virtual void CreateFoot()
{
cout << "this foot" << endl;
}
};
class ThickPerson : public Person
{
public:
virtual void CreateHead()
{
cout << "ThickPerson head" << endl;
}
virtual void CreateHand()
{
cout << "ThickPerson hand" << endl;
}
virtual void CreateBody()
{
cout << "ThickPerson body" << endl;
}
virtual void CreateFoot()
{
cout << "ThickPerson foot" << endl;
}
};
//指挥者类
class Direct
{
private:
Person* p;
public:
Direct(Person* temp)
{
p = temp;
}
void Create()
{
p->CreateHead();
p->CreateHand();
p->CreateBody();
p->CreateFoot();
}
};
//客户端代码
int main()
{
Person* p = new ThickPerson();
Direct* d = new Direct(p);
d->Create();
delete p;
delete d;
p = new ThinPerson();
d = new Direct(p);
d->Create();
delete p;
delete d;
return 0;
}