JAVA SE面试题(二)

单例模式

单例模式分为饿汉式和懒汉式

饿汉式:
直接创建对象,不管你是否需要这个对象

public class SingletonHungry {
    //创建静态常量对象
    public static final SingletonHungry INSTANCE = new SingletonHungry();

    //私有构造器
    private SingletonHungry() {

    }
}

使用枚举类型实现饿汉式单例模式

  • 适用:多个静态常量对象
public enum  SingletonHungry_enum {

    //静态常量对象
    INSTANCE

}

使用静态实现饿汉式单例模式

  • 作用:加载配置文件
public class SingletonHungry_static {

    //静态常量对象,供外部使用
    public static final SingletonHungry_static INSTANCE;

    private String info;

    static {

        try {
            Properties pro = new Properties();
            pro.load(SingletonHungry_static.class.getClassLoader().getResourceAsStream("singleton.properties"));
            INSTANCE = new SingletonHungry_static(pro.getProperty("info"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //私有构造器
    private SingletonHungry_static(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "SingletonHungry_static{" +
                "info='" + info + '\'' +
                '}';
    }
}

懒汉式:
什么时候用,什么时候创建实例

public class SingletonLazy {
    //使用静态变量保存实例
    private static SingletonLazy instance;

    //私有构造函数
    private SingletonLazy() {

    }

    //静态方法
    public static SingletonLazy getInstance() {
        if (instance == null) {
           instance = new SingletonLazy();
        }
        return instance;
    }
}

线程安全写法:

  • 静态内部类不会随着外部类初始化而初始化
public class SingletonLazy_static {

    private SingletonLazy_static() {

    }

    private static class Inner {
        private static final SingletonLazy_static INSTANCE = new SingletonLazy_static();
    }

    public SingletonLazy_static getInstance() {
        return Inner.INSTANCE;
    }
}

测试

  • 饿汉式
public class TestSingleton_Hungry {

    public static void main(String[] args) {

        //普通单例
        //SingletonHungry instance = SingletonHungry.INSTANCE;
        //System.out.println(instance);

        //枚举单例
        //SingletonHungry_enum instance = SingletonHungry_enum.INSTANCE;
        //System.out.println(instance);

        //静态单例
        SingletonHungry_static instance = SingletonHungry_static.INSTANCE;
        System.out.println(instance);
    }
}
  • 懒汉式
public class TestSingleton_Lazy {

    public static void main(String[] args) {
        SingletonLazy instance = SingletonLazy.getInstance();
        SingletonLazy instance2 = SingletonLazy.getInstance();

        System.out.println(instance == instance2);
        System.out.println(instance);
        System.out.println(instance2);
    }
}

你可能感兴趣的:(Java,SE面试题)