设计模式——共享模式

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

设计模式——共享模式_第1张图片

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

声明

引用该文档请注明出处

 

你可能感兴趣的:(设计模式——共享模式)