设计模式之单例模式

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

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

 

转载于:https://www.cnblogs.com/stivebone/p/5672680.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值