设计模式之Flyweight模式(笔记)

享元模式:运用共享技术有效地支持大量细粒度的对象。
适用场合:如果一个应用程序适用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用。
这里写图片描述

首先定义一个IFlyweight接口

public interface IFlyweight {

    public void operation(int extrinsicstate);
}

接着定义一个ConcreteFlyweight继承IFlyweight

public class ConcreteFlyweight implements IFlyweight{

    @Override
    public void operation(int extrinsicstate) {

        System.out.println("具体flyweight:"+extrinsicstate);

    }

}

再定义一个UnsharedConcreteFlyweight继承IFlyweight

public class UnsharedConcreteFlyweight implements IFlyweight{

    @Override
    public void operation(int extrinsicstate) {

        System.out.println("不共享的具体flyweight:"+extrinsicstate);

    }
}

然后定义一个FlyweightFactory

public class FlyweightFactory {

    Map<String, IFlyweight> flyweights=new HashMap<String,IFlyweight>();

    public FlyweightFactory(){
        flyweights.put("x", new ConcreteFlyweight());
        flyweights.put("y", new ConcreteFlyweight());
        flyweights.put("z", new ConcreteFlyweight());
    }

    public IFlyweight getFlyweight(String key){
        return flyweights.get(key);
    }
}

客户端代码

public static void main(String[] args) {
        //享元模式
        int extrinsicstate=22;
        FlyweightFactory factory=new FlyweightFactory();

        IFlyweight fx=factory.getFlyweight("x");
        fx.operation(--extrinsicstate);

        IFlyweight fy=factory.getFlyweight("y");
        fy.operation(--extrinsicstate);

        IFlyweight fz=factory.getFlyweight("z");
        fz.operation(--extrinsicstate);

        IFlyweight uf=new UnsharedConcreteFlyweight();
        uf.operation(--extrinsicstate);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值