---
title: "flyweight模式"
author: "Jameslyy"
date: "2007-08-22T14:51:32Z"
tags: []
slug: "flyweight"
draft: false
lastmod: "2007-08-22T14:51:32Z"
id: 115277
url: "https://jamesblog.iteye.com/blog/115277"
---

flyweight模式，即享元模式，属于结构模式的一种，通过共享相同的数据对象，避免产生重复，从而提高内存的使用效率和程序的运行速度。

      Flyweight有两个重要的概念，内部状态intrinsic和外部状态extrinsic。Flyweight的内部状态用来共享数据对象。

      Flyweight模式中常出现在Factory模式中。Flyweight factory负责维护一个Flyweight pool来存放内部状态的对象。

      **代码例子：**

 

1. public interface Flyweight {
2. public void operation( ExtrinsicState state );
3. }
4. //用于本模式的抽象数据类型(自行设计)
5. public interface ExtrinsicState {
6. }

       下面是接口的具体实现(ConcreteFlyweight) ，并为内部状态增加内存空间，ConcreteFlyweight必须是可共享的，它保存的任何状态都必须是内部(intrinsic)，也就是说，ConcreteFlyweight必须和它的应用环境场合无关。

 

1. public class ConcreteFlyweight implements Flyweight {
2. private IntrinsicState state;
3. public void operation( ExtrinsicState state ) {
4. //具体操作
5. }
6. }

     当然，并不是所有的Flyweight具体实现子类都需要被共享的,所以还有另外一种不共享的ConcreteFlyweight：

 

1. public class UnsharedConcreteFlyweight implements Flyweight {
2. public void operation( ExtrinsicState state ) {
3. }
4. }

      Flyweight factory负责维护一个Flyweight池(存放内部状态),，当客户端请求一个共享Flyweight时，这个factory首先搜索池中是否已经存在请求的对象，如果有，factory只是简单返回这个对象，否则，创建一个新的对象加入到池中，再返回这个对象。

 

01. public class FlyweightFactory {
02. //Flyweight pool
03. private Hashtable flyweights = new Hashtable();
04. public Flyweight getFlyweight( Object key ) {
05. Flyweight flyweight = (Flyweight) flyweights.get(key);
06. if( flyweight == null ) {
07. //产生新的ConcreteFlyweight
08. flyweight = new ConcreteFlyweight();
09. flyweights.put( key, flyweight );
10. }
11. return flyweight;
12. }
13. }

至此，Flyweight模式的基本框架已经就绪，我们看看如何调用：

FlyweightFactory factory = new FlyweightFactory();  
Flyweight fly1 = factory.getFlyweight( "Fred" );  
Flyweight fly2 = factory.getFlyweight( "Wilma" );  
......

从调用上看，好象是个纯粹的Factory使用，但奥妙就在于Factory的内部设计上。

（参考自 板桥里人 http://www.jdon.com 2002/05/02 ）