C/C++ 实现单类模式

本文介绍了设计模式中的单例模式,用于确保一个类只有一个实例,并提供全局访问点。通过示例代码展示了如何在C/C++中实现带有子类的单例模式,详细解释了单例模式的必要性和其解决的问题,包括静态对象的限制以及全局变量的初始化问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计模式名称: singleton(单例)

设计模式解决的问题:实现只实例一个对象,程序其他地方应用它;比如程序的日子类,方便代码任何地方都可以使用,同时避免参数的传递。

设计模式的设计思想:定义一个类,其中包括了静态的方法获取或者实例化该类,生产或者获得方法有些特别,其他方法都具有普通C/C++特性,如多态性。值得注意是一个普通的全局变量的对象或者static 变量对象有时候不够完成单例的任务,有如下情况原因:

原因1:无法保证单例的静态对象在代码中唯一的声明。可能在很多函数会有这样代码,从而多次声明了同一个对象: static Singleton a; 

原因2:全局变量的对象或者静态变量的对象无法实现动态初始化。有些单例在实例化时需要一些动态信息,而才用前者的方法是无法获取的,因为前者在编译的时候已经确定。

原因3:全局变量的对象在各个编译单元里初始化时是没有顺序的。因此无法采用判断语句来确定某个全局变量是否存在。

设计模型的参与者: 单例,客户程序

设计模型图:略

设计模型实例:采用具有子类的单例模型


/*
 * singleton.h
 *
 *  Created on: Dec 7, 2017
 *      Author: ff
 */


#ifndef INCLUDE_SINGLETON_H_
#define INCLUDE_SINGLETON_H_
class Singleton
{
public:
static Singleton* getInstance(char type);
virtual void makeWall();
virtual ~Singleton();
protected:
Singleton();


private:
static Singleton* _instance;
char* _name;
};


class SingletonA: public Singleton
{
friend class Singleton;
public:
void makeWall();
private:
SingletonA();


};
class SingletonB: public Singleton
{
friend class Singleton;
public:
void makeWall();
private:
SingletonB();
};

#endif /* INCLUDE_SINGLETON_H_ */



//singleton.cpp

#include <singleton.h>
#include <iostream>

using namespace std;
Singleton* Singleton::_instance;
Singleton* Singleton::getInstance(char type)
{
if(!_instance)
switch(type)
{
case 'A':
_instance=new SingletonA;
break;
case 'B':
_instance=new SingletonB;
break;
default:
_instance=new Singleton;
break;


}
return _instance;
}
Singleton::Singleton()
{
cout<<"Singleton constructor"<<endl;
_name=new char[10];
}
Singleton::~Singleton()
{
cout<<"~Singleton"<<endl;
delete[] _name;
}
void Singleton::makeWall()
{
cout<<"Singleton makeWall"<<endl;
}


SingletonA::SingletonA()
{
cout<<"Singleton constructorA"<<endl;
}
void SingletonA::makeWall()
{
cout<<"SingletonA makeWall"<<endl;
}


SingletonB::SingletonB()
{
cout<<"Singleton constructorB"<<endl;
}
void SingletonB::makeWall()
{
cout<<"SingletonB makeWall"<<endl;
}


//main.cpp

#include <singleton.h>
int main()
{
Singleton* in=Singleton::getInstance('A');
in->makeWall();

delete in;


return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值