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驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    JVM总结-java基本类型
    JVM总结-虚拟机怎么执行字节码
    spring-BeanDefinition流程源码分析
    spring-BeanFactory源码解析
    linux文件基本权限-基本权限的修改
    Spring-IoC容器初始化流程源码分析
    spring-AOP
    JavaScript笔记 第十六章 匿名函数和闭包
    C# 指针(unsafe与fixed的使用)
    devenv.exe
  • 原文地址:https://www.cnblogs.com/itdef/p/7456809.html
Copyright © 2011-2022 走看看