|
| 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; } } |