创建型设计模式(四)原型模式
一、一句话背景
假如我是个设计大佬,我经常需要调用服务去获取各种基本图形来组合我的素材,那重复访问的工作就会很多,那在没有外置缓存的情况下,可以考虑使用原型模式来玩~
二、使用场景
需要重复生成多次相同对象的场景。
如:重复取相同对象使用时
三、模型分析
图形原型:抽象类,原型父类,用于扩展子类对象,并进行复用
具体图形:类,图形父类的多样化拓展
模拟缓存:类,用于模拟缓存具体的对象,并提供复制方法
四、代码分析
图形原型
/** * 形状类,原型父类,用于扩展子类对象,并进行复用 */ public abstract class Shape implements Cloneable { private String id; protected String type; public abstract void draw(); public String getType() { return type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
具体图形
/** * 圆形类 */ public class Circle extends Shape { public Circle() { type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
/** * 矩形类 */ public class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
/** * 正方形类 */ public class Square extends Shape { public Square() { type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
模拟缓存
/** * 模拟缓存类,用于复制拓展的对象 */ public class ShapeCache { //这个map里存好了对象,用的时候直接调用本类的getShape来clone就好 private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); //static可以把这个方法给其他类调用,直接clone设置好的map里的对象,就不用每次都new一个对象 public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } // 对每种形状都运行数据库查询,并创建该形状 // shapeMap.put(shapeKey, shape); // 例如,我们要添加三种形状 public static void loadCache() { Circle circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(), circle); Square square = new Square(); square.setId("2"); shapeMap.put(square.getId(), square); Rectangle rectangle = new Rectangle(); rectangle.setId("3"); shapeMap.put(rectangle.getId(), rectangle); } }
克隆调用
/** * 模拟克隆调用 */ public class PrototypePatternDemo { public static void main(String[] args) { ShapeCache.loadCache(); Shape clonedShape = (Shape) ShapeCache.getShape("1"); System.out.println("Shape : " + clonedShape.getType()); Shape clonedShape2 = (Shape) ShapeCache.getShape("2"); System.out.println("Shape : " + clonedShape2.getType()); Shape clonedShape3 = (Shape) ShapeCache.getShape("3"); System.out.println("Shape : " + clonedShape3.getType()); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律