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");
    }
  • 相关阅读:
    ant build打包
    在JAVA中如何获取当前源文件名以及代码的行号
    react以组件为中心的代码分割和懒加载
    java中针对 try和finally一些总结
    JS强制关闭浏览器页签并且不提示关闭信息
    由[].slice.call()引发的思考
    JS类型判断
    nginx的location配置
    DBCP连接池
    java/Servlet
  • 原文地址:https://www.cnblogs.com/caiminfeng/p/5311934.html
Copyright © 2011-2022 走看看