运用共享技术有效地支持大量细粒度的对象
如淘宝中每个店家的网站有首页、分类、会员等
public class WebSite {
private String type = "";
public WebSite(String type) {
this.type= type;
}
public void show() {
System.out.println("网站类型: " + type);
}
}
当使用时
WebSite A = new WebSite("首页");
A.show();
WebSite B = new WebSite("首页");
B.show();
实际上不可能为每个商家都新建一个网站实例,不同网站之间只有数据不同
抽象WebSite,展示的时候传入数据加载
abstract class WebSite {
abstract void show(User user);
}
class concreteWebSite extends WebSite {
private String type = "";
public concreteWebSite(String name) {
this.type = name;
}
@Override
void show(User user) {
System.out.println("网站类型: " + type + ", 用户:" + user.getName());
}
}
class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
创建工厂维护WebSite,第一次创建时存起来,此后返回已创建的对象
class WebSiteFactory {
private Hashtable flyweights = new Hashtable<>();
public WebSite getWebSite(String key) {
if (!flyweights.contains(key)) {
flyweights.put(key, new concreteWebSite(key));
}
return flyweights.get(key);
}
public int getWebSiteCount() {
return flyweights.size();
}
}
当使用时,从工厂中取出WebSite,为其设置数据
WebSiteFactory webSiteFactory = new WebSiteFactory();
WebSite A = webSiteFactory.getWebSite("首页");
A.show(new User("A"));
WebSite B = webSiteFactory.getWebSite("首页");
B.show(new User("B"));
WebSite C = webSiteFactory.getWebSite("分类");
C.show(new User("C"));
System.out.println("网站数量: "+webSiteFactory.getWebSiteCount());
String的实现就是运用了享元模式
String s1 = new String("s");
String s2 = new String("s");
System.out.println("s1==s2: " + (s1 == s2));
System.out.println("s1.equals(s2): " + s1.equals(s2));
String s3 = "s";
String s4 = "s";
System.out.println("s3 == s4: " + (s3 == s4));
System.out.println("s3.equals(s4): " + s3.equals(s4));
打印如下,当使用new时,创建的对象地址不一样,当直接赋值时,s4的引用指向字符串"s"
s1==s2: false
s1.equals(s2): true
s3 == s4: true
s3.equals(s4): true