• 设计模式系列(八)23种设计模式-----单例设计模式


    单例模式

    所谓的单例模式,就是 采取一定的方法保证整个软件的系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法 (静态方法)

    例如: HibernateSessionFactory,它充当数据存储源的代理,并负责创建 Session 对象。SessionFactory 并不是轻量级的,一般情况下,一个项目中只需要一个 SessionFactory,这就是单例模式

    单例模式有八种

    • 饿汉式(静态常量)
    • 饿汉式(静态代码块)
    • 懒汉式(线程不安全)
    • 懒汉式(线程安全,同步方法)
    • 懒汉式(线程安全,同步代码块)
    • 双重检查
    • 静态内部类
    • 枚举

    饿汉式(静态常量)

    步骤:

    • 构造器私有化 (防止 new)
    • 类的内部创建对象
    • 只向外部暴露一个静态的公共方法。 getInstance
    1. 代码实现
    //饿汉式(静态变量)
    class Singleton {
    	//1. 构造器私有化, 防止外部new创建实例
    	private Singleton() {
    	}
    	
    	//2.本类内部创建对象实例
    	private final static Singleton instance = new Singleton();
    
    	//3. 提供一个公有的静态方法,返回实例对象,主要是提供给外部,让外界引用
    	public static Singleton getInstance() {
    		return instance;
    	}
    }
    
    
    public class SingletonTest01 {
    	public static void main(String[] args) {
    		//测试
    		Singleton instance = Singleton.getInstance();
    		Singleton instance2 = Singleton.getInstance();
    		
    		System.out.println(instance == instance2); // true
    		
    		System.out.println("instance.hashCode=" + instance.hashCode());
    		System.out.println("instance2.hashCode=" + instance2.hashCode());
    	}
    }
    
    1. 优缺点
    • 优点:写法简单,实际上在类装载的时候就完成了实例化,避免了线程同步问题。
    • 缺点:在类装载的时候就完成了实例化,没有实现 Lazy Loading懒加载 的效果。如果在项目中从始至终就没有使用过这个实例,则会造成内存的浪费
    • 这种方法基于 classloder 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,在单例模式中大多数都是调用 getInstace 方法,但是导致类装载的原因有多种,因此不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 就没有达到 懒加载 的效果

    因此:这种单例模式可用,但是可能会造成内存的浪费。除非开发人员能肯定,此类一定会被用到,那么内存就不会被浪费

    饿汉式(静态代码块)

    1. 代码
     //饿汉式(静态变量)
    class Singleton {
    	//1. 构造器私有化
    	private Singleton() {
    	}
    	
    	//2.本类内部创建对象实例
    	private static Singleton instance;
    	
    	static { // 在静态代码块中,创建单例对象
    		instance = new Singleton();
    	}
    	//3. 提供一个公有的静态方法,返回实例对象
    	public static Singleton getInstance() {
    		return instance;
    	}
    }
    
    1. 优缺点
    • 这种和上面一种很类似,都是在类内部实例化,只不过将类的实例化放在了静态代码块中。类一加载,就执行了静态代码块中的代码。优缺点和上面一样
    • 这种单例模式可用,但是如果不用,可能会造成内存的浪费

    懒汉式(线程不安全)

    1. 代码
    class Singleton {
    	private static Singleton instance;
    	
    	// 构造函数私有化
    	private Singleton() {}
    	
    	// 提供一个静态的公有方法,当使用到该方法时,才去创建instance,即懒汉式
    	public static Singleton getInstance() {
    		if(instance == null) {
    			instance = new Singleton();
    		}
    		return instance;
    	}
    }
    
    public class SingletonTest03 {
    	public static void main(String[] args) {
    		Singleton instance = Singleton.getInstance();
    		Singleton instance2 = Singleton.getInstance();
    		
    		System.out.println(instance == instance2); // true
    		
    		System.out.println("instance.hashCode=" + instance.hashCode());
    		System.out.println("instance2.hashCode=" + instance2.hashCode());
    	}
    }
    
    1. 优缺点
    • 起到了 懒加载 的效果,但是只能在 单线程下使用
    • 如果在多线程下,一个线程进入了 if(instance == null) { 判断语句块,还未来得及往下执行,另外一个线程也通过了这个判断语句,这时便会产生多个实例,所以在多线程环境下不可使用这种方式。
    • 在实际开发中,不要使用这种方式

    懒汉式(线程安全,同步方法)

    1. 代码
    // 懒汉式(线程安全,同步方法)
    class Singleton {
    	private static Singleton instance;
    	// 构造方法私有
    	private Singleton() {}
    	//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
    	//即懒汉式
    	public static synchronized Singleton getInstance() {
    		if(instance == null) {
    			instance = new Singleton();
    		}
    		return instance;
    	}
    }
    

    注:加入关键字保证线程安全问题 synchronized

    1. 优缺点
    • 虽然加入保证线程安全的关键字,解决线程安全问题(其实实际上并不一定线程安全)
    • 效率低下,每个线程在想获得实例的时候,执行 getInstance 方法都要进行同步。而其实这个方法只执行一次实例化代码就够了。后续想要获得实例,直接return 就行。方法同步的效率太低
    • 在实际开发中,不推荐这种方式

    懒汉式(线程安全,同步代码块)

    不推荐使用
    在这里插入图片描述

    双重检查

    1. 代码
    class Singleton {
    	private static volatile Singleton instance;
    	
    	// 构造方法私有化
    	private Singleton(){}
    	
    	// 提供可以被外部引用的静态方法,使用双重检查机制 double check
    	public static synchronized Singleton getInstance(){
    		if (instance == null){
    			synchronized(Singleton.class){
    				if(instance == null){
    					instance = new Singleton();	
    				}
    			}
    		}
    		return instance;
    	}
    }
    
    1. 优缺点
    • Double-Check 概念是多线程开发中常使用到的,如代码中所示,我们进行了两次 if(singleton== null)检查,这样就可以保证线程安全了
    • 这样,实例化代码只用执行一次,后面在进行访问的时候,判断 if(singleton== null),直接 return 实例化对象,也避免了反复进行方法同步。
    • 最重要的是 线程安全,延迟加载,效率高
    • 在实际开发中,推荐使用这种单例设计模式

    静态内部类

    1. 代码
    // 静态内部类完成, 推荐使用
    class Singleton {
    	private static volatile Singleton instance;
    	
    	//构造器私有化
    	private Singleton() {}
    	
    	//写一个静态内部类,该类中有一个静态属性Singleton
    	private static class SingletonInstance {
    		private static final Singleton INSTANCE = new Singleton();
    	}
    	
    	//提供一个静态的公有方法,直接返回SingletonInstance.INSTANCE
    	public static synchronized Singleton getInstance() {
    		return SingletonInstance.INSTANCE;
    	}
    }
    
    1. 优缺点
    • 这种方式采用了类装载的机制保证了初始化实例时只有一个线程
    • 静态内部类的方式在 singleton 类被装载时并不会被立即实例化,而是在需要的实例化的时候,调用 getInstance 方法,才会装载 SingletonInstance 类,从而完成 Singleton 的实例化
    • 类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM 帮助我们保证了线程的安全性,在类进行初始化的时,别的线程是无法j进入的
    • 优点:避免了线程不安全,利用静态内部类特点实现y延迟加载,效率高
    • 推荐上实际开发中使用

    枚举

    1. 代码
    //使用枚举,可以实现单例, 推荐
    enum Singleton {
    	INSTANCE; //属性
    	
    	public void sayOK() {
    		System.out.println("ok~");
    	}
    }
    
    public class SingletonTest08 {
    	public static void main(String[] args) {
    	
    		Singleton instance = Singleton.INSTANCE;
    		Singleton instance2 = Singleton.INSTANCE;
    		
    		System.out.println(instance == instance2);
    		
    		System.out.println(instance.hashCode());
    		System.out.println(instance2.hashCode());
    		instance.sayOK();
    	}
    }
    
    1. 优缺点
      这借助 JDK1.5 中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,推荐使用。

    单例模式在JDK源码中的使用

    JDK中,java.lang.Runtime 就是经典的单例模式(饿汉式)
    在这里插入图片描述

  • 相关阅读:
    Linux 重启命令
    Linux TCP连接数修改
    Linux 命令--查看物理CPU个数、核数、逻辑CPU个数
    keepalived配置文件
    keepalived 安装配置
    linux下keepalived 安装配置
    redis主从切换的集群管理
    CentOS_5.6下使用cmake编译MySQL_5.5.11
    cas错误:org.jasig.cas.client.validation.TicketValidationException: No principal was found in the response from the CAS server.
    完美实现在同一个页面中使用不同样式的artDialog样式
  • 原文地址:https://www.cnblogs.com/shanggushenlong/p/13801414.html
Copyright © 2020-2023  润新知