Java设计模式偷跑系列(21)建模和实现享受metapatterns
2015-07-26 20:35
453 查看
转载请注明出处:/article/1330854.html
享元模式(Flyweight):运用共享的技术有效地支持大量细粒度的对象。
主要目的是实现对象的共享,即共享池。当系统中对象多的时候能够降低内存的开销。在某种程度上。你能够把单例看成是享元的一种特例。
true
this is the sub method,and the key is aaa
this is the sub method。and the key is aaa
1
======================================
false
this is the sub method,and the key is ccc
2
享元模式(Flyweight):运用共享的技术有效地支持大量细粒度的对象。
主要目的是实现对象的共享,即共享池。当系统中对象多的时候能够降低内存的开销。在某种程度上。你能够把单例看成是享元的一种特例。
一、uml建模:
二、代码实现
/** * 享元模式(Flyweight):运用共享的技术有效地支持大量细粒度的对象。 * * 主要目的是实现对象的共享,即共享池,当系统中对象多的时候能够降低内存的开销。 */ abstract class FlyWeight { public abstract void method(); } /** * 创建持有key的子类 */ class SubFlyWeight extends FlyWeight { private String key; public SubFlyWeight(String key) { this.key = key; } @Override public void method() { System.out.println("this is the sub method。and the key is " + this.key); } } /** * 享元工厂:负责创建和管理享元对象 */ class FlyweightFactory { private Map<String, FlyWeight> map = new HashMap<String, FlyWeight>(); /** * 获取享元对象 */ public FlyWeight getFlyWeight(String key) { FlyWeight flyWeight = map.get(key); if (flyWeight == null) { flyWeight = new SubFlyWeight(key); map.put(key, flyWeight); } return flyWeight; } /** * 获取享元对象数量 */ public int getCount() { return map.size(); } } /** * client測试类 * * @author Leo */ public class Test { public static void main(String[] args) { /** * 创建享元工厂 */ FlyweightFactory factory = new FlyweightFactory(); /***** 第一种情况:key同样时 ***************/ FlyWeight flyWeightA = factory.getFlyWeight("aaa"); FlyWeight flyWeightB = factory.getFlyWeight("aaa"); /** * 透过打印结果为true能够知道: 因为key都为"aaa",所以flyWeightA和flyWeightB指向同一块内存地址 */ System.out.println(flyWeightA == flyWeightB); flyWeightA.method(); flyWeightB.method(); /** * 享元对象数量:1 */ System.out.println(factory.getCount()); /***** 另外一种情况:key不同样时 ***************/ System.out.println("\n======================================"); FlyWeight flyWeightC = factory.getFlyWeight("ccc"); /** * 打印结果为false */ System.out.println(flyWeightA == flyWeightC); flyWeightC.method(); /** * 享元对象数量:2 */ System.out.println(factory.getCount()); } }打印结果:
true
this is the sub method,and the key is aaa
this is the sub method。and the key is aaa
1
======================================
false
this is the sub method,and the key is ccc
2
三、总结
享元与单例的差别:1、与单例模式不同。享元模式是一个类能够有非常多对象(共享一组对象集合),而单例是一个类仅一个对象;2、它们的目的也不一样,享元模式是为了节约内存空间,提升程序性能(避免大量的new操作),而单例模式则主要是共享单个对象的状态及特征。相关文章推荐
- Java 中使用 Calendar 类得到输入日期所在月的最后一天
- java实现将资源文件转化成sql语句导入数据库
- Java多线程-工具篇-BlockingQueue
- Java原生多线程并发方法归纳
- 按键事件在java framework中的流程
- Java对话框总结
- 找出java代码中占用cpu过多问题
- Java多线程的~~~Lock接口和ReentrantLock使用
- java多线程并发——Exchanger 两个任务之间交换对象
- java 获取泛型的类型
- cmd运行记事本所编java的步骤,以及找不到或无法加载主类的解决办法
- JVM java 监控工具-命令行
- JVM java监控-可视化
- JVM java对象引用强度
- JAVA基础知识(2)--关键字final的使用
- JAVA随机数之多种方法从给定范围内随机N个不重复数
- java 静态代码块 动态代码块 加载时间
- JAVA基础知识(2)--关键字static的使用
- JAVA设计模式之观察者模式
- Spring 引入属性文件