博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
享元模式
阅读量:7232 次
发布时间:2019-06-29

本文共 2019 字,大约阅读时间需要 6 分钟。

享元模式核心掌握的一点就是——共享。如果一个程序代码中存在大量细粒度的对象,而这些大量的对象造成了很大的存储开销时就应该考虑使用。例如一个博客网站,每个人根据自己的账号登录自己的博客,此时每个“博客类”就应该成为共享,这也称为内部状态,但每个人博客里的数据又不同,这时用不同的账号区分也即是称为外部状态。

UML类图如图所示。我们将具体的享元类抽象成一个接口。

1 package day_12_flyweight; 2  3 /** 4  * 享元类接口 5  * @author 余林丰 6  * 7  * 2016年10月12日 8  */ 9 public interface Flyweight {10     void operation(int extrinsicstate);  //这里的extrinsicstate就是上面所说的外部状态11 }

对享元类接口的具体实现。

1 package day_12_flyweight; 2  3 /** 4  * 具体享元类 5  * @author 余林丰 6  * 7  * 2016年10月12日 8  */ 9 public class ConcreteFlyweight implements Flyweight {10 11     /* (non-Javadoc)12      * @see day_12_flyweight.Flyweight#operation(int)13      */14     @Override15     public void operation(int extrinsicstate) {16         System.out.println("博客,账号:" + extrinsicstate);17     }18 19 }

享元类工厂。

1 package day_12_flyweight; 2  3 import java.util.HashMap; 4  5 /** 6  * 享元类工厂 7  * @author 余林丰 8  * 9  * 2016年10月12日10  */11 public class FlyweightFactory {12     private HashMap
flyweights = new HashMap
();13 14 public FlyweightFactory(){15 flyweights.put("X", new ConcreteFlyweight());16 flyweights.put("Y", new ConcreteFlyweight());17 flyweights.put("Z", new ConcreteFlyweight());18 }19 20 public Flyweight getFlyweight(String key){21 return ((Flyweight)flyweights.get(key));22 }23 }
1 package day_12_flyweight; 2  3 /** 4  * 客户端测试 5  * @author 余林丰 6  * 7  * 2016年10月12日 8  */ 9 public class Client {10     public static void main(String[] args){11         int extrinsicstate = 100;        //代码外部状态12         FlyweightFactory f = new FlyweightFactory();13         Flyweight fx = f.getFlyweight("X");14         fx.operation(extrinsicstate);15         16         Flyweight fy = f.getFlyweight("Y");17         fx.operation(--extrinsicstate);18     }19     20 }

这样我们就实现了一个最简的享元模式,给出享元模式的定义:运用共享技术有效地支持大量细粒度对象。那什么时候能考虑使用享元模式呢?如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。——《大话设计模式》

转载地址:http://vqpfm.baihongyu.com/

你可能感兴趣的文章
Linux ALSA声卡驱动之七:ASoC架构中的Codec
查看>>
unicode编码、字符的转换和得到汉字的区位码
查看>>
SQL手工注入
查看>>
设计模式总结篇系列:适配器模式(Adapter)
查看>>
利用FlashPaper实现类似百度文库功能
查看>>
视频码率,帧率和分辨率的联系与差别
查看>>
eclipse生成可执行jar包[转]
查看>>
Scala:Object-Oriented Meets Functional
查看>>
libvirt之virt-install
查看>>
分享我对 ASP.NET vNext 的一些感受,也许多年回过头看 So Easy!
查看>>
程序员生存定律--细论影响人生成绩的四个要素(2)
查看>>
你没见过吧?16款形态各异的加载进度条设计
查看>>
url rewrite
查看>>
Axiom3D:资源引用与加载基本流程.
查看>>
Button 自定义图片,代码绘制样式,添加音效的方法
查看>>
Perl操作Oracle
查看>>
unity3d与eclipse集成开发android应用
查看>>
iOS开发系列--C语言之预处理
查看>>
Windows下FFmpeg高速入门
查看>>
第 17 章 责任链模式【Chain of Responsibility Pattern】
查看>>