Flyweight的定义:
避免大量拥有相同内容的小类开销(如消耗内存),使大家共享一个类叫元类。
为什么使用:
面向对角的原则是一切都是对象,但如果对象数非常庞大,如果字处理软件,对数据表的DAO操作。等耗内存的操作,我们就要求同存异,找出共同体,设计为一个元类。另外一些特性取决于context是不可共享的。
使用例子如:
package com.pdw.pattern;
import java.util.*;
class CD{
private String title;
private int year;
private Artist artist;
public Artist getArtist() {
return artist;
}
public void setArtist(Artist artist) {
this.artist = artist;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
class Artist{
private String name;
public String getName(){
return this.name;
}
public Artist(String n){
this.name=n;
}
}
class ArtistFactory{
Hashtable flyweights=new Hashtable();
Artist getArtist(String key){
Artist result;
result=(Artist)flyweights.get(key);
if(result==null){
result=new Artist(key);
flyweights.put(key,result);
}
return result;
}
}
public class FlyweightImpl {
/**
* @param args
*/
public static void main(String[] args) {
CD cd=new CD();
ArtistFactory af=new ArtistFactory();
cd.setArtist(new Artist("李"));
cd.setTitle("测试");
cd.setYear(1998);
Artist va=af.getArtist("裴");
System.out.println(va.getName());
af.getArtist("李");
System.out.println(af.flyweights.size());
}
}
posted on 2006-07-09 22:50
有猫相伴的日子 阅读(331)
评论(0) 编辑 收藏 所属分类:
Patterns