原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
- 创建一个实现了 Cloneable 接口的抽象类。
/**
* 形状
*
* @author 吴尚慧
* @since 2022/6/21 10:15
*/
public abstract class Shape implements Cloneable {
private Integer id;
protected String type;
/**
* 画
*/
public abstract void draw();
public String getType(){
return type;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
- 创建扩展了上面抽象类的实体类。
/**
* 圆
*
* @author 吴尚慧
* @since 2022/6/21 10:17
*/
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("画一个圆");
}
}
/**
* 长方形
*
* @author 吴尚慧
* @since 2022/6/21 10:17
*/
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("画一个长方形");
}
}
/**
* 正方形
*
* @author 吴尚慧
* @since 2022/6/21 10:17
*/
public class Square extends Shape {
public Square() {
type = "Square";
}
@Override
public void draw() {
System.out.println("画一个正方形");
}
}
- 创建一个缓存
/**
* @author 吴尚慧
* @since 2022/6/21 10:20
*/
public class ShapeCache {
private static Map<Integer, Shape> SHAPE_MAP = new HashMap<>();
public static Shape getShape(Integer shapeId) {
Shape cachedShape = SHAPE_MAP.get(shapeId);
return (Shape) cachedShape.clone();
}
public static void loadCache() {
Circle circle = new Circle();
circle.setId(1);
SHAPE_MAP.put(circle.getId(), circle);
Square square = new Square();
square.setId(2);
SHAPE_MAP.put(square.getId(), square);
Rectangle rectangle = new Rectangle();
rectangle.setId(3);
SHAPE_MAP.put(rectangle.getId(), rectangle);
}
}
- 测试
/**
* @author 吴尚慧
* @since 2022/6/21 10:22
*/
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = ShapeCache.getShape(1);
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = ShapeCache.getShape(2);
System.out.println("Shape : " + clonedShape2.getType());
Shape clonedShape3 = ShapeCache.getShape(3);
System.out.println("Shape : " + clonedShape3.getType());
}
}
结果:
Shape : Circle
Shape : Square
Shape : Rectangle
参考:
https://www.runoob.com/design-pattern/design-pattern-intro.html