• 单例模式


    单例模式是一种比较简单的模式,其定义是ensure a class has only one intance ,and provide a global point of access to it .(确保某一个类只有一个实例,并自行实例化,并向整个系统提供这个实例)

    主要分为2种模式,饿汉式和懒汉式。

    package src;
    
    /**
     * 饿汉式
     * 
     * @author joke
     * 
     */
    public class Singleton {
        private static Singleton singleton = new Singleton();
    
        private Singleton() {
    
        }
    
        public static Singleton getInstance() {
            return singleton;
        }
    }

    上面这个模式可以解决在高并发场景下的线程不安全问题,还有一种模式是懒汉式,如下:

    package src;
    
    /**
     * 懒汉式
     * 
     * @author joke
     * 
     */
    public class Singleton1 {
        private Singleton1 singleton = null;
    
        private Singleton1() {
    
        }
    
        public Singleton1 getInstance() {
            if (singleton == null) {
                singleton = new Singleton1();
            }
            return singleton;
        }
    }

    在上述懒汉式的下,在高并发场景下在内存中出现多个实例,比如在线程A执行到singleton = new Singleton1(),还没有返回singleton的时候,另外线程B执行到 if (singleton == null) 时候,此时的判断为空的,此时内存中就会出现2个实例,为了解决此问题,我们一般会在getInstance()前加上关键字synchronized,但其仍不是优秀的单例模式,其代码如下:

    package src;
    /**
     * 解决线程不安全的懒汉式
     * @author joke
     *
     */
    public class Singleton1 {
        private Singleton1 singleton = null;
    
        private Singleton1() {
    
        }
    
        public synchronized Singleton1 getInstance() {
            if (singleton == null) {
                singleton = new Singleton1();
            }
            return singleton;
        }
    }

    单例模式的使用场景:

    1、要求使用唯一序列号的环境

    2、在整个项目中需要一个共享访问点或共享数据

    3、创建一个对象需要消耗资源过多时

    4、需要定义大量的静态常量和静态方法的环境(比如工具类)。

  • 相关阅读:
    2017.5.11下午学习内容
    windows消息和消息队列
    探索Win32系统之窗口类(转载)
    WinMain函数详解(转载)
    Ajax爬取实战头条街拍美图
    Ajax实战微博
    Ajax请求分析实战
    ubuntu 安装rails
    ubuntu Thunderbird 接收邮件显示乱码的问题排除
    ubuntu 开机挂载windows分区
  • 原文地址:https://www.cnblogs.com/shawnblogs/p/4870456.html
Copyright © 2020-2023  润新知