设计模式

单例模式

2017-09-23  本文已影响10人  jfson_土豆

单例模式

最常用的单例模式,经常在项目中见,梳理后发现各种各样的单例,索性梳理一下。

public class UserModel{
        private static UserModel instance; 
        private UserModel(){
        }
        
        public static UserModel getInstance(){
            if(instance == null){
                instance = new UserModel;
            }
            return instance;
        }
    }
public class UserModel{
        private static UserModel instance; 
        private UserModel(){
        }
        
        public static synchronized UserModel getInstance(){
            if(instance == null){
                instance = new UserModel;
            }
            return instance;
        }
    }
public class UserModel{
    private static UserModel instance = new UserModel;
    private UserModel(){}

    public static UserModel getInstance{
        return instance;
    }
}
public class UserModel{
    private volatile static UserModel instance;
    private UserModel(){}
    public static UserModel getInstance{
        if(instance == null){
            synchronized(UserModel.class){
                if(instance == null){
                    instance = new UserModel();
                }
            }
        }
        return instance;
    }
}
public class UserModel{
    private static class Hodler{
        private static final UserModel INSTANCE = new UserModel();
    }
    private UserModel(){}
    public static final UserModel getInstance(){
        return Hodler.INSTANCE;
    }
}

总结

上一篇 下一篇

猜你喜欢

热点阅读