2021.10.2 建造者模式

一、今日学习内容

    

1、类图

 

2、代码

#include<iostream>
using namespace std;
#include<string>

class Computer 
{
private:
    string host;      //主机
    string internal;  //内存
    string harddisk;  //硬盘
public:
    void setHost(string host) 
    {
        this->host = host;
    }
    void setInternal(string internal)
    {
        this->internal = internal;
    }
    void setHarddisk(string harddisk)
    {
        this->harddisk = harddisk;
    }
    string getHost()
    {
        return host;
    }
    string getInternal()
    {
        return internal;
    }
    string getHarddisk()
    {
        return harddisk;
    }
};

class ComputerBuilder
{
public:
    virtual void buildHost()=0;
    virtual void buildInternal()=0;
    virtual void buildHarddisk()=0;
    Computer getComputer()
    {
        return computer;
    }
protected:
    Computer computer;
};

class Desktop : public ComputerBuilder
{
public:

    void buildHost()
    {
        computer.setHost("台式机主机");
    }

    void buildInternal()
    {
        computer.setInternal("台式机内存");
    }

    void buildHarddisk()
    {
        computer.setHarddisk("台式机硬盘");
    }

};

class Laptop : public ComputerBuilder
{
public:

    void buildHost()
    {
        computer.setHost("笔记本主机");
    }

    void buildInternal()
    {
        computer.setInternal("笔记本内存");
    }

    void buildHarddisk()
    {
        computer.setHarddisk("笔记本硬盘");
    }

};

class Worker
{
private:
    ComputerBuilder *cb;
public:
    void setComputerBuilder(ComputerBuilder *cb)
    {
        this->cb = cb;
    }
    Computer construct()
    {
        cb->buildHost();
        cb->buildInternal();
        cb->buildHarddisk();
        return cb->getComputer();
    }
};

int main()
{
    string t;
    cout << "请输入电脑类型:";
    cin >> t;
    Worker *worker = new Worker();
    if (!t.compare("Desktop")) {
        ComputerBuilder * cb = new Desktop();
        worker->setComputerBuilder(cb);

    }
    else
    {
        ComputerBuilder * cb = new Laptop();
        worker->setComputerBuilder(cb);
    }
    Computer  computer = worker->construct();
    cout << "部件组成:" << endl;
    cout << computer.getHost() << endl;
    cout << computer.getInternal() << endl;
    cout << computer.getHarddisk() << endl;
}

 

 

3、运行截图

 
 
 
 
posted @ 2021-10-02 18:32  小仙女W  阅读(85)  评论(0编辑  收藏  举报