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

设计模式之享元模式

时间:2015-07-18 14:02:47      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

享元模式

运用共享技术有效的支持大量细粒度的对象。

FlyWeight

package com.hml.flyweight;

public abstract class FlyWeight {
    public abstract void operation(int p);
}

ConcreateFlyWeight

package com.hml.flyweight;

public class ConcreateFlyWeight extends FlyWeight {

    @Override
    public void operation(int p) {
        System.out.println("具体的类:" + p);
    }

}

FlyWeigthFactory

package com.hml.flyweight;

import java.util.HashMap;
import java.util.Map;

public class FlyWeigthFactory {
    private static Map<String, FlyWeight> flyweigths = new HashMap<String, FlyWeight>();

    static {
        flyweigths.put("x", new ConcreateFlyWeight());
        flyweigths.put("y", new ConcreateFlyWeight());
        flyweigths.put("z", new ConcreateFlyWeight());
    }

    public static FlyWeight getFlyWeight(String key) {
        return flyweigths.get(key);
    }
}

Test

package com.hml.flyweight;

public class Test {
    public static void main(String[] args) {
        
        FlyWeigthFactory factory = new FlyWeigthFactory();
        FlyWeight f = factory.getFlyWeight("x");
        f.operation(22);
        f = factory.getFlyWeight("y");
        f.operation(22);
    }
}

类图
技术分享

 

享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类的实例来表示数据。如果能发现这些实例除了几个参数外基本上相同,有时就能够大幅度的减少需要实例化的类的数量。如果能把参数移到类的外面,在方法调用时传递进来,就可以可以通过共享减少单个实例的数据量。

设计模式之享元模式

标签:

原文地址:http://www.cnblogs.com/heml/p/4656709.html

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