设计模式二三事——单例模式

一、单例模式

单例模式模式能够保证一个类的对象实例只有一个,具体的做法是将类的构造函数设置为私有或者受保护,然后再提供一个静态接口,通过该接口可以创建或者获取该类的唯一实例对象,具体的代码如下表示:

class Singleton
{
private:
    Singleton(){};

public:
    static Singleton* GetInstance()
    {
        if( m_p == NULL )
            m_p = new Singleton();

        return m_p;
    }

private:
    static Singleton* m_p;
};
Singleton* Singleton::m_p = NULL;
上述代码是普通的单例模式的实现方式。

为了让类具有多态行为,可以引入继承方式,具体如下:

class Singleton_1
{
protected:
    Singleton_1(){}

public:
    virtual void show(){}

    static Singleton_1* GetInstance( const char* name )
    {
        if( m_p == NULL )
        {
            if( strcmp( name, "SingletonA" ) == 0 )
            {
                m_p = new SingletonA();
            }
            else if( strcmp( name, "SingletonB" ) == 0 )
            {
                m_p = new SingletonB();
            }
        }

        return m_p;
    }

private:
    static Singleton_1* m_p;
};
Singleton_1* Singleton_1::m_p = NULL;

class SingletonA : public Singleton_1
{
    friend class Singleton_1;//this is important for the parent class enable to create the instance of the derive class
private:
    SingletonA(){}

public:
    virtual void show()
    {
        cout<<"SingletonA"<<endl;
    }
};

class SingletonB : public Singleton_1
{
    friend class Singleton_1;//this is important for the parent class enable to create the instance of the derive class
private:
    SingletonB(){}

public:
    virtual void show()
    {
        cout<<"SingletonB"<<endl;
    }
};
在上述代码中,将单例模式的基类作为派生类的友元类,这样使得在基类中可以创建构造函数被私有化的派生类实例,这样就能够实现根据需要创建对应的单例对象。

上述代码只是提供思路,具体的实现还需要考虑很多细节问题,如内存释放问题,多线程共享问题等。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值