IT序号网

java设计模式--单例模式

luoye 2021年05月25日 编程语言 272 0

1.概念:运行时只有一个实例(对象)。

2.分类:

2.1懒汉式:在用的时候进行创建。

(多线程下的懒汉式:注意点:1.构造函数私有;2.多线程情况下,对象为空的时候进行创建)

 1 class Dog(){ 
 2      private static Dog instance; 
 3      //构造函数私有 
 4      private Dog(){ 
 5      } 
 6      public static Dog getInstance (){ 
 7           if(instance==null){ 
 8           //同步锁,在多线程下当instance为空时创建 
 9               syschronized(Dog.class){ 
10               if(instance==null){ 
11                  instance=new Dog(); 
12               } 
13             } 
14           } 
15           return instance; 
16      } 
17 }

2.2饿汉式:不管用不用先实例化,其构造函数为私有;

class Dog(){ 
     private static Dog instance =new Dog(); 
     //构造函数私有 
     private Dog(){ 
     } 
     public static Dog getInstance (){ 
          if(instance==null){ 
              syschronized(Dog.class){ 
              if(instance==null){ 
                 instance=new Dog(); 
              } 
            } 
          } 
          return instance; 
     } 
  }

评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

java重要基础知识汇总