Java共享模式/享元模式(Flyweight模式)(2)

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/25a466a3b8fba5370755efae689bd40d.html