码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-07 13:09:35      阅读:142      评论:0      收藏:0      [点我收藏+]

标签: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);
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:flyweight

原文地址:http://blog.csdn.net/qq_16687803/article/details/46786185

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!