创建型模式之原型模式PROTOTYPE
来源:互联网 发布:聊城js fs复合保温模板 编辑:程序博客网 时间:2024/05/29 07:30
意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
一、原型模式
原型模式应用场景主要在于当一个对象的创建非常复杂,消耗很多资源之时。如果一个对象的创建之前需要经过很过步骤和要求,一般情况对象用完就会销毁。但为了避免资源的消耗。可以把对象存住,下次使用时直接复制原型。
java 克隆
二、代码
原料
主要在于实现java对象的克隆
package prototype;public abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); public void setId(String id){ this.id = id; } public String getId() { return id; } public Object clone() { Shape clone = null; try { clone = (Shape)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; }}
package prototype;public class Rectangle extends Shape{ public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Rectangle"); }}
package prototype;public class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Square"); }}
容器
package prototype;import java.util.Hashtable;public class ShapeCache { private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } public static void loadCache() { Square square = new Square(); square.setId("1"); shapeMap.put(square.getId(),square); Rectangle rectangle = new Rectangle(); rectangle.setId("2"); shapeMap.put(rectangle.getId(),rectangle); } public static void main(String[] args) { ShapeCache.loadCache(); Shape clonedShape1 = (Shape) ShapeCache.getShape("1"); System.out.println(clonedShape1.type); Shape clonedShape2 = (Shape) ShapeCache.getShape("2"); System.out.println(clonedShape2.type); } }
代码
0 0
- 创建型模式之原型(ProtoType)模式
- 创建型模式之原型模式(prototype)
- 创建型模式之原型模式PROTOTYPE
- 创建模式之Prototype(原型)
- 创建模式之Prototype(原型)
- Prototype原型(创建型模式)
- Prototype原型(创建型模式)
- 创建型-原型模式(prototype)
- (创建模式)设计模式之Prototype(原型)
- 六、创建模式之原型(Prototype)模式
- 设计模式笔记--创建型模式之四--原型prototype
- 创建型模式之原型模式(ProtoType)
- 设计模式之Prototype(原型模式)对象创建型
- 设计模式(创建型)之原型模式(Prototype Pattern)
- 【设计模式】创建型模式之原型Prototype
- 5种创建型模式之:原型模式(Prototype)
- 设计模式之对象创建型 — prototype 原型模式
- Prototype - 原型创建模式
- 工控PLC收集data
- SpringMVC 2(跳转结果的方式:转发、重定向)
- Ajax的工作原理和基本操作
- ffmpeg PCM转AMR格式
- 多重继承中的信号与槽
- 创建型模式之原型模式PROTOTYPE
- 上拉加载和下拉刷新遇到的坑
- log4j2配置
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- AVPlayer 对MP4等视频格式进行截屏截屏
- eclipse中使用alt+/查看提示时报错的解决方法
- 解决jmeter 处理大数据量结果返回导致jmeter卡死的问题
- java wait和notify的使用
- iOS9、iOS10 HTTPS 网络请求