代码改变世界

设计模式之享元模式

2011-02-10 17:41  hanwesley  阅读(192)  评论(0编辑  收藏  举报

Flyweight模式中常出现Factory模式

.Flyweight的内部状态是用来共享的

Flyweight factory负责维护一个Flyweight pool(模式池)来存放内部状态的对象.

Flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度.

应用场合很多:比如你要从一个数据库中读取一系列字符串,这些字符串中有许多是重复的,那么我们可以将这些字符串储存在Flyweight池(pool)中.

package org.springframework.samples.jpetstore.dp.flyweight;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/***
 * 享元模式
 * 享元:可理解为:共享元对象,共享细粒度对象
 * 用来将实例放入一个Map中,共同的特征只产生一个实例
 * 将不可共享的状态通过参数的方式由客户端传入
 * 通过共享的方式,达到支持大量细粒度对象
 * 目的:节省空间资源,实现系统性能的改善
 * @author hanwesley
 * @version 1.0.0
 *
 */
abstract class FlyWeight {
	public abstract void operator();
}

//可以共享对象
class ConcreteFlyweight extends FlyWeight {
	public void operator() {
		System.out.println("ConcreteFlyweight");
	}
}
//不是所有的对象都需要共享。
class UnSharedConcreateFlyweigth extends FlyWeight {
	public void operator() {
		System.out.println("UnSharedConcreateFlyweigth");
	}
}

//享元模式主要要提供这个工厂类,统一获得实例对象的入口。
class FlyWeightFactory {
	private Map<String, FlyWeight> map = Collections
			.synchronizedMap(new HashMap<String, FlyWeight>());

	public FlyWeight getInstance(String key) {
		if (map.containsKey(key)) {
			return map.get(key);
		} else {
			FlyWeight fly = new ConcreteFlyweight();
			map.put(key, fly);
			return fly;
		}
	}
}

public class FlyWeightMain {
	public static void main(String[] args) {
		FlyWeightFactory factory = new FlyWeightFactory();
		FlyWeight fly1 = factory.getInstance("A");
		fly1.operator();
		FlyWeight fly2 = factory.getInstance("A");
		fly2.operator();
		System.out.println("fly1 == fly2 :" + (fly1 == fly2));
		FlyWeight fly3 = factory.getInstance("B");
		fly3.operator();
		System.out.println("fly1 == fly3 :" + (fly1 == fly3));
		FlyWeight unsharedFly = new UnSharedConcreateFlyweigth();
		unsharedFly.operator();
	}

}