zoukankan      html  css  js  c++  java
  • C++简单工厂模式

    简单工厂模式可以说是大多数人接触到的第一个设计模式。资源请求者(客户)直接调用工厂类中的函数,工厂根据传入的参数返回不同的类给资源请求者。下面给出在C++中使用简单工厂模式的一个demo,采用了auto_ptr智能指针管理类资源。

    值得注意的是抽象类Product中的析构函数必须为虚函数。《Effective C++》条款07:为多态基类声明virtual析构函数。

    采用auto_ptr也符合《Effective C++》条款13:以对象管理资源、条款18:让接口容易被正确使用,不易被误用。

    #include <iostream>
    using namespace std;
    
    enum ProductType{ TypeA, TypeB, TypeC };
    
    class Product{
    public:
        virtual void show() = 0;
        virtual ~Product(){};//virtual destructor
    };
    
    class ProductA :public Product{
    public:
        void show(){
            cout << "A" << endl;
        }
        ProductA(){
            cout << "constructing A" << endl;
        }
        ~ProductA(){
            cout << "destructing A" << endl;
        }
    };
    
    class ProductB :public Product{
    public:
        void show(){
            cout << "B" << endl;
        }
        ProductB(){
            cout << "constructing B" << endl;
        }
        ~ProductB(){
            cout << "destructing B" << endl;
        }
    };
    
    class ProductC :public Product{
    public:
        void show(){
            cout << "C" << endl;
        }
        ProductC(){
            cout << "constructing C" << endl;
        }
        ~ProductC(){
            cout << "destructing C" << endl;
        }
    };
    
    class ProductFactory{
    public:
        static auto_ptr<Product> createProduct(ProductType type){
            switch (type){
            case TypeA: return auto_ptr<Product>(new ProductA());
            case TypeB: return auto_ptr<Product>(new ProductB());
            case TypeC: return auto_ptr<Product>(new ProductC());
            default: return auto_ptr<Product>(NULL);
            }
        }
    };
    
    
    int main()
    {
        {
            auto_ptr<Product> proA = ProductFactory::createProduct(TypeA);
            auto_ptr<Product> proB = ProductFactory::createProduct(TypeB);
            auto_ptr<Product> proC = ProductFactory::createProduct(TypeC);
            proA->show();
            proB->show();
            proC->show();
        }
        system("pause");
    }
  • 相关阅读:
    思念
    空白
    curl json string with variable All In One
    virtual scroll list All In One
    corejs & RegExp error All In One
    socket.io All In One
    vue camelCase vs PascalCase vs kebabcase All In One
    element ui 表单校验,非必填字段校验 All In One
    github 定时任务 UTC 时间不准确 bug All In One
    input range & color picker All In One
  • 原文地址:https://www.cnblogs.com/caiminfeng/p/5311934.html
Copyright © 2011-2022 走看看