数学与逻辑学中,singleton定义为“有且仅有一个元素的集合”。
单例模式最初的定义出现于《设计模式》(艾迪生维斯理, 1994):“保证一个类仅有一个实例,并提供一个访问它的全局访问点。”
Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”
单例模式最初的定义出现于《设计模式》(艾迪生维斯理, 1994):“保证一个类仅有一个实例,并提供一个访问它的全局访问点。”
Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”
单例模式,可分为饿汉式单例模式和懒汉式单例模式。
好了,由于本人语言组织能力有限,还是直接上源码吧。(呵呵..)
package org.xjh.pattern;
/**
* 单例模式
*
* @author xjh
*
*/
public class SingletonTest {
public static void main(String[] args) {
//SingletonForHungryTest();
SingletonForLazyTest();
}
public static void SingletonForLazyTest(){
//创建两个饿汉式实例
SingletonForLazy sfl1 = SingletonForLazy.newInstance();
SingletonForLazy sfl2 = SingletonForLazy.newInstance();
//单线程获取懒汉式实例
System.out.println(sfl1.hashCode() == sfl2.hashCode());
//多线程获取懒汉式实例
for(int i = 0; i < 20; i++){
new Thread(new Runnable(){
@Override
public void run() {
System.out.println(SingletonForLazy.newInstance().hashCode());
}
}).start();
}
}
public static void SingletonForHungryTest(){
//创建两个饿汉式实例
SingletonForHungry sfh1 = SingletonForHungry.newInstance();
SingletonForHungry sfh2 = SingletonForHungry.newInstance();
//单线程获取饿汉式实例
System.out.println(sfh1.hashCode() == sfh2.hashCode());
//多线程获取饿汉式实例
for(int i = 0; i < 20; i++){
new Thread(new Runnable(){
@Override
public void run() {
System.out.println(SingletonForHungry.newInstance().hashCode());
}
}).start();
}
}
}
/**
* 单例模式的饿汉式
* @author xjh
*
*/
class SingletonForHungry{
/**
* 第3步:提供一个私有的静态的本类的实例变量
*/
private final static SingletonForHungry instance = new SingletonForHungry();
/**
* 第1步:私有化构造方法
*/
private SingletonForHungry(){}
/**
* 第2步:提供一个静态的获取该类实例的一个方法供外界使用
* @return
*/
public static SingletonForHungry newInstance(){
return instance;
}
}
/**
* 单例模式的懒汉式
* @author xjh
*
*/
class SingletonForLazy{
private static SingletonForLazy instance = null;
private SingletonForLazy(){}
public static SingletonForLazy newInstance(){
//外部这层判断是为了提高性能,毕竟如果直接执行下面的代码的话,加锁和解锁是耗性能的
if(instance == null){
//加入同步锁,解决多线程访问带来的安全问题
synchronized(SingletonForLazy.class){
if(instance == null){ //判断是否已经实例化过了
instance = new SingletonForLazy();
}
}
}
return instance;
}
}