zoukankan      html  css  js  c++  java
  • builder模式

     1 #include <iostream>
     2 using namespace std;
     3 
     4 
     5 struct person{
     6     int head;
     7     int body;
     8 };
     9 class Builder
    10 {
    11 public:
    12     virtual void BuildHead() {}
    13     virtual void BuildBody() {}
    14     virtual person* get()=0;
    15     virtual ~Builder(){}
    16 };
    17 //构造瘦人
    18 class ThinBuilder : public Builder
    19 {
    20 public:
    21     person * my;
    22     ThinBuilder(){my=new person;}
    23     virtual void BuildHead() { cout<<"build thin body"<<endl;my->body=3; }
    24     virtual void BuildBody() { cout<<"build thin head"<<endl;my->head=5; }
    25     virtual person* get(){return my;}
    26 };
    27 
    28 
    29 //构造胖人
    30 class fatBuilder : public Builder
    31 {
    32 public:
    33     person * my;
    34     fatBuilder(){my=new person;}
    35     virtual void BuildHead() { cout<<"build thin body"<<endl;my->body=30; }
    36     virtual void BuildBody() { cout<<"build thin head"<<endl;my->head=50; }
    37     virtual person* get(){return my;}
    38 };
    39 
    40 
    41 //构造的指挥官
    42 class Director
    43 {
    44 private:
    45     Builder *m_pBuilder;
    46 public:
    47     Director(Builder *builder) { m_pBuilder = builder; }
    48     //两种create方法都可以,本质上是一样的
    49     void Create(){
    50         m_pBuilder->BuildHead();
    51         m_pBuilder->BuildBody();
    52     }
    53 
    54     person* create2(){
    55         m_pBuilder->BuildHead();
    56         m_pBuilder->BuildBody();
    57         return m_pBuilder->get();
    58     }
    59 };
    60 int main()
    61 {
    62     ThinBuilder thin;
    63     Director director(&thin);
    64     director.Create();
    65     person* tmp = thin.get();
    66     cout << tmp->body << "\t" << tmp->head << endl;
    67     delete tmp;
    68 
    69     fatBuilder thin2;
    70     Director director2(&thin2);
    71     tmp = director2.create2();
    72     cout << tmp->body << "\t" << tmp->head << endl;
    73     delete tmp;
    74     return 0;
    75 }
  • 相关阅读:
    项目常见异常
    mysql 存储过程中使用事物+事件定时执行存储过程
    Spring Mvc 配置 之 ContextLoaderListener
    Spring Boot 之 https
    Spring Boot 之 annotation注解
    用python打印99乘法口诀表
    gerrit代码审核工具之“error unpack failed error Missing unknown”错误解决思路
    在eclipse搭建python开发环境
    python2与python3语法区别之_重定向
    2_jenkins_git创建创建及项目构建
  • 原文地址:https://www.cnblogs.com/kakamilan/p/2593412.html
Copyright © 2011-2022 走看看