现在的位置: 首页 > 综合 > 正文

【2013.1.16】真相永远只有一个——Singleton

2018年10月09日 ⁄ 综合 ⁄ 共 1293字 ⁄ 字号 评论关闭

// // // // // // // // //

///2013.1.16

// // // // // // // // //

如果说评选一个最简单的设计模式的话,

Singleton当之无愧。

【核心】利用static使类与对象一一对应,并将类的构造函数私有化。


但单纯的外表下是Singleton强大的灵魂。

这一点童鞋们也能从今年的面向对象考试题中看出来(填空第一题就写Singleton…)。

在实际的编程应用中也不乏其拥有明显特征的代码身影。

最简单的例子,

就是假设我们创建一个类叫做HumanPlanet,那么应该只有一个名为Earth的实例。

值得一提的是,

这个模式在Java中是非常重要的,

因为在纯面向对象的范式中,是不可以使用static的。

还有很多人因为这个模式易用所以开始滥用,

但首先要注意两点:

1.使用单例不一定会节省内存。因为它的生命周期是Forever Until u delete it by yourself.

2.在需要扩展的结构当中,尽量不要使用单例,原因很简单,static容易扩展么?

接下来是示例代码。

HumanPlanet.h

#ifndef _HUMAN_PLANET_H_
#define _HUMAN_PLANET_H_

class HumanPlanet
{
private:
	static HumanPlanet* earth;
protected:

	//Constructor couldn't be accessed from outside.
	HumanPlanet(){}
public:
	static HumanPlanet* GetHumanPlanet();

	//This function only used to test this class is exist.
	void saySomething();
};

#endif

HumanPlanet.cpp

#include"HumanPlanet.h"
#include<iostream>

//Initial static variable before use it.
HumanPlanet* HumanPlanet::earth = 0;

HumanPlanet* HumanPlanet::GetHumanPlanet()
{
	if(earth == nullptr)
		earth = new HumanPlanet();
	return earth;
}

void HumanPlanet::saySomething()
{
	std::cout<<"Only one earth,please love and protect this beautiful planet."<<std::endl;

	return;
}

main.cpp

#include "HumanPlanet.h"

int main()
{
	HumanPlanet* planet = HumanPlanet::GetHumanPlanet();
	planet->saySomething();

	return 0;
}

以及输出结果:


最后需要注意的是,

在c++中不可以直接使用静态函数的返回值来do something.(And i knew this point after i programming this example...)

抱歉!评论已关闭.