大话设计模式-享元模式

UML

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

/** * @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());

    }
}

运行结果

全部评论

相关推荐

11-09 14:54
已编辑
华南农业大学 产品经理
大拿老师:这个简历,连手机号码和照片都没打码,那为什么关键要素求职职位就不写呢? 从上往下看,都没看出自己到底是产品经理的简历,还是电子硬件的简历? 这是一个大问题,当然,更大的问题是实习经历的描述是不对的 不要只是去写实习流程,陈平,怎么去开会?怎么去讨论? 面试问的是你的产品功能点,是怎么设计的?也就是要写项目的亮点,有什么功能?这个功能有什么难处?怎么去解决的? 实习流程大家都一样,没什么优势,也没有提问点,没有提问,你就不得分 另外,你要明确你投的是什么职位,如果投的是产品职位,你的项目经历写的全都是跟产品无关的,那你的简历就没用 你的面试官必然是一个资深的产品经理,他不会去问那些计算机类的编程项目 所以这种四不像的简历,在校招是大忌
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务