1. 程式人生 > >建造者模式(Builder) C++實現

建造者模式(Builder) C++實現

#include <iostream>
#include <string>

using namespace std;

class Product {
private :
    int id; // 假設為複雜物件
    string name; // 假設為複雜物件
public :
    Product() {
        id = 0;
        name = "";
    }
    void setId(int id) {
        this->id = id;
    }
    void setName(string name) {
        this->name = name;
    }
    int getId() {
        return this->id;
    }
    string getName() {
        return this->name;
    }
};

class Builder {
public :
    virtual void buildId() = 0;
    virtual void buildName() = 0;
    virtual Product * getResult() = 0;
};

class ConcreteBuilder : public Builder {
private :
    Product * product;
public :
    ConcreteBuilder() {
        product = new Product();
    }
    void buildId() {
        product->setId(1);
    }
    void buildName() {
        product->setName("Lucy");
    }
    Product * getResult() {
        return product;
    }
};

class Directer {
private :
    Builder * builder;
public :
    Directer(Builder * builder) {
        this->builder = builder;
    }
    Product * construct() {
        builder->buildId();
        builder->buildName();
        return builder->getResult(); 
    }
};

int main() {
    Builder * builder = new ConcreteBuilder();
    Directer * directer = new Directer(builder);
    Product * product = directer->construct();
    cout << "id : " << product->getId() << ", name : " << product->getName() << endl;
    
    delete product;
    delete directer;
    delete builder;

    return 0;
}