享元模式:运用共享技术有效地支持大量细粒度的对象。如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时,可以考虑使用享元模式。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3afd7610f8708d4b1b8f09a63475ac60.png)
public abstract class FlyWeight {
public abstract void operation(int extrinsicState);
}
class ConcreteFlyWeight extends FlyWeight {
@Override
public void operation(int extrinsicState) {
System.out.println("具体FlyWeight:" + extrinsicState);
}
}
class UnsharedConcreteFlyWeight extends FlyWeight {
@Override
public void operation(int extrinsicState) {
System.out.println("不共享的具体FlyWeight:" + extrinsicState);
}
}
public class FlyWeightFactory {
private HashMap<String, FlyWeight> flyWeights = new HashMap<String, FlyWeight>();
public FlyWeight getFlyWeight(String key) {
if (!flyWeights.containsKey(key)) {
flyWeights.put(key, new ConcreteFlyWeight());
}
return flyWeights.get(key);
}
}
public class FlyWeightClient {
public static void main(String[] args) {
int extrinsicState = 22;
FlyWeightFactory f = new FlyWeightFactory();
FlyWeight fx = f.getFlyWeight("X");
fx.operation(--extrinsicState);
FlyWeight fy = f.getFlyWeight("Y");
fy.operation(--extrinsicState);
FlyWeight fz = f.getFlyWeight("Z");
fz.operation(--extrinsicState);
FlyWeight uf = new UnsharedConcreteFlyWeight();
uf.operation(--extrinsicState);
}
}
案例
public class User {
private String name;
public String getName() {
return name;
}
public User(String name) {
this.name = name;
}
}
public abstract class WebSite {
public abstract void use(User user);
}
public class ConcreteWebSite extends WebSite {
private String name;
public ConcreteWebSite(String name) {
this.name = name;
}
@Override
public void use(User user) {
System.out.println("网站分类:" + name + " 用户:" + user.getName());
}
}
public class WebSiteFactory {
private Hashtable flyweights = new Hashtable();
public WebSite getWebSiteCategory(String key) {
if (!flyweights.contains(key)) {
flyweights.put(key, new ConcreteWebSite(key));
}
return (WebSite) flyweights.get(key);
}
public int getWebSiteCount() {
return flyweights.size();
}
}
public class Client {
public static void main(String[] args) {
WebSiteFactory f = new WebSiteFactory();
WebSite fx = f.getWebSiteCategory("产品展示");
fx.use(new User("小菜"));
WebSite fy = f.getWebSiteCategory("产品展示");
fy.use(new User("大鸟"));
WebSite fz = f.getWebSiteCategory("产品展示");
fz.use(new User("娇娇"));
WebSite fl = f.getWebSiteCategory("博客");
fl.use(new User("老顽童"));
WebSite fm = f.getWebSiteCategory("博客");
fm.use(new User("桃谷六仙"));
WebSite fn = f.getWebSiteCategory("博客");
fn.use(new User("南海鳄神"));
System.out.println("得到网站分类总数为" + f.getWebSiteCount());
}
}