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

来源:互联网 发布:电脑风扇反转软件 编辑:程序博客网 时间:2024/04/30 02:35

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

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

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



publicclassWechatPropertiesextendsProperties {


  privatefinalstaticStringWECHAT_PROPERTIES_FILE_NAME="wechat.properties";


  privatestaticWechatPropertiesinstance;


  privateWechatProperties() {


   }


  privateWechatProperties(Propertiesarg0){

    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(IOExceptione){

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

       }

     }

    returninstance;

   }


}



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

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

0 0
原创粉丝点击