设计模式名称: 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;
}