单例模式:创建独一无二的对象

单例模式是最简单也是最复杂的设计模式,说简单是因为组成单例模式的只有一个类,说复杂是因为单例模式的实现起码有七八上十种。有兴趣的程序员朋友请百度“单例模式有几种”。

本人在项目中往往将property文件的读写类设计成单例模式,这样可以保证在整个项目中读写property文件的一致性。

由于单例模式的实现只有一个类,就不看类图了,直接上代码:



publicclassWechatProperties extendsProperties {


   privatefinalstaticString WECHAT_PROPERTIES_FILE_NAME= "wechat.properties";


   privatestaticWechatProperties instance;


   privateWechatProperties() {


   }


   privateWechatProperties(Properties arg0){

     super(arg0);

   }


   publicstaticsynchronizedWechatProperties getInstance() throwsPropertiesException {

     if(null== instance){

       instance= newWechatProperties();

       InputStreampropertiesFileStream= WechatProperties.class.getResourceAsStream("/"+ WECHAT_PROPERTIES_FILE_NAME);

       if(null== propertiesFileStream){

         thrownewPropertiesFileNotExistException("Load"+ WECHAT_PROPERTIES_FILE_NAME+ "failed, please make sure that file is in the classpath.");

       }

       try{

         instance.load(propertiesFileStream);

       }catch(IOException e){

         thrownewPropertiesException("Load"+ WECHAT_PROPERTIES_FILE_NAME+ "error, "+ e.getMessage());

       }

     }

     returninstance;

   }


}



从代码中可见,WechatProperties类的实例是在getInstance()方法中创建的,因此是典型的懒汉型单例模式。用synchronized关键字修饰getInstance()方法,使得该单例模式是线程安全的。这种单例模式牺牲了一点效率,保证了线程的安全和资源的最小占用。

希望以上的例子对您理解和使用单例模式能有所启发和借鉴。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值