码迷,mamicode.com
首页 > 编程语言 > 详细

java设计模式

时间:2019-03-19 16:43:53      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:into   volatil   ola   java设计   vat   stat   rom   模式   check   

1、单例模式

  • 饿汉模式
public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
  
    // Private constructor suppresses
    // default public constructor
    private Singleton() {};
 
    public static Singleton getInstance() {
        return INSTANCE;
    }
  }

 

  • 懒汉模式
public class Singleton {
    private static volatile Singleton INSTANCE = null;
  
    // Private constructor suppresses 
    // default public constructor
    private Singleton() {};
  
    //Thread safe and performance  promote 
    public static  Singleton getInstance() {
        if(INSTANCE == null){
             synchronized(Singleton.class){
                 // When more than two threads run into the first null check same time, 
                 // to avoid instanced more than one time, it needs to be checked again.
                 if(INSTANCE == null){ 
                     INSTANCE = new Singleton();
                  }
              } 
        }
        return INSTANCE;
    }
  }

 



java设计模式

标签:into   volatil   ola   java设计   vat   stat   rom   模式   check   

原文地址:https://www.cnblogs.com/cnwuhao/p/10559403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!