C++ 设计模式——创建型模式


源码点击(https://github.com/bob-young/CPPDesignPattern ) .

Singleton
特点:确保一个类只有一个实例,自行实例化,并向整个系统提供该实例
应用:线程池,文件IO等处,应对单一对象频繁的创建和销毁,方便资源之间的互相通信。
    #include <iostream>
    class Singleton {
    private:
        Singleton(){
            std::cout<<"Create Singleton\n";
        }
        static Singleton* s;
    public:
        static Singleton* getInstance(){
            return s;
        }
    };
    Singleton* Singleton::s=new Singleton();//global init


Factory
特点:使用工厂来控制子类的实例化
应用:我们明确地计划不同条件下创建不同实例时

    #include<iostream>
    class Product{
    public:
        virtual void getType(){std::cout<<"base type\n";};
    };
    class ProductA:public Product {
    public:
        void getType();
    };
    class ProductB:public Product {
    public:
        void getType();
    };
    class ProductC:public Product {
    public:
        void getType();
    };
    class Factory {
    public:
        Product* getProduct(char t);
    };
    Product* Factory::getProduct(char t){
        std::cout<<"producing "<<t<<std::endl;
        switch (t){
            case 'A':
                return new ProductA();
            case 'B':
                return new ProductB();
            case 'C':
                return new ProductC();
            default:
                return nullptr;
        }
    }
    void ProductA::getType() {
        std::cout<<"my type is A\n";
    }
    void ProductB::getType() {
        std::cout<<"my type is B\n";
    }
    void ProductC::getType() {
        std::cout<<"my type is C\n";
    }


Abstract Factory

特点:围绕一个超级工厂创建其他工厂,接口隔离,每个工厂都是负责一个接口的类的实例化
应用:不同功能需要单独对对象进行创建和控制
例子:apple公司和Samsung生产产品情景

      #include <iostream>
      //product
      class laptop{
      public:
          virtual void info()=0;
          laptop();
          virtual ~laptop();
      };
      class smartphone{
      public:
          virtual void info()=0;
          smartphone();
          virtual ~smartphone();
      };
      class samsungLaptop:public laptop{
      public:
          void info(){
              std::cout<<"laptop made by samsung\n";
          }
      };
      class samsungSmartphone:public smartphone{
      public:
          void info(){
              std::cout<<"smartphone made by samsung\n";
          }
      };
      class appleLaptop:public laptop{
      public:
          void info(){
              std::cout<<"laptop made by apple\n";
          }
      };
      class appleSmartphone:public smartphone{
      public:
          void info(){
              std::cout<<"smartphone made by apple\n";
          }
      };
      //factory
      class AbstractFactory {
      public:
          virtual smartphone* makePhone()=0;
          virtual laptop* makeLaptop()=0;
          virtual ~AbstractFactory();
      };
      class samsungFactory:public AbstractFactory{
      public:
          smartphone* makePhone(){
              return new samsungSmartphone();
          }
          laptop* makeLaptop(){
              return new samsungLaptop();
          }
      };
      class appleFactory:public AbstractFactory{
      public:
          smartphone* makePhone(){
              return new appleSmartphone();
          }
          laptop* makeLaptop(){
              return new appleLaptop();
          }
      };
      aptop::laptop() {
      }
      laptop::~laptop() {
      }
      smartphone::smartphone() {
      }
      smartphone::~smartphone() {
      }
      AbstractFactory::~AbstractFactory() {
      }


Builder

特点:使用多个简单的对象一步一步构建成一个复杂的对象,开闭原则,里氏代换,将变与不变分离开。
应用:一些基本部件不会变,而其组合经常变化的时候。

例子:快餐店套餐供应

      #include <iostream>
      #include <string>
      #include <vector>
      class Pack{
      public:
          virtual std::string getContainer()=0;
      };
      class Wrapper : public Pack{
      public:
          std::string getContainer(){
              return "wrapper";
          }
      };
      class Bottle : public Pack{
      public:
          std::string getContainer(){
              return "bottle";
          }
      };
      class Item{
      public:
          virtual std::string getName()=0 ;
          virtual float getPrice()=0 ;
          virtual Pack* getPackage()=0;
      };
      class Burger:public Item{
      public:
          Pack* getPackage(){
              return new Wrapper();
          }
      };
      class Drink:public Item{
      public:
          Pack* getPackage(){
              return new Bottle();
          }
      };
      class VegBurger :public Burger{
      public:
          std::string getName(){
              return "vegburger";
          }
          float getPrice(){
              return 10.0;
          }
      };
      class ChickenBurger:public Burger{
      public:
          std::string getName(){
              return "chicken burger";
          }
          float getPrice(){
              return 15.0;
          }
      };
      class Coca:public Drink{
      public:
          std::string getName(){
              return "cocacola";
          }
          float getPrice(){
              return 3.0;
          }
      };
      class Spirit:public Drink{
      public:
          std::string getName(){
              return "spirit";
          }
          float getPrice(){
              return 2.5;
          }
      };
      class Meal{
          std::vector<Item*> food;
      public:
          void addItem(Item* i){
              food.push_back(i);
          }
          float getTotalPrice(){
              float totalPrice=0.0;
              for(int i=0;i<food.size();i++){
                  totalPrice+=food[i]->getPrice();
              }
              return totalPrice;
          }
          void showItems(){
              for(int i=0;i<food.size();i++){
                  std::cout<<"\titem:"<<food[i]->getName();
                  std::cout<<"\tpackage:"<<food[i]->getPackage()->getContainer();
                  std::cout<<"\tprice:"<<food[i]->getPrice()<<std::endl;
              }
          }
          ~Meal(){
              for(long i=food.size()-1;i!=0;i--){
                  delete food[i];
              }
          }
      };
      class Builder {
      public:
          virtual Meal* getMeal()=0;
      };
      class VegBuilder:public Builder{
      public:
          Meal* getMeal(){
              Meal* m=new Meal();
              Item* burger=new VegBurger();
              m->addItem(burger);
              Item* drink=new Coca();
              m->addItem(drink);
              return m;
          }
      };
      class MeatBuilder:public Builder{
      public:
          Meal* getMeal(){
              Meal* m=new Meal();
              Item* burger=new ChickenBurger;
              m->addItem(burger);
              Item* drink=new Spirit();
              m->addItem(drink);
              return m;
          }
      };


Prototype

特点:这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆
应用:用原型实例指定创建对象的种类,实现快速的deepcopy。<br>
当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

      #include <cstdlib>
      class Prototype {
      public:
          int *ip=(int*)malloc(sizeof(int));
          int counter=100;
          virtual Prototype* clone()=0;
      };
      class cloneablePrototype:public Prototype{
      public:
          cloneablePrototype();
          Prototype* clone();
      private:
          cloneablePrototype(const cloneablePrototype&);//copy
          cloneablePrototype& operator=(cloneablePrototype const& cloneablePrototype1 );//ban on =operator
      };
      cloneablePrototype::cloneablePrototype() {
      }
      Prototype *cloneablePrototype::clone() {
          return new cloneablePrototype(*this);
      }
      cloneablePrototype:: cloneablePrototype(const cloneablePrototype& c){
          //pass your stack value and heap value here
          counter=c.counter;
          *(ip)=*(c.ip);
      }//copy


<br>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值