设计模式学习笔记九、单例模式=>饿汉模式代码

1、静态常量

package com.hao.demo.design.singel;

/**
 * @author haoxiansheng
 * @date 2020-05-13
 */
public class SingletonTest1 {
    public static void main(String[] args) {
        Singelton1 instance1 = Singelton1.getInstance();
        Singelton1 instance2 = Singelton1.getInstance();
        System.out.println("instance1 => " + instance1.hashCode());
        System.out.println("instance2 => " + instance2.hashCode());
    }
}

// 饿汉式一 静态常量

/**
 * 优缺点分析
 * 1、优点:写法简单,就是在类装载的时候完成实例化,避免了线程同步问题(基于classloder机制)
 * 2、缺点:在类装载过程的时候就完成了实例化。没有达到Lazy Loading 的效果。
 *         如果一直没有使用这个实例造成资源浪费
 */
class Singelton1 {

    /**
     * 1、构造器私有
     */
    private Singelton1() {

    }

    // 2、本类内部创建实例
    private final static Singelton1 instance = new Singelton1();

    // 3、提供一个公有的静态方法, 返回实例对象
    public static Singelton1 getInstance() {
        return instance;
    }

}

2、静态代码块

package com.hao.demo.design.singel;

/**
 * @author haoxiansheng
 * @date 2020-05-13
 */
public class SingletonTest2 {
    public static void main(String[] args) {
        Singelton2 instance1 = Singelton2.getInstance();
        Singelton2 instance2 = Singelton2.getInstance();
        System.out.println("instance1 => " + instance1.hashCode());
        System.out.println("instance2 => " + instance2.hashCode());
    }
}

// 饿汉式二 静态代码块

/**
 * 优缺点分析
 * 1、优点:写法简单,就是在类装载的时候完成实例化,避免了线程同步问题(基于classloder机制)
 * 2、缺点:在类装载过程的时候就完成了实例化。没有达到Lazy Loading 的效果。
 *         如果一直没有使用这个实例造成资源浪费
 */
class Singelton2 {

    /**
     * 1、构造器私有
     */
    private Singelton2() {

    }

    // 2、本类内部创建实例
    private  static Singelton2 instance ;

    /**
     * 3 在静态代码块中创建
     */
    static {
        instance = new Singelton2();
    }

    // 4、提供一个公有的静态方法, 返回实例对象
    public static Singelton2 getInstance() {
        return instance;
    }

}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值