前言
博主github
博主个人博客http://blog.healerjean.com
1、业务场景
**当创建对象的代价比较大的时候,采用这种模式, **
实现方式、 容器,clone
2、实例代码1
2.1、被复制的抽象对象
@Data
@ToString
public abstract class Shape implements Cloneable {
public String id;
public String type;
abstract void draw();
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
2.2、子类
2.2.1、Rectangle
extends Shape
@Data
@ToString
public class Rectangle extends Shape {
private String pectangleName ;
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println(id+":"+type+":"+pectangleName);
}
}
2.2.2、Square
extends Shape
@Data
@ToString
public class Square extends Shape {
private String squareName ;
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println(id+":"+type+":"+squareName);
}
}
2.3、创建和复制的类ShapeCache
public class ShapeCache {
private static Map<String, Shape> shapeMap = new HashMap<>();
/**
* 通过map和拷贝 获取全新对象
*/
public static Shape getByType(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
/**
* 创建原型
*/
public static void create(Shape shape) {
shapeMap.put(shape.getType(),shape);
}
}
2.4、测试
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setType("rectangle");
rectangle.setId("1");
rectangle.setPectangleName("rectangleName");
ShapeCache.create(rectangle);
Square square = new Square();
square.setType("square");
square.setId("2");
square.setSquareName("squareName");
ShapeCache.create(square);
rectangle = (Rectangle)ShapeCache.getByType("rectangle") ;
rectangle.draw();
square = (Square)ShapeCache.getByType("square") ;
square.draw();
}
// 1:rectangle:rectangleName
// 2:square:squareName
}
3、总结:
ShapeCache
用于创建和克隆 clone 复制实例对象
感兴趣的,欢迎添加博主微信
哈,博主很乐意和各路好友交流,如果满意,请打赏博主任意金额,感兴趣的在微信转账的时候,备注您的微信或者其他联系方式。添加博主微信哦。
请下方留言吧。可与博主自由讨论哦
微信 | 微信公众号 | 支付宝 |
---|---|---|