java常用设计模式--单例模式简单例子

package com.ruanyun;

/**
* @Auther: maxw
* @Date: 2018/11/10 17:29
* @Description:
*/
public class Test4 {
public static void main(String args[]){
F99 f99 = F99.getInstance();
F99 f100 = F99.getInstance();
System.out.println(f99==f100);
}
}
//假设 F99战机 只有一架
class F99{
//懒汉模式
/* private volatile static F99 f99;
public F99() {
}
public static synchronized F99 getInstance(){
if(f99 == null){
f99 = new F99();
}
return f99;
}*/
//饿汉模式
/*private static final F99 f99 = new F99();
public F99() {
}
public static F99 getInstance(){
return f99;
}*/
//双重锁模式
/*private volatile static F99 f99;
public F99() {
}
public static F99 getInstance(){
if(f99==null){
synchronized (F99.class){
if(f99==null){
f99 = new F99();
}
}
}
return f99;
}*/
//静态内部类模式 最优写法
private static class innerClass{
private static final F99 f99 = new F99();
}
public static F99 getInstance(){
return innerClass.f99;
}
//还有一种方法 枚举 在此不再展示
}

猜你喜欢

转载自www.cnblogs.com/maxiw/p/9940138.html