设计模式——共享模式

2019-05-18 07:08:01来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

共享模式_共享对象,避免内存浪费(避免重复创建相同的对象)

/**
 * 需要被共享的对象
 * @author maikec
 * @date 2019/5/17
 */
public class Flyweight {
    private String name;
    public Flyweight(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

/**
 * @author maikec
 * @date 2019/5/17
 */
public class FlyweightFactory {
    private static FlyweightFactory ourInstance = new FlyweightFactory();
    @Getter
    private final Map<String, Flyweight> pool = Collections.synchronizedMap( new HashMap<>(  ) );

    public static FlyweightFactory getInstance() {
        return ourInstance;
    }

    private FlyweightFactory() {
    }

    public Flyweight getFlyweight(String flyweightName){
        if (pool.containsKey( flyweightName )){
            return pool.get( flyweightName );
        }else{
            Flyweight flyweight = new Flyweight( flyweightName );
            pool.putIfAbsent( flyweightName,flyweight );
            return flyweight;
        }
    }
}

/**
 * @author maikec
 * @date 2019/5/17
 */
public class FlyweightDemo {
    public static void main(String[] args) {
        FlyweightFactory instance = FlyweightFactory.getInstance();
        System.out.println( instance.getFlyweight( "Flyweight" ).getName() );
        System.out.println( instance.getFlyweight( "Flyweight" ).getName() );

        System.out.println( instance.getFlyweight( "Flyweight1" ).getName() );

        // 需要配置虚拟机 -ea 参数启用assert功能
        assert 2==instance.getPool().size();
    }
}

附录

github.com/maikec/patt… 个人GitHub设计模式案例

声明

引用该文档请注明出处

 


原文链接:https://www.cnblogs.com/imaikce/p/10882244.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【Java】NIO中Channel的注册源码分析

下一篇:Java面向对象之继承