单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:
1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。
2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。
3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。(比如一个军队出现了多个司令员同时指挥,肯定会乱成一团),所以只有使用单例模式,才能保证核心交易服务器独立控制整个流程。
package test.single;
public class Singleton {
private static Singleton sing = null;
private Singleton(){}
//线程不安全
public static Singleton getInstance_one() {
if(null == sing){
sing = new Singleton();
System.out.println("-----getInstance_one():线程不安全-----");
}
return sing;
}
//性能低
public static synchronized Singleton getInstance_two(){
if(null == sing){
sing = new Singleton();
System.out.println("-----getInstance_two():性能低-----");
}
return sing;
}
//调用时不需要加锁,当sing为null时才会加锁实例化
public static Singleton getInstance_three(){
if(null == sing){
synchronized (sing) {
if(null == sing){
sing = new Singleton();
System.out.println("-----getInstance_three():调用不需要加锁,sing为null时加锁实例化-----");
}
}
}
return sing;
}
public static class SingletonFactory {
private static Singleton singleton = new Singleton();
}
//内部类
public static Singleton getInstance_four(){
System.out.println("-----getInstance_four():内部类实例化-----");
return SingletonFactory.singleton;
}
private static synchronized void synInit(){
if(null == sing){
sing = new Singleton();
System.out.println("-----synInit():独立方法加锁实例化-----");
}
}
//独立加锁实例化
public static Singleton getInstance_five(){
if(null == sing){
synInit();
}
return sing;
}
}
1、单例模式理解起来简单,但是具体实现起来还是有一定的难度。
2、synchronized关键字锁定的是对象,在用的时候,一定要在恰当的地方使用(注意需要使用锁的对象和过程,可能有的时候并不是整个对象及整个过程都需要锁)。