0
点赞
收藏
分享

微信扫一扫

设计模式之生成实例_Prototype复制模式_通过复制生成实例


前言

​​博主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 复制实例对象

设计模式之生成实例_Prototype复制模式_通过复制生成实例_实例代码

举报

相关推荐

0 条评论