设计模式-11-享元模式
来源:互联网 发布:算法的乐趣代码 编辑:程序博客网 时间:2024/06/03 21:45
享元模式:主要用于减少创建对象的数量,以减少内存的占用和提高性能。
享元模式的核心在于享元工厂类,享元工厂类的作用在于提供一个用于存储享元对象的享元池,用户需要对象时,首先从享元池中获取,如果享元池中不存在,则创建一个新的享元对象返回给用户,并在享元池中保存该新增对象。
package com.structuralPattern.enjoy_yuan.edition1;public abstract class Shape { public abstract void draw();}
package com.structuralPattern.enjoy_yuan.edition1;public class Circle extends Shape{ private String color; public Circle(String color){ this.color = color; } public void draw() { System.out.println("画了一个" + color +"的圆形"); }}
package com.structuralPattern.enjoy_yuan.edition1;import java.util.HashMap;import java.util.Map;public class FlyweightFactory{ static Map<String, Shape> shapes = new HashMap<String, Shape>(); public static Shape getShape(String key){ Shape shape = shapes.get(key); //如果shape==null,表示不存在,则新建,并且保持到共享池中 if(shape == null){ shape = new Circle(key); shapes.put(key, shape); } return shape; } public static int getSum(){ return shapes.size(); }}
package com.structuralPattern.enjoy_yuan.edition1;public class Client { public static void main(String[] args) { Shape shape1 = FlyweightFactory.getShape("红色"); shape1.draw(); Shape shape2 = FlyweightFactory.getShape("灰色"); shape2.draw(); Shape shape3 = FlyweightFactory.getShape("绿色"); shape3.draw(); Shape shape4 = FlyweightFactory.getShape("红色"); shape4.draw(); Shape shape5 = FlyweightFactory.getShape("灰色"); shape5.draw(); Shape shape6 = FlyweightFactory.getShape("灰色"); shape6.draw(); System.out.println("一共绘制了"+FlyweightFactory.getSum()+"中颜色的圆形"); }}
阅读全文
0 0
- 设计模式(11) 享元模式(FLYWEIGHT)
- 设计模式(11)------享元模式
- 设计模式(11)-享元模式
- 设计模式(11)-享元模式
- 设计模式(11)--享元模式
- 设计模式-11-享元模式
- 设计模式---享元模式
- 设计模式 享元模式
- 设计模式 - 享元模式
- 设计模式:享元模式
- 设计模式 - 享元模式
- 设计模式-享元模式
- 设计模式---------享元模式
- 设计模式:享元模式
- 设计模式--享元模式
- 设计模式-享元模式
- 设计模式:享元模式
- 设计模式-享元模式
- 线性回归LinearRegression(单变量线性回归)
- Spring-Data Redis 实现验证码的功能
- Mysql主从配置
- Hdu-6052 To my boyfriend(单调栈)
- SLAM学习——回环检测
- 设计模式-11-享元模式
- Yii2 ajax 提交 view 端 和 controller端
- 一个面试题
- storm与流计算
- Sublime Text编辑器在前端中的快捷操作
- 5种排序算法的Java代码
- 杭电oj1017
- AutoCAD文档01——安装教程
- No module named keras