单列模式

单列模式是最后常见的设计模式之一,主要用途是保证在整个程序中,指定的对象只创建一次,用到的始终都是同一个对象;

demo类

package com.huahaha;

public class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

1.饿汉式(类加载时就创建),整个程序在运行时,有可能,没用到这个对象,这就造成了系统资源的浪费

package com.huahaha;

public class OnlyClass {
    //类加载的时候就创建对象
    private static Student student = new Student();

    //私有化构造方法(使其不能创建对象)
    private OnlyClass(){}

    //房间方法返回对象
    public Student getStudnet(){
        return student;
    }
}

2.懒汉式(需要的时候创建) 为了保证多线程的安全性,需要加synchronized 进行同步锁,但这样就影响程序的性能,所以不推荐

package com.huahaha;

public class OnlyClass {
    //类加载的时候先不创建对象
    private static Student student ;

    //私有化构造方法(使其不能创建对象)
    private OnlyClass(){}

    //房间方法返回对象
    public static Student getStudnet(){
        if (student==null) {
            synchronized (OnlyClass.class){
            //静态方法,同步对象为该类的字节码对象,如果非静态,则为this
                if(student==null){
                //调用该方法时,再创建对象,返回
                    student = new Student();
                }
            }
        }
        return student;
    }
}

3.静态内部类实现单列(内部类:在类加载时不会创建对象,在第一次引用的时候才会创建,也保证了线程的安全性)

package com.huahaha;

public class OnlyClass {
    //私有化构造方法(使其不能创建对象)
    private OnlyClass(){}

    //静态内部类
    private static class Intance{
        private static Student student = new Student();
    }

    public Student getStudent(){
        return Intance.student;
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值