一.单例设计模式
单例设计模式是java的一种设计模式,有两种主要实现方式:懒汉式和饿汉式。
单例设计模式特点是:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须对外提供一个访问方法。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须对外提供一个访问方法。
二.单例模式代码实现
<span style="font-size:18px;background-color: rgb(255, 255, 255);">public class Singleton {
private static Singleton Single = null;
private Singleton() {
}
public static Singleton getInstance() {
if (Single == null) {
Single = new Singleton();
}
return Single;
}
</span>
三.懒汉式
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//懒汉式单例类.在第一次调用的时候实例化
public class Singleton2 {
//私有的默认构造子
private Singleton2() {}
//注意,这里没有final
private static Singleton2 single=null;
public synchronized static Singleton2 getInstance() {
if (single == null) {
single = new Singleton2();
}
return single;
}
} </span>
四.饿汉式
<span style="font-size:18px;background-color: rgb(255, 255, 255);"><span style="font-size:18px;">//饿汉式单例类.在类初始化时,已经自行实例化
public class Singleton1 {
//私有的默认构造方法
private Singleton1() {}
//已经自行实例化
private static final Singleton1 single = new Singleton1();
public static Singleton1 getInstance() {
return single;
}
} </span></span>