栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

单例设计模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单例设计模式

单例模式应用实例:

饿汉式步骤如下:(对象还没使用就已经创建了对象)

1)构造器私有化    (防止直接new)

2)类的内部创建对象

3)向外部暴露一个静态的公共方法

4)代码实现

饿汉式单例实例:

public class SingleTon01 {
    public static void main(String[] args) {
//        GirFriend girFriend1 = new GirFriend("小红");
//        GirFriend girFriend2 = new GirFriend("小花");
        GirFriend instance = GirFriend.getInstance();
        System.out.println(instance.toString());
    }
}

//一个GirFriend类
class GirFriend {

    private String name;

    private static GirFriend gf = new GirFriend("小红");

    //如何保障我们只能创建一个GirFriend对象
    //步骤【单例模式-饿汉式】:
    //1.将构造器私有化
    //2.在类的内部直接创建一个私有的对象
    //3.再提供一个公共的 static 方法,返回 gf对象
    private GirFriend(String name) {
        this.name = name;
    }

    public static GirFriend getInstance() {
        return gf;
    }

    @Override
    public String toString() {
        return name;
    }
}

懒汉式单例实例:

public class SingleTon02 {
    public static void main(String[] args) {

        Cat instance1 = Cat.getInstance();
        System.out.println(instance1);

        System.out.println("-----------------------------");

        Cat instance2 = Cat.getInstance();
        System.out.println(instance2);

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

}


//创建一个Cat对象
class Cat{
    private String name;
    private static Cat cat;

    //步骤【单例模式-懒汉式】:
    //1.构造器私有化
    //2.定义一个 static 静态属性对象
    //3.提供一个public的 static方法 ,可以返回一个Cat对象
    //4.懒汉式,只当用户调用getInstance()时,才会返回对象,后面再次调用时,会返回上次创建的 cat 对象,从而保证了单例
    private Cat(String name){
        this.name = name;
        System.out.println("构造器被调用...");
    }

    public static Cat getInstance(){

        if (cat == null){//如果没有创建cat对象
            cat = new Cat("小可爱");
        }
        return cat;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + ''' +
                '}';
    }
}



运行结果:

构造器被调用...
Cat{name='小可爱'}
-----------------------------
Cat{name='小可爱'}
true

进程已结束,退出代码0
饿汉式VS懒汉式:

1.二者主要的区别在于创建对象的时机不同:饿汉式是在类加载就创建了对象实例,而懒汉式是在使用时才创建。

2.饿汉式不存在线程安全问题,懒汉式存在线程安全问题。

3.饿汉式存在浪费资源的可能。应为如果程序员一个对象实例都没有使用,那么饿汉式创建的对象就浪费了,懒汉式是使用时才创建,就不存在这个问题。

4.在JavaSE标准类中,java.lang.Runtime就是经典的单例模式。

//观看老韩视频总结

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/858057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号