首页 > 其他 > 详细

设计模式之单例模式

时间:2016-07-15 13:17:01      阅读:208      评论:0      收藏:0      [点我收藏+]

1、饿汉式:

 1 public class Singleton1 {
 2     /**
 3      * 单例模式之饿汉式
 4      */
 5     private static final Singleton1 S1 = new Singleton1();
 6     
 7     public static final Singleton1 getInstance(){
 8         return S1;
 9     }
10     
11     private Singleton1() {
12         System.out.println("单例模式之饿汉式");
13     }
14 }

2、懒汉式:

 1 public class Singleton2 {
 2     /**
 3      * 单例模式之懒汉式
 4      */
 5     private static Singleton2 S2 = null;
 6     
 7     public static final Singleton2 getInstance(){
 8         if(S2 == null){
 9             S2 = new Singleton2();
10         }
11         return S2;
12     }
13     
14     private Singleton2() {
15         System.out.println("单例模式之懒汉式");
16     }
17 }

测试类:
 1 public class Test {
 2  
 3      public static void main(String[] args) {
 4          
 5          //测试饿汉式
 6          Singleton1 S11 = Singleton1.getInstance();
 7          Singleton1 S12 = Singleton1.getInstance();
 8          
 9          System.out.println(S11);
10          System.out.println(S12);
11          
12          //测试懒汉式
13          Singleton2 S21 = Singleton2.getInstance();
14          Singleton2 S22 = Singleton2.getInstance();
15          
16          System.out.println(S21);
17          System.out.println(S22);
18      }
19  }
输出:
  单例模式之饿汉式
  net.stivebone.designpatterns.Singleton1@39e5b5
  net.stivebone.designpatterns.Singleton1@39e5b5
  单例模式之懒汉式
  net.stivebone.designpatterns.Singleton2@5f6303
  net.stivebone.designpatterns.Singleton2@5f6303

 构造器仅调用了一次,切仅有一个实例。

 

设计模式之单例模式

原文:http://www.cnblogs.com/stivebone/p/5672680.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!