Flyweight定义: 避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类).
作者:中国IT实验室 来源:中国IT实验室 2007年8月26日
关键字:
虽然上面举例CD只有3张,CD可看成是大量重复的小类,因为其中成分只有三个字段,而且有重复的(歌唱者姓名).
CD就是类似上面接口 Flyweight:
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;}
}
将"歌唱者姓名"作为可共享的ConcreteFlyweight:
public class Artist {
//内部状态
private String name;
// note that Artist is immutable.
String getName(){return name;}
Artist(String n){
name = n;
}
}
再看看Flyweight factory,专门用来制造上面的可共享的ConcreteFlyweight:Artist
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;
}
}
当你有几千张甚至更多CD时,Flyweight模式将节省更多空间,共享的flyweight越多,空间节省也就越大.