flyweight定义:
避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类).
为什么使用?
面向对象语言的原则就是一切都是对象,但是如果真正使用起来,有时对象数可能显得很庞大,比如,字处理软件,如果以每个文字都作为一个对象,几千个字,对象数就是几千,无疑耗费内存,那么我们还是要"求同存异",找出这些对象群的共同点,设计一个元类,封装可以被共享的类,另外,还有一些特性是取决于应用(context),是不可共享的,这也flyweight中两个重要概念内部状态intrinsic和外部状态extrinsic之分.
说白点,就是先捏一个的原始模型,然后随着不同场合和环境,再产生各具特征的具体模型,很显然,在这里需要产生不同的新对象,所以flyweight模式中常出现factory模式.flyweight的内部状态是用来共享的,flyweight factory负责维护一个flyweight pool(模式池)来存放内部状态的对象.
flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度.应用场合很多:比如你要从一个数据库中读取一系列字符串,这些字符串中有许多是重复的,那么我们可以将这些字符串储存在flyweight池(pool)中.
如何使用?
我们先从flyweight抽象接口开始:
程序代码:
| public interface flyweight { public void operation( extrinsicstate state ); } //用于本模式的抽象数据类型(自行设计) public interface extrinsicstate { } |
| public class concreteflyweight implements flyweight { private intrinsicstate state; public void operation( extrinsicstate state ) { //具体操作 } } 当然,并不是所有的flyweight具体实现子类都需要被共享的,所以还有另外一种不共享的concreteflyweight: |
| public class unsharedconcreteflyweight implements flyweight { public void operation( extrinsicstate state ) { } } |
| public class flyweightfactory { //flyweight pool private hashtable flyweights = new hashtable(); public flyweight getflyweight( object key ) { flyweight flyweight = (flyweight) flyweights.get(key); if( flyweight == null ) { //产生新的concreteflyweight flyweight = new concreteflyweight(); flyweights.put( key, flyweight ); } return flyweight; } } |
| flyweightfactory factory = new flyweightfactory(); flyweight fly1 = factory.getflyweight( "fred" ); flyweight fly2 = factory.getflyweight( "wilma" ); ...... |
| <?xml version="1.0"?> <collection> <cd> <title>another green world</title> <year>1978</year> <artist>eno, brian</artist> </cd> <cd> <title>greatest hits</title> <year>1950</year> <artist>holiday, billie</artist> </cd> <cd> <title>taking tiger mountain (by strategy)</title> <year>1977</year> <artist>eno, brian</artist> </cd> ....... </collection> |
| public class cd { private string title; private int year; private artist artist; public string gettitle() { return title; } public int getyear() { return year; } public artist getartist() { return artist; } public void settitle(string t){ title = t;} public void setyear(int y){year = y;} public void setartist(artist a){artist = a;} } |
| public class artist { //内部状态 private string name; // note that artist is immutable. string getname(){return name;} artist(string n){ name = n; } } |
| public class artistfactory { hashtable pool = new hashtable(); artist getartist(string key){ artist result; result = (artist)pool.get(key); ////产生新的artist if(result == null) { result = new artist(key); pool.put(key,result); } return result; } } |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器