`

享元模式 flyweight

 
阅读更多

个人理解:当系统内部需要使用大量的细粒度对象时,内存中每种类型的细粒度对象只存在一个实例,通过给这个实例包装一下,增加一些特殊的属性,生成一个实现类,然后再有client类来维护实现类的特殊属性,这个模式的好处就是不必

在内存中一次次的创建、销毁享元对象,而通过工厂来获取内存中已经存在的对象。文章最后有个例子,看了就明白了。

 

 

Flyweight在拳击比赛中指最轻量级,即"蝇量级",有些作者翻译为"羽量级"。这里使用"享元模式"更能反映模式的用意。

享元模式以共享的方式高效地支持大量的细粒度对象。享元对象能做到共享的关键是区分内蕴状态(Internal State)和外蕴状态(External State)。内蕴状态是存储在享元对象内部并且不会随环境改变而改变。因此内蕴状态并可以共享。

外蕴状态是随环境改变而改变的、不可以共享的状态。享元对象的外蕴状态必须由客户端保存,并在享元对象被创建之后,在需要使用的时候再传入到享元对象内部。外蕴状态与内蕴状态是相互独立的。

享元模式的应用

享元模式在编辑器系统中大量使用。一个文本编辑器往往会提供很多种字体,而通常的做法就是将每一个字母做成一个享元对象。享元对象的内蕴状态就是这 个字母,而字母在文本中的位置和字模风格等其他信息则是外蕴状态。比如,字母a可能出现在文本的很多地方,虽然这些字母a的位置和字模风格不同,但是所有 这些地方使用的都是同一个字母对象。这样一来,字母对象就可以在整个系统中共享。


二、 单纯享元模式的结构

在单纯享元模式中,所有的享元对象都是可以共享的。单纯享元模式所涉及的角色如下:

抽象享元(Flyweight)角色:此角色是所有的具体享元类的超类,为这些类规定出需要实现的公共接口。那些需要外蕴状态(External State)的操作可以通过调用商业方法以参数形式传入。

具体享元(ConcreteFlyweight)角色:实现抽象享元角色所规定的接口。如果有内蕴状态的话,必须负责为内蕴状态提供存储空间。享元对象的内蕴状态必须与对象所处的周围环境无关,从而使得享元对象可以在系统内共享的。

享元工厂(FlyweightFactory)角色:本角色负责创建和管理享元角色。 本角色必须保证享元对象可以被系统适当地共享。当一个客户端对象调用一个享元对象的时候,享元工厂角色会检查系统中是否已经有一个复合要求的享元对象。如 果已经有了,享元工厂角色就应当提供这个已有的享元对象;如果系统中没有一个适当的享元对象的话,享元工厂角色就应当创建一个合适的享元对象。

客户端(Client)角色:本角色需要维护一个对所有享元对象的引用。本角色需要自行存储所有享元对象的外蕴状态。

 

这个战争游戏例子实例化5个士兵client(2种类型:海军,陆军,有共同的方法:移动),每个client维护自己坐标属性,而这些属性又是士兵的外部属性,尽管产生了5个士兵,但是只使用了一个享元soilder对象。

 

 

士兵interface:

 

package flyweight;

public interface Soldier {
	/**
	 * Move Soldier From Old Location to New Location 
	 * Note that soldier location is extrinsic 
	 *    to the SoldierFlyweight Implementation
	 * @param previousLocationX
	 * @param previousLocationY
	 * @param newLocationX
	 * @param newLocationY
	 */
	public void moveSoldier(int previousLocationX,
			int previousLocationY , int newLocationX ,int newLocationY);
}

 

 

士兵实现类:

package flyweight;

public class SoldireImpl implements Soldier {
	/**
	 * Intrinsic State maintained by flyweight implementation
	 * Solider Shape ( graphical represetation)
	 * how to display the soldier is up to the flyweight implementation
	 */
	private Object soldierGraphicalRepresentation;

	//Intrinsic State
	private String type;
	
	public SoldireImpl(String type) {
		super();
		this.type = type;
	}

	/**
	 * Note that this method accepts soldier location 
	 * Soldier Location is Extrinsic and no reference to previous location 
	 * or new location is maintained inside the flyweight implementation
	 */
	public void moveSoldier(int previousLocationX, int previousLocationY,
			int newLocationX, int newLocationY) {

		// delete soldier representation from previous location 
		// then render soldier representation in new location 	
	}


}

 

 士兵工厂:

package flyweight;

import java.util.HashMap;

public class SoldierFactory {
	/**
	 * Pool for one soldier only 
	 * if there are more soldier types 
	 * this can be an array or list or better a HashMap
	 * 
	 */
	private static HashMap<String, Soldier> soldiers = new HashMap<String, Soldier>();
	
	/**
	 * getFlyweight
	 * @return
	 */
	public Soldier getSoldier(String type){

		// this is a singleton 
		// if there is no soldier 
		if(soldiers.containsKey(type)){
			return soldiers.get(type);
		}else{
			soldiers.put(type, new SoldireImpl(type));
			return soldiers.get(type);
		}
		
	}

}

 

士兵客户类(client)

package flyweight;

public class SoldierClient {
	/**
	 * Reference to the flyweight
	 */
	private Soldier soldier ;
	
	public SoldierClient(String soldierType) {
		super();
		this.soldier = new SoldierFactory().getSoldier(soldierType);
	}


	/**
	 * this state is maintained by the client 
	 */
	private int currentLocationX = 0;
	
	/**
	 * this state is maintained by the client 
	 */
	private int currentLocationY=0;
	
	
	public void moveSoldier(int newLocationX, int newLocationY){

		// here the actual rendering is handled by the flyweight object 
		soldier.moveSoldier(currentLocationX, 
			currentLocationY, newLocationX, newLocationY);
		
		// this object is responsible for maintaining the state
		// that is extrinsic to the flyweight
		currentLocationX = newLocationX;
		
		currentLocationY = newLocationY;
	}

}

 

 

战争游戏:

package flyweight;

public class WarGame {
	public static void main(String[] args) {
		// start war 
		
		// draw war terrain 
		
		// create 5 soldiers:
		SoldierClient warSoldiers [] ={
				new SoldierClient("navy"),
				new SoldierClient("navy"),
				new SoldierClient("navy"),
				new SoldierClient("army"),
				new SoldierClient("army")
		};
		
		// move each soldier to his location 
		// take user input to move each soldier 
		warSoldiers[0].moveSoldier(17, 2112);
		
		// 	take user input to move each soldier 
		warSoldiers[1].moveSoldier(137, 112);
		
		// note that there is only one SoldierImp ( flyweight Imp)
		// for all the 5 soldiers 
		// Soldier Client size is small due to the small state it maintains
		// SoliderImp size might be large or might be small 
		// however we saved memory costs of creating 5 Soldier representations
	}

}

  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics