建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
例如建造一个车, 宝马先建造车身, 发动机, 车窗, 车轮, 奔驰先造发动机, 车身,车轮, 车窗等等。对于客户来说, 知道造车工厂就可以了, 具体怎么造, 那是汽车工厂的事情。
使用场景
当创建复杂对象的算法独立于他的组成部分
当构造的过程必须允许被构造对象有不同的表示时候
-
#include<iostream>
-
using namespace std;
-
-
class Builder {
-
public:
-
virtual ~Builder() {};
-
virtual void BuildEngine() =0;
-
virtual void BuildWindow() =0;
-
virtual void BuildWheel() =0;
-
virtual void BuildChassis() =0;
-
-
};
-
class Ben : public Builder {
-
public:
-
void BuildEngine() { cout << "Ben BuildEngine \n"; }
-
void BuildWindow() { cout << "Ben BuildWindow\n"; }
-
void BuildWheel() { cout << "Ben BuildWheel \n"; }
-
void BuildChassis() { cout << "Ben BuildChassis"; }
-
};
-
class BMW : public Builder {
-
public:
-
void BuildEngine() { cout << "BMW BuildEngine \n"; }
-
void BuildWindow() { cout << "BMW BuildWindow\n"; }
-
void BuildWheel() { cout << "BMW BuildWheel \n"; }
-
void BuildChassis() { cout << "BMW BuildChassis\n"; }
-
};
-
-
class Direct {
-
public:
-
Direct(Builder *pB) { pb = pB; }
-
void Create() {
-
pb->BuildEngine();
-
pb->BuildWindow();
-
pb->BuildChassis();
-
pb->BuildWheel();
-
}
-
private:
-
Builder *pb;
-
};
-
-
int main(int argc, char* agrv[]) {
-
Builder *pC = new BMW();
-
Direct *pD = new Direct(pC);
-
pD->Create();
-
-
delete pD;
-
delete pC;
-
return 0;
-
}
备注:
手绘UML图
Makefile文件
-
# set CPUS for Linux or FreeBSD
-
CPUS := $(shell cat /proc/cpuinfo|grep -c processor)
-
-
-
GCC472_PATH=/usr/local/gcc-4.7.2
-
CXX := env LD_LIBRARY_PATH=$(GCC472_PATH)/lib:/usr/local/mpc/lib $(GCC472_PATH)/bin/g++
-
CXXFLAGS := -g3 -O2 -fno-strict-aliasing -Wall -Werror -fPIC \
-
-isystem /usr/local/include \
-
-isystem /usr/include
-
-
LDFLAGS := -pthread \
-
-L/usr/local/lib64/ \
-
-L/usr/local/lib/
-
RTFLAGS := \
-
-Wl,-rpath=.. \
-
-Wl,-rpath=/$(GCC472_PATH)/lib64
-
-
LIBS := -lpthread
-
-
SRC := $(wildcard *.cc)
-
OBJ := $(patsubst %.cc, %.o, $(SRC))
-
DEP := $(patsubst %.o, %.d, $(OBJ))
-
-
TARGET := main_test
-
-
all:
-
$(MAKE) -j$(CPUS) target
-
-
main_test: $(OBJ)
-
$(CXX) $^ -o $@ $(RTFLAGS) $(LDFLAGS) $(LIBS)
-
-
-
target: $(TARGET)
-
-
%.o : %.cc
-
$(CXX) -c $(CXXFLAGS) $< -o $@
-
-
%.d : %.cc
-
@$(CXX) -MM $< $(CXXFLAGS) | sed 's/$(notdir $*)\.o/$(subst /,\/,$*).o $(subst /,\/,$*).d/g' > $@
-
-
clean:
-
-rm -rf $(OBJ) $(TARGET) *.core $(DEP) *_unittest
-
-
test: all
-
./main_test
-
-
.PHONY: all target clean test
阅读(878) | 评论(0) | 转发(0) |