zoukankan      html  css  js  c++  java
  • 设计模式之单件模式

    有人说叫单例模式,可是这有什么关系呢,叫什么都可以。

    好了进入正题,这个非常简单,就是把构造函数私有化,然后通过一个静态方法获得对象实例

    (这年头对象真不好找,都是私有化的)

    有一个问题就是可能会多线程的时候,导致实例化多次,解决这个问题的方法有三种:

    1、同步方法,简单快捷,但是性能较差:

    public class Singleton {
        private static Singleton uniqueInstance;
    
        private Singleton() {}
    
        public static synchronized Singleton getSingleInstance() {
            if (uniqueInstance == null) {
                uniqueInstance = new Singleton();
            }
            return uniqueInstance;
        }
    }
    

    2、直接实例化,简单粗暴,但是不会延时实例化。

    public class Singleton1 {
        public static Singleton1 uniqueInstance = new Singleton1();
    
        private Singleton1() {}
    
        public static Singleton1 getInstance() {
            return uniqueInstance;
        }
    }
    

    3、通过 同步块 与 volatile 原子操作关键字结合 双重加锁:

    public class Singleton2 {
        private volatile static Singleton2 uniqueInstance;
    
        private Singleton2() {}
    
        public static Singleton2 getInstance() {
            if (uniqueInstance == null) {
                synchronized (Singleton2.class) {
                    if (uniqueInstance == null) {
                        uniqueInstance = new Singleton2();
                    }
                }
            }
            return uniqueInstance;
        }
    }
    

    注:volatetile应不意味着真正的原子操作,在多线程涉及自身操作时会出现误差,如i++ ,结合同步块可解决此问题。

  • 相关阅读:
    WebService基于SoapHeader实现安全认证
    js中SetInterval与setTimeout用法
    Fiddler 教程
    jQuery 的 serializeArray()、serialize() 方法
    Javascript中Array.prototype.map()详解
    MS DOS 命令大全
    Chrome的JS调试工具
    jquery插件之DataTables 参数介绍
    C#中的Params、ref、out的区别
    C#记录日志、获取枚举值 等通用函数列表
  • 原文地址:https://www.cnblogs.com/yingbing/p/4739898.html
Copyright © 2011-2022 走看看