zoukankan      html  css  js  c++  java
  • 设计模式——共享模式

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

    /**
     * 需要被共享的对象
     * @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设计模式案例

    声明

    引用该文档请注明出处

  • 相关阅读:
    pytorch_基于cifar创建自己的数据集并训练
    Pytorch_3.8_多层感知机
    Pytorch_3.6_ SOFTMAX回归的从零实现
    Linux(debian)下的Python程序守护进程
    Ubuntu16.04安装OpenCV3.4.3
    Beaglebone black 安装docker
    电脑与虚拟机ping
    Beaglebone升级Python3.7过程
    多图上传预览
    放大镜代码
  • 原文地址:https://www.cnblogs.com/imaikce/p/10882244.html
Copyright © 2011-2022 走看看