设计模式面试题

单例模式

饿汉式

在类初始化时直接创建实例对象,不管你是否需要这个对象都会创建

普通写法

  1. 构造器私有化
  2. 自行创建,并且用静态变量保存
  3. 向外提供这个实例
  4. 强调这是一个单例,我们可以用final修饰
public class Singleton1{
	public static final Singleton1 INSTANCE = new Singleton1();
	private Singleton1(){

	}
}

枚举enum

  1. 枚举类,标识该类型的对象是有限的几个
  2. 我们可以限定为一个,就成了单例
public enum Singleton2{
	INSTANCE
}

静态代码块

public class Singleton {
    private Singleton(String info) {
        this.info = info;
    }

    private String info;
    public static Singleton INSTANCE = null;

    static {
        try {
            Properties pro = new Properties();
            pro.load(Singleton.class.getClassLoader().getResourceAsStream("xq.properties"));
            INSTANCE = new Singleton(pro.getProperty("info"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

懒汉式

延迟创建这个实例对象

普通写法(线程不安全)

  1. 构造器私有化
  2. 用一个静态变量保存这个唯一的实例
  3. 提供一个静态方法,获取这个实例对象
public class Singleton1 {
    private static Singleton1 instance;

    private Singleton1() {

    }
    public static  Singleton1 getInstance(){
        if (instance == null){
            instance = new Singleton1();
        }
        return instance;
    }
}

考虑线程安全性和效率

public class Singleton1 {
    private static Singleton1 instance;

    private Singleton1() {

    }

    public static Singleton1 getInstance() {
        //性能
        if (instance == null) {
            synchronized (Singleton1.class) {
                try {
                    if (instance == null) {
                        Thread.sleep(100);
                        instance = new Singleton1();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        return instance;
    }
}

内部类

在内部类被加载和初始化时,才创建INSTANCE实例对象
静态内部类不会自动随着外部类的加载和初始化而初始化,它是要单独去加载和初始化的
因为是在内部类初始化时加载和初始化,因此是线程安全的

public class Singleton2 {

    private Singleton2(){

    }

    private static class Inner{
        private static final Singleton2 instance = new Singleton2();
    }
    
    public static Singleton2 getInstance(){
        return Inner.instance;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值