zoukankan      html  css  js  c++  java
  • 设计模式 工厂模式 使用shared_ptr

    参考http://blog.csdn.net/calmreason/article/details/50903729

    所有产品继承同一基本类

    由工厂保存基类指针 产生各类产品

    代码

    // 002.cpp: 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <memory>
    #include <iostream> 
    
    using namespace std;
    
    class Base
    {
    public:
        virtual void f(void) = 0;
        virtual void g(void) = 0;
    protected:
        Base() { std::cout << "Base()" << std::endl; }
        virtual ~Base() { std::cout << "~Base()" << std::endl; }
    };
    
    class A :public Base
    {
    public:
        A(void) { std::cout << "A()" << std::endl; }
        ~A() { std::cout << "~A()" << std::endl; }
        void f(void) { std::cout << "A::f()" << std::endl; }
        void g(void) { std::cout << "A::g()" << std::endl; }
    };
    
    class B :public Base {
    public:
        B(void) { std::cout << "B()" << std::endl; }
        ~B(void) { std::cout << "~B()" << std::endl; }
        void f() { std::cout << "B::f()" << std::endl; }
        void g() { std::cout << "B::g()" << std::endl; }
    };
    
    class Factory {
    public:
        static std::shared_ptr<Base> CreateA(void) {
            return std::make_shared<A>();
        }
        static std::shared_ptr<Base> CreateB(void) {
            return std::make_shared<B>();
        }
    };
    
    
    int main()
    {
        std::shared_ptr<Base> pbase = Factory::CreateA();
        pbase->f();
        pbase->g();
    
        pbase = Factory::CreateB();
        pbase->f();
        pbase->g();
    
        return 0;
    }
    View Code
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    Git 远程操作详解
    Golang io标准库
    Golang strings标准库
    Go WebSocket 实现
    Golang Gorm零值数据更新小坑
    [Linux] 分区扩容
    即截即贴,推荐一个提升截图对比效率的工具Snipaste
    POI 替换 word 关键字并保留样式
    前端图片压缩与 zip 压缩
    ubuntu20更换内核
  • 原文地址:https://www.cnblogs.com/itdef/p/7456809.html
Copyright © 2011-2022 走看看