1类图

设计模式之构造模式_.net

 

2c++实现


/*
* builder.cpp
*
* Created on: 2017年2月7日
* Author: admin
*/

#include <string>
#include <iostream>

using namespace std;

class Car{
public:
const string& getBody() const {
return body;
}

void setBody(const string& body) {
this->body = body;
}

const string& getHead() const {
return head;
}

void setHead(const string& head) {
this->head = head;
}

const string& getTail() const {
return tail;
}

void setTail(const string& tail) {
this->tail = tail;
}

private:
string head;
string body;
string tail;
};

class Builder{
public:
virtual void buildHead()=0;
virtual void buildBody()=0;
virtual void buildTail()=0;
virtual Car * getResult()=0;
virtual ~Builder(){}
};



class CarBuilder:public Builder{
public:
CarBuilder(Car *car){
this->car=car;
}
public:
virtual void buildHead(){
car->setHead("bm head");
}
virtual void buildBody(){
car->setBody("bm body");
}
virtual void buildTail(){
car->setTail("bm tail");
}
virtual Car * getResult(){
return car;
}
private:
Car * car;
};

class Director{
public:
Director(Builder * builder){
this->builder=builder;
}
public:
void build(){
builder->buildHead();
builder->buildBody();
builder->buildTail();
}
private:
Builder * builder;
};

int main(){
Car * car=new Car;
Builder * builder=new CarBuilder(car);
Director *director=new Director(builder);
director->build();
car=builder->getResult();
cout<<car->getHead()<<endl;
cout<<car->getBody()<<endl;
cout<<car->getTail()<<endl;
return 0;
}