单例模式(Singleton)

一、介绍

单例模式是一种比较普遍和简单的模式,在我们的程序中经常会用到。简单的说就是,单例模式就是让一个类永远只对外发布唯一的实例(Instance)。

 

 

二、实例

在本模式中介绍的例子中,SingleSpoon类拥有一个实例,声明为静态(static)私有(private)变量"theSpoon",核心代码内容如下:

public class SingleSpoon  {     
   private static SingleSpoon theSpoon;    
       
   private SingleSpoon() {}    
         
   public static SingleSpoon getTheSpoon() {    
       if (theSpoon == null) {    
           theSpoon = new SingleSpoon();    
       }    
       return theSpoon;    
   }    
        
   public String toString() {    
       return "Behold the glorious single spoon!";    
   }    
}   
 

单例模式的实际运用的代码如下:

class TestSingleSpoon {    
        
   public static void main(String[] args) {    
       System.out.println("First person getting the spoon");    
       SingleSpoon spoonForFirstPerson =     
         SingleSpoon.getTheSpoon();    
       if (spoonForFirstPerson != null)    
           System.out.println(spoonForFirstPerson);    
       else   
           System.out.println("No spoon was available");    
           
       System.out.println("");    
           
       System.out.println("Second person getting a spoon");    
       SingleSpoon spoonForSecondPerson = SingleSpoon.getTheSpoon();    
       if (spoonForSecondPerson != null)    
           System.out.println(spoonForSecondPerson);    
       else   
           System.out.println("No spoon was available");    
   }    
}  

 


三、分析

创建一个单例模式,需要注意的是:
1、实例变量应该是静态的私有的。
2、外部调用该实例时,不是通过类的构造方法,而是通过一个getInstance()这样的静态方法来创建该类的唯一实例。
3、默认的构造方法应该是私有的,没有强行规定,但觉得这样子自绝后路的办法未尝不可取 :P
4、单例模式并不是线程安全的,要实现这一点,必须在getTheSpoon()方法前面添加一个同步关键字synchronized。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值