设计模式-建造者模式
建造者 模式
builderModle.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Phone {
public:
Phone() {}
~Phone() {}
void setBattery(string batteryName) { cout << batteryName << endl; this->m_batteryName = batteryName; }
void setScreen(string screenName) { cout << screenName << endl; this->m_screenName = screenName; }
void setCamera(string cameraName) { cout << cameraName << endl; this->m_cameraName = cameraName; }
void displayPhone() {
cout << "battery:" << this->m_batteryName;
cout << "screen:" << this->m_screenName;
cout << "camera:" << this->m_cameraName;
}
private:
string m_batteryName;
string m_screenName;
string m_cameraName;
};
class Builder {
public:
Builder() {}
~Builder() {}
//Builder(string EngerneerName){ }
virtual void produceBattery() = 0;
virtual void produceScreen() = 0;
virtual void produceCamera() = 0;
virtual Phone* getPhone() { return phone1; }
protected:
Phone *phone1 = NULL;
};
class xiaomiBuilder : public Builder
{
public:
xiaomiBuilder() { phone = new Phone; }
void produceBattery() { phone->setBattery("xiaomi Battery"); }
void produceScreen() { phone->setScreen("xiaomi Screen"); }
void produceCamera() { phone->setCamera("xiaomi Camera"); }
Phone* getPhone() { return phone; }
private:
Phone *phone;
};
class Director {
public:
Director() { }
Director(Builder *builder) :m_builder(builder) { }
void create(Builder *builder) {
Builder * test = builder;
test->produceBattery();
test->produceCamera();
test->produceScreen();
}
void create() {
this->m_builder->produceBattery();
this->m_builder->produceCamera();
this->m_builder->produceScreen();
}
/*Director(const Director& director){
builder = director.builder;
}*/
private:
Builder *m_builder = NULL;
};
主函数
main.cpp
#pragma once
#include <iostream>
#include "builderModle.h"
using namespace std;
//设计模式
int main() {
//建造者模式
Builder *xiaomiEngerneer = new xiaomiBuilder();
Director *director = new Director(xiaomiEngerneer);
//director->getbuilder(xiaomiEngerneer);
director->create(xiaomiEngerneer);
Phone *m_phone = xiaomiEngerneer->getPhone();
m_phone->displayPhone();
cout << "hello" << endl;
return 0;
}
输出
xiaomi Battery
xiaomi Camera
xiaomi Screen
battery:xiaomi Batteryscreen:xiaomi Screencamera:xiaomi Camerahello
注意
1.注意类的相互包含
2.注意类声明和展开的顺序