Add to favourites
News Local and Global in your language
17th of January 2018

因特网



Java设计模式之享元模式 - EnjoyCodeの博客 - CSDN博客

享元模式(Flyweight):运用共享技术有效地支持大量细粒度对象。

所有具体享元类的超类,接受并作用于外部状态:

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); } }运行结果:具体FlyWeight:21 具体FlyWeight:20 具体FlyWeight:19 不共享的具体FlyWeight:18享元模式的应用场景:

如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象时,可以考虑使用享元模式。

Read More




Leave A Comment

More News

互联网

中新网IT新闻

CSDN博客推荐文章

Disclaimer and Notice:WorldProNews.com is not the owner of these news or any information published on this site.