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

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

饿汉式:

在使用之前就先 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;

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章