zoukankan      html  css  js  c++  java
  • c++设计模式——工厂模式

    简单工厂模式,一个工厂,多个产品;增加一种产品,就要修改工厂类中的代码,违反了对扩展开放,对修改关闭原则,会使得代码边的臃肿

    #include <iostream>
    using namespace std;
    
    class Product
    {
    public:
        virtual void show()=0;
    };
    class PA:public Product
    {
    public:
        void show()
        {
            cout<<"this is a"<<endl;
            return ;
        }
    };
    class PB:public Product
    {
    public:
        void show()
        {
            cout<<"this is b"<<endl;
            return ;
        }
    };
    class Factroy
    {
    public:
        Product* create(int i)
        {
            switch (i)
            {
            case 1:
                return new PA();
                break;
            case 2:
                return new PB();
                break;
            default:
                return nullptr;
            }
            return nullptr;
        }
    };
    int main()
    {
        
        Factroy f;
        f.create(1)->show();
        f.create(2)->show();
    
        return 0;
    }

    定义一个创建对象的接口, 让其子类自己决定实例化哪一个工厂类,多个工厂多个产品,当增加一个新产品时,同时增加一个新工厂。增加新工厂属于扩展,不会修改以前工厂类和产品类的任何代码。

    #include <iostream>
    using namespace std;
    
    class Product
    {
    public:
        virtual void show()=0;
    };
    class PA:public Product
    {
    public:
        void show()
        {
            cout<<"this is a"<<endl;
            return ;
        }
    };
    class PB:public Product
    {
    public:
        void show()
        {
            cout<<"this is b"<<endl;
            return ;
        }
    };
    
    class Factroy
    {
    public:
        virtual Product* create()=0;
    };
    class FA:public Factroy
    {
    public:
        Product* create()
        {
            return new PA();
        }
    };
    class FB:public Factroy
    {
    public:
        Product* create()
        {
            return new PB();
        }
    };
    int main()
    {
        FA fa;
        fa.create()->show();
        FB fb;
        fb.create()->show();
        return 0;
    }
  • 相关阅读:
    shell 中的expect 用法
    Python下安装protobuf
    google protobuf 中的proto文件编写规则
    ubuntu 16.04 安装grpc
    python 常见的错误类型 和 继承关系
    倒排索引
    python 调用c函数
    python中的re模块,常用函数介绍
    leecode第二十二题(括号生成)
    leecode第十九题(删除链表的倒数第N个节点)
  • 原文地址:https://www.cnblogs.com/tianzeng/p/12458828.html
Copyright © 2011-2022 走看看