虽然上面举例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; } }