设计模式(1)-对象创建型模式-Singleton模式

来源:互联网 发布:启动mysql服务 编辑:程序博客网 时间:2024/05/21 08:42

1.对象创建型模式

1.1            SINGLETON模式

 

Singleton 模式是最为简单、最为常见、最容易实现的设计模式。公司企业在招聘的时候为了考察员工对设计的了解和把握,考的最多的就是Singleton模式。

1.1.1 意图

意图: 保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1.1.2 动机(需求)

动机: 保证一个类仅有一个实例,并提供一个访问它的全局访问点。比如只应该有一个文件系统和一个窗口管理器。

1.1.3 结构


1.1.4 C++实现

 

//Singleton.h

#ifndef _SINGLETON_H_

#define _SINGLETON_H_

#include<iostream>

using namespace std;

 

class Singleton

{

public:

       static Singleton *Instance();

protected:

       Singleton();

private:

       static Singleton *_instance;

};

#endif //~_SINGLETON_H_

 

//Singleton.cpp

#include"Singleton.h"

#include<iostream>

using namespace std;

 

Singleton*Singleton::_instance = 0;

Singleton::Singleton()

{

       cout << "Singleton...."<< endl;

}

 

Singleton*Singleton::Instance()

{

       if (_instance == 0)

       {

              _instance = new Singleton();

       }

       return _instance;

}

 

#include"Singleton.h"

#include<iostream>

using namespace std;

 

int main(int argc, char*argv[])

{

       Singleton *sgn = Singleton::Instance();

       return 0;

}

 

客户仅通过I n s t a n c e 成员函数访问这个单件。变量_ i n s t a n c e初始化为0,而静态成员函数In s t a n c e 返回该变量值,如果其值为0则用唯一实例初始化它。I n s t a n c e使用惰性(l a z y)初始化;它的返回值直到被第一次访问时才创建和保存。

注意构造器是保护型的。试图直接实例化S i n g l e t o n的客户将得到一个编译时的错误信息。这就保证了仅有一个实例可以被创建。

1.1.5 Java实现

 

一个经典的单例实现:
public class Singleton{
      
private static Singleton uniqueInstance = null;
      private Singleton(){
          // Exists only todefeat instantiation.
     
}

   public static SingletongetInstance() {
             
if (uniqueInstance == null) {
                      
uniqueInstance = new Singleton();

      }

       return uniqueInstance;

   }

    // Othermethods...

}

Singleton通过将构造方法限定为private避免了类在外部被实例化,在同一个虚拟机范围内,Singleton的唯一实例只能通过getInstance()方法访问。(事实上,通过Java反射机制是能够实例化构造方法为private的类的,那基本上会使所有的Java单例实现失效。此问题在此处不做讨论,姑且掩耳盗铃地认为反射机制不存在。)

Singleton模式经常和Factory(AbstractFactory)模式在一起使用,因为系统中工厂对象一般来说只要一个.

0 0