您的位置:首页 > 编程语言 > Java开发

Java设计模式偷跑系列(21)建模和实现享受metapatterns

2015-07-26 20:35 453 查看
转载请注明出处:/article/1330854.html

享元模式(Flyweight):运用共享的技术有效地支持大量细粒度的对象。

主要目的是实现对象的共享,即共享池。当系统中对象多的时候能够降低内存的开销。在某种程度上。你能够把单例看成是享元的一种特例。

一、uml建模:



二、代码实现

/**
* 享元模式(Flyweight):运用共享的技术有效地支持大量细粒度的对象。
*
* 主要目的是实现对象的共享,即共享池,当系统中对象多的时候能够降低内存的开销。

*/
abstract class FlyWeight {
public abstract void method();
}

/**
* 创建持有key的子类
*/
class SubFlyWeight extends FlyWeight {
private String key;

public SubFlyWeight(String key) {
this.key = key;
}

@Override
public void method() {
System.out.println("this is the sub method。and the key is " + this.key);
}
}

/**
* 享元工厂:负责创建和管理享元对象
*/
class FlyweightFactory {
private Map<String, FlyWeight> map = new HashMap<String, FlyWeight>();

/**
* 获取享元对象
*/
public FlyWeight getFlyWeight(String key) {
FlyWeight flyWeight = map.get(key);
if (flyWeight == null) {
flyWeight = new SubFlyWeight(key);
map.put(key, flyWeight);
}
return flyWeight;
}

/**
* 获取享元对象数量
*/
public int getCount() {
return map.size();
}
}

/**
* client測试类
*
* @author Leo
*/
public class Test {
public static void main(String[] args) {
/**
* 创建享元工厂
*/
FlyweightFactory factory = new FlyweightFactory();
/***** 第一种情况:key同样时 ***************/
FlyWeight flyWeightA = factory.getFlyWeight("aaa");
FlyWeight flyWeightB = factory.getFlyWeight("aaa");
/**
* 透过打印结果为true能够知道: 因为key都为"aaa",所以flyWeightA和flyWeightB指向同一块内存地址
*/
System.out.println(flyWeightA == flyWeightB);
flyWeightA.method();
flyWeightB.method();
/**
* 享元对象数量:1
*/
System.out.println(factory.getCount());

/***** 另外一种情况:key不同样时 ***************/
System.out.println("\n======================================");
FlyWeight flyWeightC = factory.getFlyWeight("ccc");
/**
* 打印结果为false
*/
System.out.println(flyWeightA == flyWeightC);
flyWeightC.method();
/**
* 享元对象数量:2
*/
System.out.println(factory.getCount());
}
}
打印结果:

true

this is the sub method,and the key is aaa

this is the sub method。and the key is aaa

1

======================================

false

this is the sub method,and the key is ccc

2

三、总结

享元与单例的差别:1、与单例模式不同。享元模式是一个类能够有非常多对象(共享一组对象集合),而单例是一个类仅一个对象;2、它们的目的也不一样,享元模式是为了节约内存空间,提升程序性能(避免大量的new操作),而单例模式则主要是共享单个对象的状态及特征。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: