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驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    android listview去掉分割线
    svn 上传 过滤
    PPPOE 模拟环境搭建
    Android笔记之网络-基本了解
    ios多线程操作(五)—— GCD串行队列与并发队列
    UVa 679
    android中更改spinner、AutoCompleteTextView切割线的颜色
    Cocos2d-x中触摸事件
    全然符合package.json在CommonJS中的规范
    Hibernate实体对象继承策略
  • 原文地址:https://www.cnblogs.com/itdef/p/7456809.html
Copyright © 2011-2022 走看看