设计模式FlyWeight 享元模式
Flyweight模式的核心思想是将对象的可共享部分抽取出来,以避免重复创建相同内容的对象。换句话说,Flyweight模式允许多个对象共享相同的数据来节省内存。
示例代码
java
import java.util.HashMap; import java.util.Map; // Flyweight接口 interface Shape { void draw(); } // 具体的Flyweight类 class Circle implements Shape { private String color; // 内部状态:可以共享 private int x; // 外部状态:不共享 private int y; private int radius; public Circle(String color) { this.color = color; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setRadius(int radius) { this.radius = radius; }
代码说明:
-
Shape接口:定义了
draw
方法,所有的具体形状类都需要实现这个接口。 -
Circle类:这是具体的Flyweight类,实现了
Shape
接口。color
是共享的内部状态,x
、y
和radius
是外部状态,不能被共享,每次绘制时都会设置这些值。 -
ShapeFactory类:这是Flyweight工厂类,它通过维护一个
Map
来存储已经创建的Circle
对象。通过颜色来查找已经存在的Circle
对象,如果没有找到则创建一个新的Circle
对象并添加到Map
中。 -
FlyweightPatternDemo类:客户端代码演示了如何使用
ShapeFactory
来获取共享的Circle
对象,并设置外部状态来绘制不同的圆形。
输出示例:
plaintext
Creating circle of color : Green Drawing Circle [Color : Green, x : 49, y :50, radius :100] Creating circle of color : Red Drawing Circle [Color : Red, x : 36, y :85, radius :100] Creating circle of color : Blue Drawing Circle [Color : Blue, x : 18, y :14, radius :100] Creating circle of color : White Drawing Circle [Color : White, x : 54, y :92, radius :100] Creating circle of color : Black Drawing Circle [Color : Black, x : 28, y :70, radius :100] Drawing Circle [Color : Green, x : 78, y :26, radius :100] Drawing Circle [Color : Red, x : 37, y :15, radius :100] ...
在这个示例中,通过共享相同颜色的圆形对象,可以避免重复创建相同颜色的Circle
对象,从而节省内存。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?