* 单例模式:饿汉加载式
* 1.静态常量饿汉式:类一加载就创建单例实例,浪费内存,效率不高。
* 2.静态代码块饿汉式:把创建对象方到静态块里
*/
public class HungryMan {
private HungryMan(){}
private final static HungryMan instance = new HungryMan();
public HungryMan getInstance(){
return instance;
}
}
* 单例模式:懒汉模式
* 线程安全懒汉式:
* 1.同步代码块式
* 2.双重校验式
* 3.静态内部类式
* 4.枚举方式
*/
public class LazyMan {
private LazyMan(){}
private static LazyMan instance = null;
public static synchronized LazyMan getInstance(){
if (instance == null){
instance = new LazyMan();
}
return instance;
}
}
class LazyMan_DoubleCheck{
private LazyMan_DoubleCheck(){}
private static volatile LazyMan_DoubleCheck instance = null;
public static LazyMan_DoubleCheck getInstance(){
if (instance == null){
synchronized (LazyMan.class){
if (instance == null){
instance = new LazyMan_DoubleCheck();
}
}
}
return instance;
}
}
class LazyMan_StaticInnerClass{
private LazyMan_StaticInnerClass(){}
private static class LazyMan_Instance{
private static final LazyMan_StaticInnerClass INSTANCE = new LazyMan_StaticInnerClass();
}
public LazyMan_StaticInnerClass getInstance(){
return LazyMan_Instance.INSTANCE;
}
}
enum LazyMan_Enum{
INSTANCE;
}
class MyTest{
public static void main(String[] args) {
LazyMan instance = LazyMan.getInstance();
LazyMan instance2 = LazyMan.getInstance();
if (instance == instance2){
System.out.println("是单例模式,同一个内存地址!"+instance.hashCode()+":"+instance2.hashCode());
}
}
}