单例模式:某个类只存在一个对象实例
方法1:饿汉式
class HungryMan{
//1.私有化类的构造器
private HungryMan(){}
//2.内部创见类的对象
//4.要求此对象也必须声明为静态的
private static HungryMan instance = new HungryMan();
//3.提供公共的静态的方法,返回类的对象。
public static HungryMan getInstance(){
return instance;
}
}
方法2、3:懒汉式
class LazyMan{
//1.私有化类的构造器
private LazyMan(){}
//2.声明当前类对象,没有初始化。
//4.此对象也必须声明为 static 的
private static LazyMan instance = null;
//3.提供公共的静态的方法,返回类的对象。
//方式2:线程要一个一个的去获取对象
// public static synchronized LazyMan getInstance() {//synchronized也可以写在方法里,形成同步代码块
// if (instance == null) {
// instance = new LazyMan();
// }
// return instance;
// }
//方式3:使用了double-check,可以多线程同时并发访问获取对象
public static LazyMan getInstance(){
if(instance == null) {
synchronized (LazyMan.class) {
if (instance == null) {
instance = new LazyMan();
}
}
}
return instance;
}
}
方法4:内部静态类,外部类初次加载,会初始化静态变量、静态代码块、静态方法,但不会加载内部类和静态内部类。
class InnerStaticClass {
private InnerStaticClass() {}
public static InnerStaticClass getInstance() {
return InnerStaticClassFactory.instance;
}
private static class InnerStaticClassFactory {
private static InnerStaticClass instance = new InnerStaticClass();
}
}
方法5:枚举
enum Enumeration {
INSTANCE;
public void doSomething() {
System.out.println("doSomething");
}
}
测试:
public class BankTest {
public static void main(String[] args) {
HungryMan hungryMan1 = HungryMan.getInstance();
HungryMan hungryMan2 = HungryMan.getInstance();
LazyMan lazyMan1 = LazyMan.getInstance();
LazyMan lazyMan2 = LazyMan.getInstance();
InnerStaticClass innerStaticClass1 = InnerStaticClass.getInstance();
InnerStaticClass innerStaticClass2 = InnerStaticClass.getInstance();
Enumeration.INSTANCE.doSomething();
System.out.println(hungryMan1 == hungryMan2);
System.out.println(lazyMan1 == lazyMan2);
System.out.println(innerStaticClass1 == innerStaticClass2);
}
}
结果:
doSomething
true
true
true
Process finished with exit code 0