大话设计模式-享元模式

UML

大话设计模式-享元模式_第1张图片

所有具体享元类的超类或接口

/**
 * @ClassName: FlyWeight
 * @Author: Leo
 * @Description: 所有具体享元类的超类或接口
 * @Date: 2019/5/28 9:18
 */
public abstract class FlyWeight {
    public abstract void operation(int extrinsicstate);
}

具体的FlyWeight

/**
 * @ClassName: ConcreteFlyWeight
 * @Author: Leo
 * @Description: 具体的FlyWeight
 * @Date: 2019/5/28 9:21
 */
public class ConcreteFlyWeight extends FlyWeight {
    @Override
    public void operation(int extrinsicstate) {
        System.out.println("具体的FlyWeight--->" + extrinsicstate);
    }
}

不共享的具体的FlyWeight

/**
 * @ClassName: UnsharedFlyWeight
 * @Author: Leo
 * @Description: 不共享的具体的FlyWeight
 * @Date: 2019/5/28 9:22
 */
public class UnsharedFlyWeight extends FlyWeight {
    @Override
    public void operation(int extrinsicstate) {
        System.out.println("不共享的具体的FlyWeight--->" + extrinsicstate);
    }
}

享元工厂 创建并管理FlyWeight对象

import java.util.Hashtable;

/**
 * @ClassName: FlyWeightFactory
 * @Author: Leo
 * @Description: 享元工厂 创建并管理FlyWeight对象
 * @Date: 2019/5/28 9:23
 */
public class FlyWeightFactory {
    private Hashtable<String, FlyWeight> hashtable = new Hashtable<>();

    public FlyWeight getFlyWeight(String key) {
        if (hashtable.containsKey(key)) {
            return hashtable.get(key);
        } else {
            ConcreteFlyWeight concreteFlyWeight = new ConcreteFlyWeight();
            hashtable.put(key, concreteFlyWeight);
            return concreteFlyWeight;
        }
    }

    public int getCount() {
        return hashtable.size();
    }
}

测试类

/**
 * @ClassName: Main
 * @Author: Leo
 * @Description: 测试类
 * @Date: 2019/5/28 9:14
 */
public class Main {
    public static void main(String[] args) {
        //代码外部状态
        int extrinsicstate = 10;

        FlyWeightFactory factory = new FlyWeightFactory();
        FlyWeight f1 = factory.getFlyWeight("X");
        f1.operation(--extrinsicstate);

        FlyWeight f2 = factory.getFlyWeight("Y");
        f2.operation(--extrinsicstate);

        //以下都创建同一个对象
        FlyWeight f3 = factory.getFlyWeight("Z");
        f3.operation(--extrinsicstate);

        FlyWeight f31 = factory.getFlyWeight("Z");
        f31.operation(--extrinsicstate);

        FlyWeight f32 = factory.getFlyWeight("Z");
        f32.operation(--extrinsicstate);

        FlyWeight f33 = factory.getFlyWeight("Z");
        f33.operation(--extrinsicstate);

        FlyWeight f4 = new UnsharedFlyWeight();
        f4.operation(--extrinsicstate);

        System.out.println("享元数量--->" + factory.getCount());

    }
}

运行结果

大话设计模式-享元模式_第2张图片

你可能感兴趣的:(大话设计模式)