设计模式--单例模式学习

最近学习设计模式,做一点总结:

1.单例模式的实现一

单例模式使用内部类来维护单例的实现,JVM内部的机制能够保证当一个类被加载的时候,这个类的加载过程是线程互斥的。这样当我们第一次调用getInstance的时候,JVM能够帮我们保证instance只被创建一次,并且会保证把赋值给instance的内存初始化完毕,这样我们就不用担心上面的问题。同时该方法也只会在第一次调用的时候使用互斥机制,这样就解决了低性能问题。

 1 public class Singleton implements Serializable {
 2     private Singleton() {
 3 
 4     }
 5 
 6     public static Singleton getInstance() {
 7         return SingletonFactory.instance;
 8     }
 9 
10     /* 此处使用一个内部类来维护单例 */
11     private static class SingletonFactory {
12         private static Singleton instance = new Singleton();
13     }
14 
15     /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
16     public Object readResovle() {
17         return getInstance();
18     }
19 }

第二种方法:

因为我们只需要在创建类的时候进行同步,所以只要将创建和getInstance()分开,单独为创建加synchronized关键字,

 1 public class Singleton2 implements Serializable {
 2     private static Singleton2 instance = null;
 3 
 4     private Singleton2() {
 5     }
 6 
 7     private static synchronized void syncInit() {
 8         if (instance == null) {
 9             instance = new Singleton2();
10         }
11     }
12 
13     public static Singleton2 getInstance() {
14         if (instance == null) {
15             syncInit();
16         }
17 
18         return instance;
19     }
20 
21     public Object readResolve() {
22         return instance;
23     }
24 
25 }

 第三:采用"影子实例"的办法为单例对象的属性同步更新

 1 public class Singleton3 {
 2     private static Singleton3 instance = null;
 3     private Vector properties = null;
 4 
 5     private Singleton3() {
 6     }
 7 
 8     public Singleton3 getInstance() {
 9         if (instance == null) {
10             syncInit();
11         }
12 
13         return instance;
14     }
15 
16     public Vector getProperties() {
17         return properties;
18     }
19 
20     public void updateProperties() {
21         Singleton3 shadow = new Singleton3();
22         properties = shadow.getProperties();
23     }
24 
25     private static synchronized void syncInit() {
26         if (instance == null) {
27             instance = new Singleton3();
28         }
29     }
30 
31 }

 

posted @ 2013-12-19 18:48  自由飞翔2012  阅读(167)  评论(0编辑  收藏  举报