JAVA设计模式 单例模式

JAVA设计模式

笔记 单例模式

danlimoshi

在这里插入图片描述

  • 饿汉式 空间换时间加载模式
    SingletonOne.java
package com.imooc.singleton;

/**
 * 饿汉式: 创建对象实例直接初始化
 */
public class SingletonOne {
    //1,创建类中的私有构造,类外不能实例,只能通过类名调用
    private SingletonOne(){

    }

    //2, 创建该类中的静态私有实例
    private static SingletonOne instance = new SingletonOne();

    //3,创建共有静态方法,返回静态实例对象
    public static SingletonOne getInstance(){
        return instance;
    }
}

test.java

package com.imooc.test;

import com.imooc.singleton.SingletonOne;

public class test {
    public static void main(String[] args){
        SingletonOne one = SingletonOne.getInstance();
        SingletonOne two = SingletonOne.getInstance();
        System.out.println(one == two);
        System.out.println(one);
        System.out.println(two);
    }
}

结果

  • 懒汉式
    SingletonTwo.java
package com.imooc.singleton;

/**
 * 懒汉式: 类内实例对象创建时,并不会直接初始化,只有调用get方法时初始化。
 */
public class SingletonTwo {
    //1,创建私有构造方法
    private SingletonTwo(){

    }
    //2,创建静态实例对象
    private static SingletonTwo instance = null;

    //3,创建开发的静态方法提供实例对象
    public static SingletonTwo getInstance(){
        if (instance==null)
            instance = new SingletonTwo();
        return instance;
    }
}

test.java

package com.imooc.test;

import com.imooc.singleton.SingletonOne;
import com.imooc.singleton.SingletonTwo;

public class test {
    public static void main(String[] args){
        SingletonOne one = SingletonOne.getInstance();
        SingletonOne two = SingletonOne.getInstance();
        System.out.println(one == two);
        System.out.println(one);
        System.out.println(two);

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

        SingletonTwo one2 = SingletonTwo.getInstance();
        SingletonTwo two2 = SingletonTwo.getInstance();
        System.out.println(one2);
        System.out.println(two2);
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

注意
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值