参考资料
《设计模式:可复用面向对象软件的基础》
标签:exist 实例 面向 public numbers enable sign actor gpo
享元模式(Flyweight Pattern)
The flyweight design pattern enables use sharing of objects to support large numbers of fine-grained objects efficiently.
1、Flyweight
-描述一个接口,通过这个接口flyweight可以接受并作用于外部状态。
2、ConcreteFlyweight
-实现Flyweight接口,并为内部状态(如果有的话)增加存储空间。ConcreteFlyweight对象必须是可共享的。它所存储的状态必须是内部的;即,它必须独立于ConcreteFlyweight对象的场景。
3、UnsharedConcreteFlyweight
-并非所有的Flyweight子类都需要被共享。Flyweight接口使共享成为可能,但它并不强制共享。在Flyweight对象结构的某些层次,UnsharedConcreteFlyweight对象通常将ConcreteFlyweight对象作为子节点。
4、FlyweightFactory
-创建并管理flyweight对象。
-确保合理地共享flyweight。当用户请求一个flyweight时,FlyweightFactory对象提供一个已创建的实例或创建一个。
5、Client
-维持一个对flyweight的引用。
-计算或者存储一个(多个)flyweight的外部状态。
class UnsharedConcreteFlyweight { private String sharedInfo; UnsharedConcreteFlyweight(String sharedInfo) { this.sharedInfo= sharedInfo; } public String getSharedInfo() { return sharedInfo; } public void setSharedInfo(String sharedInfo) { this.sharedInfo=sharedInfo; } }
interface Flyweight { public void operation(UnsharedConcreteFlyweight state); }
class ConcreteFlyweight implements Flyweight { private String key; ConcreteFlyweight(String key) { this.key=key; } public void operation(UnsharedConcreteFlyweight outState) { outState.getSharedInfo() } }
class FlyweightFactory { private HashMap<String, Flyweight> flyweights=new HashMap<String, Flyweight>(); public Flyweight getFlyweight(String key) { Flyweight flyweight=(Flyweight)flyweights.get(key); if(flyweight!=null) { System.out.println(key+" is exist!"); } else { flyweight=new ConcreteFlyweight(key); flyweights.put(key, flyweight); } return flyweight; } }
JAVA 中的 String,如果有则返回,如果没有则创建一个字符串保存在字符串缓存池里面。
《设计模式:可复用面向对象软件的基础》
标签:exist 实例 面向 public numbers enable sign actor gpo
原文地址:https://www.cnblogs.com/diameter/p/13194490.html