• 设计模式之Factory模式(C++)


    Factory模式具有两大重要的功能:

    (1)、定义创建对象的接口,封装了对象的创建;

    (2)、使具体化类工作延迟到了子类中。

    //Product.h
    #ifndef _PRODUCT_H_
    #define _PRODUCT_H_
    
    class Product
    {
    public:
          virtual ~Product();
    protected:
           Product();
    private:
       
    };
    
    class ConcreteProduct:public Product
    {
    public:
        ConcreteProduct();
        ~ConcreteProduct();
    protected:
    
    private:
    };
    #endif //_PRODUCT_H_
    //Product.cpp
    #include "Product.h"
    #include <iostream>
    using namespace std;
    
    Product::Product()
    {}
    Product::~Product()
    {}
    ConcreteProduct::ConcreteProduct()
    {}
    ConcreteProduct::~ConcreteProduct()
    {}
    //Factory.h
    #ifndef _FACTORY_H_
    #define _FACTORY_H_
    
    class Product;
    class Factory
    {
    public:
        virtual ~Factory();
        virtual Product *CreateProduct() = 0; 
    protected:
        void Factory();
    private:
    };
    
    class ConcreteFactory:public Factory
    {
    public:
        ConcreteFactory();
        ~ConcreteFactory();
        Product * CreateProduct();
    protected:
    private:    
    };
    #endif //_FACTORY_H_
    //Fatory.cpp
    
    #include "Factory.h"
    #include "Product.h"
    
    #include <iostream>
    using namespace std;
    
    Factory::Factory()
    {}
    Factory::~Factory()
    {}
    
    ConcreteFactory::ConcreteFactory()
    {}
    ConcreteFactory::ConcreteFactory()
    {}
    
    Product ConcreteFactory::CreateProduct()
    {
        ConcreteProduct cproduct = new ConcreteProduct;
        return product;
    }
    //main.cpp
    
    #include "Factory.h"
    #include "Product.h"
    
    #include <iostream>
    using namespace std;
    
    int main(int argc,char *argv[])
    {
        Factory *fac = new ConcreteFactory;
        Product *p = fac->CreateProduct();
    
        return 0;
    }

  • 相关阅读:
    Shell 基础
    史上最全储能系统优缺点梳理
    IEEE文章分类
    【能源常识】如何理解“电力电量平衡”
    最优化基础(五)
    最优化基础(四)
    json
    python基础知识之zip
    Python sendmail
    指定的结尾换行
  • 原文地址:https://www.cnblogs.com/tslDream/p/4456397.html
Copyright © 2020-2023  润新知