建造者模式

xiaoxiao2021-02-28  10

#include<iostream> using namespace std; #include "string" //房子 class House { public: void setDoor(string door) { m_door = door; } void setWindow(string window) { m_window = window; } void setWall(string wall) { m_wall = wall; } string getDoor() { cout << m_door << endl; return m_door; } string getWindow() { cout << m_window << endl; return m_window; } string getWall() { cout << m_wall << endl; return m_wall; } private: string m_door; string m_window; string m_wall; }; //抽象工程队 class Builder { public: virtual void buildDoor() = 0; virtual void buildWall() = 0; virtual void buildWindow() = 0; virtual House *getHouse() = 0; }; //公寓工程队 class FlatBuilder :public Builder { public: FlatBuilder() { m_house = new House; } virtual void buildDoor() { m_house->setDoor("flat door"); } virtual void buildWall() { m_house->setWall("flat wall"); } virtual void buildWindow() { m_house->setWindow("flat window"); } virtual House *getHouse() { return m_house; } private: House *m_house; }; //别墅工程队 class VillaBuilder :public Builder { public: VillaBuilder() { m_house = new House; } virtual void buildDoor() { m_house->setDoor("Villa door"); } virtual void buildWall() { m_house->setWall("Villa wall"); } virtual void buildWindow() { m_house->setWindow("Villa window"); } virtual House *getHouse() { return m_house; } private: House *m_house; }; //设计师 class Director { public: Director(Builder*builder) { m_builder = builder; } void Construct() { m_builder->buildDoor(); m_builder->buildWall(); m_builder->buildWindow(); } private: Builder* m_builder; }; void main() { Director *director = NULL; Builder *builder = NULL; House *house = NULL; builder = new FlatBuilder; director =new Director(builder); director->Construct(); house = builder->getHouse(); house->getDoor(); house->getWall(); delete house; delete builder; builder = new VillaBuilder; director = new Director(builder); director->Construct(); house = builder->getHouse(); house->getDoor(); house->getWall(); delete house; delete builder; }
转载请注明原文地址: https://www.6miu.com/read-2800068.html

最新回复(0)