设计模式之——建造者模式

builder.h

#ifndef BUILDER_H
#define BUILDER_H
#include "computer.h"

class Builder
{
public:
    Builder() {}
    virtual void buildCpu() = 0;
    virtual void buildRam() = 0;
    virtual Computer *getResult() = 0;
};

#endif // BUILDER_H

builderA.h

#ifndef BUILDERA_H
#define BUILDERA_H
#include "builder.h"
#include "computer.h"

class BuilderA : public Builder
{
public:
    BuilderA() { m_computerA = new Computer(); }
    void buildCpu(){ m_computerA->setCpu("i5"); }
    void buildRam(){ m_computerA->setRam("DDR4"); }
    Computer *getResult(){ return m_computerA; }

private:
    Computer *m_computerA;

};

#endif // BUILDERA_H

computer.h

#ifndef COMPUTER_H
#define COMPUTER_H

#include 

class Computer
{
public:
    Computer() {}
    void setCpu(QString cpu){ m_cpu = cpu;}
    void setRam(QString ram){ m_ram = ram;}

    QString getCpu(){ return m_cpu; }
    QString getRam(){ return m_ram; }

private:
    QString m_cpu;
    QString m_ram;
};

#endif // COMPUTER_H

director.h

#ifndef DIRECTOR_H
#define DIRECTOR_H

#include "builder.h"

class Director
{
public:
    Director() {}
    void create(Builder *builder)
    {
        builder->buildCpu();
        builder->buildRam();
    }
};

#endif // DIRECTOR_H

main

#include 
#include 

#include "director.h"
#include "builder.h"
#include "builderA.h"

//建造者模式
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Director *director = new Director();
    Builder *builderA = new BuilderA();

    director->create(builderA);
    Computer *A = builderA->getResult();
    qDebug() << A->getCpu();
    qDebug() << A->getRam();

    return a.exec();
}

建造者模式的好处就是建造代码与表示代码分离
UML
设计模式之——建造者模式_第1张图片

你可能感兴趣的:(设计模式,建造者模式,设计模式,c++)