设计模式总结(1)
单例模式
单例模式是java设计模式中较为简单但使用广泛的一种创建型模式。使用这种设计模式的类不需要实例化,可以直接使用并且只能有一个自己创建的实例。这样的优点是在一个类如果需要被频繁使用的场景下可以减少内存开销。
单例模式有多种实现方法:
饿汉式
**
* 饿汉式
*/
class Singleton1 {
private static Singleton1 singleton = new Singleton1();
private Singleton1() {
}
public static Singleton1 getInstance() {
return singleton;
}
}
饿汉式是一种懒加载的单例模式,只在该类需要被使用的时候才创建出来,并且这是一种线程不安全的单例模式。
懒汉式
/**
* 懒汉式
*/
class Singleton2 {
private static Singleton2 singleton;
private Singleton2(){}
public static synchronized Singleton2 getInstance() {
if (singleton == null) {
singleton = new Singleton2();
}
return singleton;
}
}
懒汉式是一种非懒加载的单例模式,该类在JVM启动的时候便会自动创建,因为加入了synchronized关键字,所以这是一种线程安全的单例模式。
懒汉式与饿汉式的根本区别在与是否在类内方法外创建自己的对象
单例模式的使用
/**
* 懒汉式使用
*/
class Singleton2 {
private static Singleton2 singleton;
private static int i;
private Singleton2(){
i=3;
}
public static synchronized Singleton2 getInstance() {
if (singleton == null) {
singleton = new Singleton2();
}
return singleton;
}
public void sayHelle() {
System.out.println(i++);
}
}
/**
* 测试
*/
public static void main(String[] args){
Singleton2 singleton21 = Singleton2.getInstance();
singleton21.sayHelle(); //3
Singleton2 singleton22 = Singleton2.getInstance();
singleton22.sayHelle(); //4
Singleton2 singleton23 = Singleton2.getInstance();
singleton23.sayHelle(); //5
}
双重锁模式
/**
* 双重锁模式
*/
class Singleton3 {
private static volatile Singleton3 instance = null;
private Singleton3() {
//do something
}
public static Singleton3 getInstance() {
if (instance == null) {
synchronized (Singleton3.class) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
单例设计模式还有一种双重锁的实现方法,这是一种懒加载、线程安全的单例模式。