当前页面: 开发资料首页 → Java 专题 → java设计模式之Flyweight
摘要: java设计模式之Flyweight
public interface Flyweight
{
public void operation( ExtrinsicState state );
}
public class ConcreteFlyweight implements Flyweight {
private IntrinsicState state;
public void operation( ExtrinsicState state )
{
//具体操作
}
}
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;
}
} <?xml version="1.0"?>Another Green World 1978 Eno, Brian Greatest Hits 1950 Holiday, Billie Taking Tiger Mountain (by strategy) 1977 Eno, Brian
.......
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;
}
}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;
}
}