[Java][Sigleton]单态设计模式

  rel="File-List" href="file:///C:%5CUsers%5CHua_Yan%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"> rel="themeData" href="file:///C:%5CUsers%5CHua_Yan%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"> rel="colorSchemeMapping" href="file:///C:%5CUsers%5CHua_Yan%5CAppData%5CLocal%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml">
    Destination
:让一个类只允许存在一个实例。
    下面我们来看在Primary阶段实现的三个方法【见实例】。

method 1:
 
  1. public class Point {
  2.     
  3.     private int x; 
  4.     private int y;
  5.     private String id;
  6.     
  7.     static int count;
  8.     private static Point instance = new Point();
  9.     
  10.     public Point() {
  11.         id = "Point" + (++count);
  12.     }
  13.     
  14.     public static Point getInstance() {
  15.         
  16.         return instance;
  17.     }
  18.     
  19.     //main
  20.     public static void main(String[] args) {
  21.         
  22.         Point ex1 = Point.getInstance();
  23.         Point ex2 = Point.getInstance();
  24.         System.out.println("New Instance Number: " + count);
  25.     }
  26. }

method 2:

  1. public class Point {
  2.     
  3.     private int x; 
  4.     private int y;
  5.     private String id;
  6.     
  7.     static int count;
  8.     private static Point instance;
  9.     
  10.     public Point() {
  11.         id = "Point" + (++count);
  12.     }
  13.     
  14.     public static Point getInstance() {
  15.         
  16.         if(instance == null)
  17.             instance  = new Point();
  18.         return instance;
  19.     }
  20.     
  21.     //main
  22.     public static void main(String[] args) {
  23.         
  24.         Point ex1 = Point.getInstance();
  25.         Point ex2 = Point.getInstance();
  26.         System.out.println("New Instance Number: " + count);
  27.     }
  28. }

method 3:
这里我们看一下Crazy Bob在前几年解决该问题实现的方法:
  1.    1.  public class Singleton {   
  2.    2.   
  3.    3.   static class SingletonHolder {   
  4.    4.     static Singleton instance = new Singleton();   
  5.    5.   }   
  6.    6.   
  7.    7.   public static Singleton getInstance() {   
  8.    8.     return SingletonHolder.instance;   
  9.    9.   }   
  10.   10.   
  11.   11. } 
对于方法一和二的优劣,在引入线程的概念后,比较得出方法一好点,不过Bob Lee的懒汉法具体有多么优劣,在询问Master后才能清楚,各位也可留言给我
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值