首页 > 其他 > 详细

单例模式

时间:2019-08-02 02:05:36      阅读:107      评论:0      收藏:0      [点我收藏+]

一、单例模式:

  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;
    }
}

 

 

单例模式

原文:https://www.cnblogs.com/Tractors/p/11286138.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!