Skip to content

Latest commit

 

History

History
executable file
·
106 lines (84 loc) · 2.43 KB

File metadata and controls

executable file
·
106 lines (84 loc) · 2.43 KB

设计模式

常见的设计模式

工厂模式、策略模式、适配器模式、模版模式、装饰模式、代理模式、单例模式等

单例模式代码

//1. 饿汉模式
public class InstanceFactory {
    
    // 利用静态变量来记录唯一实例,直接初始化静态变量
    private static final Single instance = new Single();
    
    //构造器私有化
    private InstanceFactory() {}
    
    public static Single getInstance() {
        return this.instance;
    }
}

//2. 懒汉模式,双重校验锁
public class InstanceFactory {
    
    //volatile防止重排序
    private volatile static Single instance;
    
    private static final Object object = new Object();
    
    //构造器私有化
    private InstanceFactory(){}
    
    public static Single getInstance() {
        if(instance == null) {
            synchronized(object) {
                if (instance == null) {
                    instance = new Single();
                }
            }
        }
        return instance;
    }
}

//3. 静态内部类
public class InstanceFactory {
    private static class InnerClass {
        private static final Single INSTANCE = new Single();
    }
    
    private InstanceFacotry() {}
    
    public static final Single getInstance() {
        return InnerClass.INSTANCE;
    } 
}

//以上方法如果在考虑反射的情况下,依然是能够创建不同的实例的

//4. 枚举实现,最佳单例实现
public enum InstanceFactory {
    INSTANCE;
    public InstanceFactory getInstance() {
        return INSTANCE;
    }
}
//枚举实现单例demo
public class User {
    //私有化构造函数
    private User(){ }
 
    //定义一个静态枚举类
    static enum SingletonEnum{
        //创建一个枚举对象,该对象天生为单例
        INSTANCE;
        private User user;
        //私有化枚举的构造函数
        private SingletonEnum(){
            user=new User();
        }
        public User getInstnce(){
            return user;
        }
    }
 
    //对外暴露一个获取User对象的静态方法
    public static User getInstance(){
        return SingletonEnum.INSTANCE.getInstnce();
    }
}

public class Test {
    public static void main(String [] args){
        System.out.println(User.getInstance());
        System.out.println(User.getInstance());
        System.out.println(User.getInstance()==User.getInstance());
    }
}
//结果为true