zoukankan      html  css  js  c++  java
  • 设计模式--单例模式学习

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

    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 }
  • 相关阅读:
    面试题来积累自己
    基于php基础语言编写的小程序之计算器
    配置apache的虚拟机+软件下载
    执行表空间使用率SQL突然变慢问题分析
    DM-建库选项-字符串比较大小写敏感-测试
    OGG再次遇到虚拟列无法处理,导致进程abend二
    OGG应用进程abend报错无法insert虚拟列
    Oracle Asm Failgroup测试学习
    OGG复制进程报错,存在update set 主键列 is null
    测试:OGG初始化同步表,源端抽取进程scn<源端事务的start_scn时,这个变化是否会同步到目标库中?
  • 原文地址:https://www.cnblogs.com/androidstudy/p/3482708.html
Copyright © 2011-2022 走看看