单例模式
Singleton Pattern
定义:
Ensure a class has only one instance, and provide a global point of access to it.
确保一个类只有一个实例(对象),而且自行实例化并且像整个系统提供这个实例
通用代码
/**
* 饿汉式单例
*/
public class Singleton {
private final static Singleton singleton = new Singleton;
//构造私有,限制产生多个对象
private Singleton() {
}
//提供get实例对象的方法
public static Singleton getSingleton() {
return this.singleton;
}
// 该类中的其他方法 最好也是 static 修饰的
public static void fun() {
}
}
/**
* 懒汉式单例, 是线程不安全的
*/
public class Singleton {
private final static Singleton singleton = null;
private Singleton() {
}
public static Singleton getSingleton() {
if singleton == null {
singleton = new Singleon();
}
return singleton;
}
public static void fun() {
}
}
优点:
- 减少内存的资源消耗,因为无需频繁创建、销毁;
- 减少系统性能开销,就是说当需要一些读取较多资源的时候,比如读取配置文件等。就可以只需要创建一个单例的对象,让它常驻内存中。当然,这需要注意垃圾回收GC。
- 避免对资源的多重占用或重复读取;
- 可以作为系统的全局访问点,优化资源的共享。
缺点:
-
因为没有interface,所以除了修改代码外,很难进行拓展。
Q:为何没接口?
A:因为单例模式需要自行实例化呀,interface或者abstract都是需要不能直接实例化的。
-
单例模式对测试不利。
-
单例模式和单一职责原则有冲突。
个人觉得还好吧;换句话说,单一职责本来就很难实现的。
实践:
- Spring 中的
Bean
就是使用单例模式;从而Spring可以统一管理这些Bean的生命周期。