设计模式的 C++ 实现---单例模式(二)

前文回顾
单例模式(一)

前言

上篇文章记录了 C++ 中限制一个类只生成一个实例的方法,本文在此基础上进行扩展:限制某个类最多只能有 n 个实例对象。

限制类对象个数

  1. 实现说明
    ①.对象创建会调用构造函数,对象销毁会调用析构函数,因此可以在构造和析构函数中进行数量的记录。
    ②.使用静态成员变量记录类的实例数量。
    ③.构造函数定义为 private,然后提供另外的构造函数用于创建对象。
  2. 代码示例

class Anyleton
{
public:
    class TooManyObj{};//异常
    ~Anyleton()
    {
        --curObjCount;
    }
    static const int maxObjCount = 10;//最大实例个数
    static int curObjCount ;
    static Anyleton * getAnyleton()
{
        return  new Anyleton();
    }
    static Anyleton *getAnyleton( const Anyleton & obj)
{
        return  new Anyleton(obj);
    }
private:
    Anyleton()
    {
        if( curObjCount >= maxObjCount )
            throw TooManyObj();
         ++curObjCount;
    }
    Anyleton(const Anyleton &)
    {
        if( curObjCount >= maxObjCount )
            throw TooManyObj();
         ++curObjCount;
    }
};

模版基类

当有多个类需要控制实例数量时,可以采用模版及继承的方式实现代码复用。

  1. 模版基类

template <typename T>
class AnyletonTemple
{
public:
    class TooMantObj{};
    static int getCurObjCount(){ return curObjCount ;}
protected:
     AnyletonTemple()
     {
         init();
     }
     AnyletonTemple(const AnyletonTemple &)
     {
         init();
     }
     ~AnyletonTemple()
     {
         --curObjCount;
     }
private:
     static const int maxObjCount ;
     static int curObjCount;
     void init()
{
         if( curObjCount >= maxObjCount )
             throw TooMantObj();
         ++curObjCount;
     }
};
  1. 派生类示例
class AnyletonExample:private AnyletonTemple<AnyletonExample>
{
public:
    static  AnyletonExample * getAnyletonObj(){ return new AnyletonExample() ;}
    static AnyletonExample * getAnyletonObj(const AnyletonExample & obj){ return new AnyletonExample(obj) ;}
    ~AnyletonExample(){};
    using AnyletonTemple<AnyletonExample>::TooMantObj;
    using AnyletonTemple<AnyletonExample>::getCurObjCount;
private:
    AnyletonExample(){};
    AnyletonExample(const AnyletonExample &){}
};

template<typename AnyletonExample>
int AnyletonTemple<AnyletonExample>::curObjCount = 0;

template<typename AnyletonExample>
const int AnyletonTemple<AnyletonExample>::maxObjCount  = 3;

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值