1 享元模式:通过共享技术有效的支持大量细粒度的对象。
代码:
public abstract class WebSite {
public abstract void user(User user);
}
public class ConcreteWebSite extends WebSite {
private String name;
public ConcreteWebSite(String name) {
this.name = name;
}
@Override
public void user(User user) {
// TODO Auto-generated method stub
System.out.println("name:"+name+" "+user.getName());
}
}
工厂:
public class WebFactory {
private Hashtable<String, ConcreteWebSite> webSite = new Hashtable<String, ConcreteWebSite>();
public WebFactory() {
webSite.put("A", new ConcreteWebSite("A"));
webSite.put("B", new ConcreteWebSite("B"));
webSite.put("C", new ConcreteWebSite("C"));
}
/**
* 获取网站对象
* @param name
* @return
*/
public WebSite getWebSite(String name) {
if (!webSite.containsKey(name)) {
webSite.put(name, new ConcreteWebSite(name));
}
return webSite.get(name);
}
}
测试:
public class TextMain {
public static void main(String[] args){
WebFactory webFactory=new WebFactory();
WebSite webSite01=webFactory.getWebSite("A");
webSite01.user(new User("01号"));
WebSite webSite02=webFactory.getWebSite("B");
webSite02.user(new User("01号"));
}
}
对于享元模式,目前对其的理解只停留在表面,未完待续。。。