单例模式

一、单例模式:

  1)使用:一个类在内存只存在一个对象;

  2)三个条件:

    (1)构造私有化;

    (2)提供一个唯一的静态的私有的当前类成员对象;

    (3)提供一个静态的公有的访问方法;

二、使用示例:

(1)饿汉式

public class User {
    private User(){}
    private static User user = new User();
    public static User getUser(){
        return user;
    }
}

(2)懒汉

public class User {
    private User(){}
    private static User user;
    public synchronized static User getUser(){
        if (user == null){
            user = new User();
        }
        return user;
    }
}

升级:

public class User {
    private User() {}
    private static User user;
    public static User getUser() {
        if (user == null) {
            synchronized (User.class) {
                if (user == null) {
                    user = new User();
                }
            }
        }
        return user;
    }
}

 

 

posted @ 2019-08-01 23:43  开拖拉机的拉风少年  阅读(106)  评论(0编辑  收藏  举报