C++ 建造者模式


#include 
#include 
#include 
// 创建型设计模式, 创建主机(cpu、内存条、显卡、硬盘)

class Product {
 public:
  virtual ~Product() = default;
  virtual void setCpu(const std::string& cpu) = 0;
  virtual void setMemory(const std::string& mem) = 0;
  virtual void setGraphicsHard(const std::string& grph) = 0;
  virtual void setHardDisk(const std::string& hrd) = 0;
  virtual void show() = 0;
};

class ComputerHost final : public Product {
 public:
  ComputerHost() = default;

  void setCpu(const std::string& cpu) { cpu_ = cpu; }
  void setMemory(const std::string& mem) { memory_ = mem; }
  void setGraphicsHard(const std::string& grph) { graphicsHard_ = grph; }
  void setHardDisk(const std::string& hrd) { hardDisk_ = hrd; }
  void show() {
    std::cout << cpu_ << "," << memory_ << "," << graphicsHard_ << ","
              << hardDisk_ << std::endl;
  }

 private:
  std::string cpu_;
  std::string memory_;
  std::string graphicsHard_;
  std::string hardDisk_;
};

class AbstractBuilder {
 public:
  virtual ~AbstractBuilder() = default;

  virtual void buildCpu(const std::string& cpu) = 0;
  virtual void buildMemory(const std::string& mem) = 0;
  virtual void buildGraphicsHard(const std::string& grph) = 0;
  virtual void buildHardDisk(const std::string& hrd) = 0;

  virtual auto getProduct() -> Product* = 0;
};

class ConcretComputerHostBuilder final : public AbstractBuilder {
 public:
  ConcretComputerHostBuilder(Product* pro) : pro_(pro) {}
  virtual void buildCpu(const std::string& cpu) { pro_->setCpu(cpu); }
  virtual void buildMemory(const std::string& mem) { pro_->setMemory(mem); }
  virtual void buildGraphicsHard(const std::string& grph) {
    pro_->setGraphicsHard(grph);
  }
  virtual void buildHardDisk(const std::string& hrd) { pro_->setHardDisk(hrd); }

  auto getProduct() -> Product* { return pro_.get(); }

 private:
  std::unique_ptr<Product> pro_;
};

class Director {
 public:
  Director(AbstractBuilder* builder) : builder_(builder) {}

  void create(const std::string& cpu, const std::string& mem,
              const std::string& grph, const std::string& hrd) {
    builder_->buildCpu(cpu);
    builder_->buildMemory(mem);
    builder_->buildGraphicsHard(grph);
    builder_->buildHardDisk(hrd);
  }

  void output() { builder_->getProduct()->show(); }

 private:
  std::unique_ptr<AbstractBuilder> builder_;
};

void Test() {
  Product* pro = new ComputerHost();
  AbstractBuilder* builder = new ConcretComputerHostBuilder(pro);

  Director* dir = new Director(builder);
  dir->create("intel", "三星", "华硕", "东芝");
  dir->output();
}
int main() {
  Test();
  return 0;
}

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