1.单例模式

单例模式

主要分为以下三部分讲解,请认真看完,绝对是最全面的单例模式的讲解

  • 单例模式的演化 (基础)
    饿汉式–>懒汉式(最基础的懒汉式–>单重校验–>双重校验)–>枚举实现(最好的单例模式的实现)
  • 单例模式的反思(基础)
    volatile关键字的应用+选择单例模式的意见
  • 单例模式引出的volatile+反射知识(引申)

1.单例模式的演化

注意点:1.构造方法私有 2.实例静态+私有(private static Singleton singleton) 3.公开+静态getInstance()方法

/**
 * Created with IntelliJ IDEA.
 *
 * @author: mason
 * @date: 2019-09-13
 * Time: 20:57
 * Description:
 */
public class Singleton {
    //构造方法私有
    private Singleton(){}
    //饿汉式 线程安全
    /*private static Singleton singleton = new Singleton();
    public static Singleton getInstance(){
        return singleton;
    }*/
    //懒汉式 线程不安全
    //1.多线程情况下不安全
   /* private static Singleton singleton = null ;
    public static   Singleton getSingleton(){
        if(singleton==null){
            singleton = new Singleton();
        }
        return singleton;
    }*/
    //2.改进 加synchronized保证了单一对象
    /*private static Singleton singleton = null ;
    public synchronized static   Singleton getSingleton(){
        if(singleton==null){
            singleton = new Singleton();
        }
        return singleton;
    }*/
    //与在类加synchronized效果一样
    /*private static Singleton singleton = null;

    public static Singleton getSingleton() {
        synchronized (Singleton.class) {
            if (singleton == null) {
                singleton = new Singleton();
            }
            return singleton;
        }
    }*/
    //3.双重检查进行校验 锁定部分代码块 提高效率
    private static Singleton singleton = null;

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

使用枚举实现

public class EnumSingleton{
	INSTANCE;
	public void sayHello(){
			System.out.pringln("HELLO");
		}
 }

2.单例模式的反思

volatile关键字的应用+选择单例模式的意见
A:volatile关键字防止指令重排序,具体详细的解释看文末,需要在双重校验即以下代码需要加volatile

public class Singleton {
//1.对象私有且静态
 private static  Singleton singleton = null;//此处需要加volatile关键字
 //2.构造方法私有
 private Singleton(){}
 //3.获取实例方法公开且静态
 public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                	//若无volatile此行会发生指令重排序,
                    //原因在于此处为非原子操作具体看文章末尾的解释
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

B:如何选择合适的单例模式
单例模式的写法那么多,到底选择哪一种呢,在我看来可以选择饿汉式,双重检验的懒汉式来完成功能的实现,如果明确要求要能够应对反射攻击,则选择枚举方法,千万不要选择最基础的懒汉式或者单重校验的懒汉式。

3.单例模式引出的volatile+反射知识

A.单例模式中的volatile(具体看下述链接)

https://blog.youkuaiyun.com/qq_25848311/article/details/102630344

B.反射知识

一句话总结反射:在运行时动态的获取类的属性和方法,对象的属性和方法。
可以利用反射创建对象(改变已有的new对象的方式)

//单例类
public class Singleton {
    private Singleton() {
    }
    //C 需要加锁 此时需要用volatile关键字
    private static Singleton instance = null;
    public synchronized Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    public void print(){
        System.out.println("ok");
    }
    //私有方法
    private void printPrivate(){
        System.out.println("我是私有方法");
    }

}
//测试类
public class TestSingleton {
    //    Singleton singleton = new Singleton();
    //反射获取
    public static void ReflectNewInstance() {
        try {

            Class<?> className = Class.forName("model.decorate.Singleton.Singleton");
			//创建对象
            Constructor<?> constructor = className.getDeclaredConstructor();
            constructor.setAccessible(true);
            Singleton singleton = (Singleton) constructor.newInstance();

			//创建方法
            Method method = className.getDeclaredMethod("printPrivate");
            method.setAccessible(true);
            method.invoke(singleton);
            } 
            catch (Exception e) {
	            e.printStackTrace();
	            System.out.println("出错了");
            }
    }

    public static void main(String[] args) {
//        TestSingleton test = new TestSingleton();
        ReflectNewInstance();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值