设计模式-Builder模式(创建型模式)

//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码

//Product.h

#pragma once
class Product {
public:
    Product();
    ~Product();
    void ProducePart();
protected:
private:
};

class ProductPart {
public:
    ProductPart();
    ~ProductPart();
    ProductPart* buildPart();
protected:
private:

};

//Product.cpp

#include"Product.h"
#include<iostream>

Product::Product()
{
    ProducePart();
    std::cout << "return a Product." << std::endl;
}
Product::~Product()
{

}
void Product::ProducePart()
{
    std::cout << "Build part of product." << std::endl;
}

ProductPart::ProductPart(){}
ProductPart::~ProductPart(){}
ProductPart* ProductPart::buildPart()
{
    return new ProductPart;
}

//Build.h

#pragma once
#include<string>
class Product;
class Builder {
public:
    virtual ~Builder();
    virtual void BuildPartA(const std::string& buildPara) = 0;
    virtual void BuildPartB(const std::string& buildPara) = 0;
    virtual void BuildPartC(const std::string& buildPara) = 0;
    virtual Product* getProduct() = 0;
protected:
    Builder();
private:
};

class ConcreateBuilder :public Builder {
public:
    ConcreateBuilder();
    virtual ~ConcreateBuilder();
    void BuildPartA(const std::string& buildPara);
    void BuildPartB(const std::string& buildPara);
    void BuildPartC(const std::string& buildPara);
    Product* getProduct();
protected:
private:
};

//Build.cpp

#include"Build.h"
#include"Product.h"
#include<iostream>

Builder::Builder(){}
Builder::~Builder(){}
ConcreateBuilder::ConcreateBuilder(){}
ConcreateBuilder::~ConcreateBuilder(){}
void ConcreateBuilder::BuildPartA(const std::string& buildPara)
{
    std::cout << "Step1: Build Part1...." << buildPara << std::endl;
}
void ConcreateBuilder::BuildPartB(const std::string& buildPara)
{
    std::cout << "Step2: Build Part2..." << buildPara << std::endl;
}
void ConcreateBuilder::BuildPartC(const std::string& buildPara)
{
    std::cout << "Step3: Build Part3..." << buildPara << std::endl;
}
Product* ConcreateBuilder::getProduct()
{
    BuildPartA("Pre-Defined");
    BuildPartB("Pre-Defined");
    BuildPartC("Pre-Defined");
    return new Product();
}

//Director.h

#pragma once
class Builder;
class Director {
public:
    ~Director();
    Director(Builder* bld);
    void Construct();
protected:
private:
    Builder* _bld;
};

//Director.cpp

#include"Director.h"
#include"Build.h"

Director::~Director()
{

}
Director::Director(Builder* bld)
{
    _bld = bld;
}
void Director::Construct()
{
    _bld->BuildPartA("User-Defined");
    _bld->BuildPartB("User-Defined");
    _bld->BuildPartC("User-Defined");
}

//main.cpp

#include"Build.h"
#include"Director.h"
#include"Product.h"

int main(int args, char* argv)
{
    Director* dir = new Director(new ConcreateBuilder());
    dir->Construct();

    return 0;
}
posted @ 2019-12-20 21:30  fourmii  阅读(348)  评论(0编辑  收藏  举报