ITeye博客

Singleton模式

fansofjava · 2009-03-05 23:46 · 设计模式 · 编程语言 · Markdown

这几天感觉想写点什么,但又没什么好写,最近又听人说起单例模式,所以想复习一下,把它写在这里。 单例就是指一个类只有一个实例。准确定义:

The Single pattern provides the possibility to control the number of instances(mostly one) that are allowed to be made.We also receive a global point of access to it(them).

实现方法有三种:

1、采用synchronized方法的方式实现。


public class Singleton {
	private static Singleton uniqueInstance;
	private Singleton(){}
	public static synchronized Singleton getInstance(){
		if(uniqueInstance==null){
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}
}

此方法有一些不足:因为只有第一次执行此方法时,才真正需要同步,一旦设置好uniqueInstance变量,就不再需要同步此方法。因此存在一些性能影响。

2、急切实例化


public class EagerSingleton {
	private static EagerSingleton uniqueInstance = new EagerSingleton();
	private EagerSingleton(){}
	public static  EagerSingleton getInstance(){
		return uniqueInstance;
	}
}

此方法在使用之前就把对象创建好了,所以不存在同步问题。如果在创建和运行时负担不太重的话,则较为合理。

3、双重检查加锁


public class DoubleCheckedSingleton {
	private volatile static DoubleCheckedSingleton uniqueInstance;
	private DoubleCheckedSingleton() {
	}
	public static DoubleCheckedSingleton getInstance() {
		if (uniqueInstance == null) {
			synchronized (DoubleCheckedSingleton.class) {
				if (uniqueInstance == null) {
					uniqueInstance = new DoubleCheckedSingleton();
				}
			}
		}
		return uniqueInstance;
	}
}

volatile: 当uniqueInstance被实例化时,多个线程正确地处理uniqueInstance变量,在JAVA 5 中有效。

单例模式的使用场合: When only one instance or a specific number of instances of a class are allowed. Facade objects are often Singletons because only one Facade object is required. 就是说当一个对象只需要一个实例或明确的实例个数时才被使用。外观对象(具体可见外观模式)通常就是单例模式。

优点: * Controlled access to unique instance. * Reduced name space. * Allows refinement of operations and representations.

缺点: Singleton pattern is also considered an anti-pattern by some people,who feel that it is overused,introducing unnecessary limitations in situations where a sole instance of a class is not actually required.

最新发现一种,就是通过枚举enum的方式:


public enum Elvis {
    INSTANCE;
    private int age;
    public int getAge() {
        return age;
    }
}

and then called Elvis.INSTANCE.getAge()也可以这样:


public enum Elvis {
    INSTANCE;
    private int age;


    public static int getAge() {
        return INSTANCE.age;
    }
}

and called Elvis.getAge() 优点:无偿的提供了序列化机制,能绝对保证实例的唯一性,是实现单例的最佳方法。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。