Java单例模式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java单例模式

Demo龙   2022-06-18 我要评论

1.单例

1.所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。

2.单例设计模式有两种方式:

1)饿汉式。

2)懒汉式

2.单例设计模式的应用实例

1.步骤

1)构造器私有化=》防止用户直接new出一个对象

2)类的内部创建对象

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

4)代码实现

2.单例模式-饿汉式

package com.demo.single_;

public class test01 {
    public static void main(String[] args) {
        //    girlfriend g01=new girlfriend("小红");
//    girlfriend g01=new girlfriend("下华");
        girlfriend t01=girlfriend.getInstance();
        System.out.println(t01);
        girlfriend t02=girlfriend.getInstance();
        System.out.println(t02);
        if(t01==t02)
            System.out.println("true");
    }
}
//有一个类,girlfriend
//只能有一个girlfriend
class girlfriend{
    private String name;
    //1.构造器私有化
    private girlfriend(String name){
        this.name=name;
    }
//    2.在类的内部直接创建
    private static girlfriend g=new girlfriend("小红");
    //提供一个公共的static方法,返回对象g
    public static girlfriend getInstance(){
        return g;
    }
    @Override
    public String toString() {
        return "girlfriend{" +
                "name='" + name + '\'' +
                '}';
    }
}

测试结果

注:单例设计模式中的对象通常是重量级的对象,饿汉式可能造成创建了对象,但是没有使用

3.单例模式-懒汉式

package com.demo.single_;
//演示懒汉式的单例模式
public class test02 {
    public static void main(String[] args) {
        //new cat("大飞");错误。
        System.out.println(cat.n);
        cat instence=cat.getInstance();
        System.out.println(instence);
        //再次执行,依然是大黄,cat.getInstance()中的if语句不再执行
        cat instence2=cat.getInstance();
        System.out.println(instence2);
    }
}
//希望在程序运行过程中,,只能创建一个cat对象
//使用单例模式
class cat{
    private String name;
    //1,将构造器私有化
    private cat(String name) {
        System.out.println("构造器被调用");
        this.name = name;
    }
    //2,定义一个静态属性对象
    private static cat c1;
    public static int n=999;
    //3,提供一个public的static方法,可以返回一个cat对象
    public static cat getInstance(){
        if(c1==null){
            c1=new cat("大黄");
        }
        return c1;
    }
    @Override
    public String toString() {
        return "cat{" +
                "name='" + name + '\'' +
                '}';
    }
}
//4,总结:只有当用户使用getInstence()时,才返回cat c1对象,
// 当后面再次调用时,会返回上次创建的对象

测试结果

3.饿汉式与懒汉式的区别

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

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

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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们