享元模式应用场景
在面向对象程序设计过程中,有时会面临创建大量相同或相似的对象实例的问题。创建那么多的对象将会耗费很多系统资源,它是系统提升的一个瓶颈。
例如,围棋和五子棋中的黑白棋子,图像中坐标或颜色,在局域网中的路由器,交换机和集线器等。这些对象有很多相似的地方,如果能够把她们的相同部分提取出来,则能节省大量的系统资源。
享元模式代码示例
抽象享元
package com.demo.test.flyweight.iml;
import com.demo.test.flyweight.UnsharedConcreteFlyweight;
public interface Flyweight {
public void operation(UnsharedConcreteFlyweight state);
}
具体享元A
package com.demo.test.flyweight;
import com.demo.test.flyweight.iml.Flyweight;
public class ConcreteFlyweightA implements Flyweight {
private String key;
public ConcreteFlyweightA(String key){
this.key = key;
}
@Override
public void operation(UnsharedConcreteFlyweight state) {
System.out.println("ConcreteFlyweightA:具体享元"+key+"被调用");
System.out.println("非享元信息:"+state.getInfo());
}
}
具体享元B
package com.demo.test.flyweight;
import com.demo.test.flyweight.iml.Flyweight;
public class ConcreteFlyweightB implements Flyweight {
private String key;
public ConcreteFlyweightB(String key){
this.key = key;
}
@Override
public void operation(UnsharedConcreteFlyweight state) {
System.out.println("ConcreteFlyweightB:具体享元"+key+"被调用");
System.out.println("非享元信息:"+state.getInfo());
}
}
非享元角色
package com.demo.test.flyweight;
public class UnsharedConcreteFlyweight {
private String info;
public UnsharedConcreteFlyweight(String info){
this.info = info;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
享元工厂角色
package com.demo.test.flyweight;
import com.demo.test.flyweight.iml.Flyweight;
import java.util.HashMap;
public 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+"已经存在,被成功获取");
}else{
if(key.equals("a")){
flyweight = new ConcreteFlyweightA(key);
}else if(key.equals("b")){
flyweight = new ConcreteFlyweightB(key);
}else{
return null;
}
flyweights.put(key,flyweight);
}
System.out.println("实例数量:"+flyweights.size());
return flyweight;
}
}
客户端
package com.demo.test.flyweight;
import com.demo.test.flyweight.iml.Flyweight;
public class Client {
public static void main(String[] agr){
FlyweightFactory flyweightFactory = new FlyweightFactory();
Flyweight f1 = flyweightFactory.getFlyweight("a");
Flyweight f2 = flyweightFactory.getFlyweight("b");
Flyweight f3 = flyweightFactory.getFlyweight("a");
Flyweight f4 = flyweightFactory.getFlyweight("a");
Flyweight f5 = flyweightFactory.getFlyweight("a");
f1.operation(new UnsharedConcreteFlyweight("非享元信息a"));
f2.operation(new UnsharedConcreteFlyweight("非享元信息b"));
f3.operation(new UnsharedConcreteFlyweight("非享元信息3"));
f4.operation(new UnsharedConcreteFlyweight("非享元信息4"));
f5.operation(new UnsharedConcreteFlyweight("非享元信息5"));
}
}
小结
个人认识享元和单例有一些相似的地方,享元模式对重复或者相似很高的实例有很好的复用功能,从示例的执行结果来看,对象只实例话了两次。