写在前面:
首先,设计模式就是一套可以被复用的代码的总结,也可以是一个普遍问题的解决方案。Java中有23种设计模式,从今天开始为大家总结设计模式的用处,代码实现等。
单例设计模式:
(1)懒汉式
在调用getInstance方法时,才会创建实例。
代码实现:
package singleton;
/**
*
* @ClassName SingletonDemo2
* @Description 单例模式:懒汉式
* @author McGRADY
* @date 2018年3月4日
*/
public class SingletonDemo2 {
private SingletonDemo2() {
}
private static SingletonDemo2 singleton = null;
public static synchronized SingletonDemo2 getSingleton() {
if (singleton == null) {
singleton = new SingletonDemo2();
}
return singleton;
}
}
(2)饿汉式
在类加载时,就会创建Instance实例。
代码实现:
package singleton;
/**
*
* @ClassName SingletonDemo1
* @Description 单例模式:饿汉式
* @author McGRADY
* @date 2018年3月4日
*/
public class SingletonDemo1 {
private SingletonDemo1() {
}
private static SingletonDemo1 singleton = new SingletonDemo1();
public static SingletonDemo1 getSingleton() {
return singleton;
}
}
总结:
(1) 单例模式类中的构造器为private ,防止外界通过new 来创建实例
(2) 通过public static的方法,返回一个实例。