Java笔记(设计模式:单利模式):

1.单利模式:

1)概念:

一个类的实例在内存中有且仅有一个!

2)分类:

饿汉式:永远不会出现的一种单例模式
懒汉式:可能出现安全问题的一种单例模式

3)饿汉式:

    1.概念

饿汉式:
      当类一加载,就,而且始创建了当前类对象终只有一个

    2.创建步骤:

          1)自定义类:具体类
          2)无参构造方法私有化,目的:外界不能创建对象了
          3)在当前类的成员位置:创建自己本身对象
          4)在当前类中提供一个对外的公共的静态的功能,返回值是它本身

    3.案例:

public class Student {//具体类

    //成员位置:创建当前类的实例
   // public static Student s = new Student() ; //
    private static Student s = new Student() ;
    //无参构造私有化
    private Student(){}


    //在当前类中提供一个对外的公共的静态的功能,返回值是它本身
    public static Student getInstance(){
        return s ;//静态只能访问静态
    }
}
public class SingleObjectPattern {
    public static void main(String[] args) {

       /* Student s1 = new Student() ;
        Student s2 = new Student() ;
        //多例了;对象不同
        System.out.println(s1==s2);
        System.out.println(s1.getClass()==s2.getClass());*/ //获取字节码文件对象*/

        //Student.s = null ;//没有意义:直接赋值空对象,不安全

        Student s1 = Student.getInstance();
        Student s2 = Student.getInstance();
        Student s3 = Student.getInstance() ;
        System.out.println(s1==s2) ;
        System.out.println(s2==s3) ;

4)饿汉式:

     1.概念:

懒汉式:
      可能出现安全问题的一种单例模式
                  1)懒加载 (延迟加载)  Mybatis框架:延迟加载(用户表和账户表)
                  2)可能存在一种多线程安全问题

    2.创建步骤:

1)自定义类:具体类
2)无参构造方法私有化,外界不能创建当前类对象
3)需要在成员位置,声明当前类型的变量
4)提供一个对外公共的并且静态的访问方法,返回值就是当前类本身

    3.案例:

public class Teacher  {//具体类

    private  static Teacher t ; //声明  默认值null

    //无参构造方法私有化
    private Teacher(){

    }

    //对外提供一个静态的公共访问方法,返回值是当前类本身
    //每一个用户都需要请求getInstance():每一个用户相当于线程
    //t1,t2,t3  都执行这个代码
   /* public static Teacher getInstance(){ //静态的:锁对象:类名.class
        synchronized (Teacher.class){//同步代码块
            //先判断
            //如果当前t变量为null,说明并没有创建当前类实例 (在使用的时候才创建)
            if(t == null){
                t = new Teacher() ; //创建对象
            }
            return  t ;
        }

    }*/
   //优化
    public static synchronized  Teacher getInstance(){ //静态的同步方法
        //先判断
        //如果当前t变量为null,说明并没有创建当前类实例 (在使用的时候才创建)
        if(t == null){
            t = new Teacher() ; //创建对象
        }
        return  t ;
    }

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

        //测试
        Teacher t1 = Teacher.getInstance() ;
        Teacher t2 = Teacher.getInstance() ;
        System.out.println(t1== t2) ;

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值