学习笔记-设计模式入门基础篇-单例模式

学习笔记-设计模式入门基础篇-单例模式

饿汉式:

在使用之前就先 new 出来再说,避免了线程安全问题

public class Hungry {

    private Hungry(){}

    private final static Hungry hungry = new Hungry();

    public static Hungry getInstance(){

        System.out.println(System.currentTimeMillis()+":"+ hungry);

        return hungry;

    }

}

懒汉式

默认加载的时候不实例化,在需要使用的时候才实例化

1、线程不安全

public class LazyOne {

    private  LazyOne (){}

    private static LazyOne lazyOne = null;

    public static LazyOne getInstance(){

        if (lazyOne== null){

            lazyOne = new LazyOne();

        }

        return  lazyOne;

    }

}

2、线程安全,但是效率慢

public class LazyTwo {

    private LazyTwo(){}

    private static LazyTwo lazyTwo = null;

    public static synchronized LazyTwo getInstance(){

        if (lazyTwo== null){

            lazyTwo = new LazyTwo();

        }

        return  lazyTwo;

    }

}

3、线程安全速度快

public class LazyThree {

    public static final LazyThree getInstance(){

        return LazyHolder.LAZY;

    }

    private static class LazyHolder {

        private static final LazyThree LAZY = new LazyThree();

    }

}

 

注册登记式单利

每使用一次就往固定的容器中去注册,并且将使用过的对象进行缓存,下次去使用对象的时候直接去缓存中取,以保证每次获取的都是同一个对象

/**

 * 注册登记式单利

 */

public class RegisterMap {

    private RegisterMap (){}

    private static Map<String,Object> register = new HashMap<>();

    private static RegisterMap getInstance(String name){

        if (name==null){

            name= RegisterMap.class.getName();

        }

        if(register.get(name)==null ){

            register.put(name,new RegisterMap());

        }

        return (RegisterMap)register.get(name);

    }

}

序列化与反序列化保证单利:

重写readResolve  方法

 

public class Seriable implements Serializable {

    private final static Seriable INSTANCE = new Seriable();

    private Seriable(){}

    public static Seriable getInstance (){

        return INSTANCE;

    }

    /**

     * 实现序列化与反序列化中,对象的重复利用,由JVM 自动调用

     *

     * @return

     */

     private Object readResolve(){

        return INSTANCE;

    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值