原型模式
内容参考 w3cSchool
目录
UML 类图
抽象类AbstractShape中有两个属性:id 、 类型,一个绘制图形的方法,并且继承了 Clone接口
三个实现类:Circle 、 Square 、Rectangle
在ShapeCache中进行对数据的缓存以及读取。ShapMap中缓存在数据库中查询到的数据【loadCache()】,getShape中深复制返回对应ID的Shape对象。即一次缓存后,在应用中多次使用不必每次查询数据库,直接在缓存中查询相关数据,如果没有数据再适时进行数据库查询。
下面根据教程里的自己实现一遍
创建 AbstractShape 类
public abstract class Shape implements Cloneable{
private String id;
protected String type = "Unknown";
/**
* 绘制图形
*/
abstract void draw();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
/*
* 实现拷贝
*/
@Override
protected Object clone(){
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
实体类 Circle Rectangle Square
Circle
public class Circle extends Shape{
public Circle() {
type = "Circle";
}
@Override
void draw() {
System.out.println("[Circle] Draw");
}
}
Rectangle
public class Rectangle extends Shape{
public Rectangle() {
type = "Rectangle";
}
@Override
void draw() {
System.out.println("[Rectangle] draw");
}
}
Square
public class Square extends Shape{
public Square() {
type = "Square";
}
@Override
void draw() {
System.out.println("[Square] Draw");
}
}
创建缓存类 ShapeCache
public class ShapeCache {
private static Hashtable<String,Shape> shapeMap = new Hashtable<>();
public static Shape getShape(String shapeId){
Shape shapeCache = shapeMap.get(shapeId);
return (Shape) shapeCache.clone(); //深拷贝
}
/*
* 这里是模拟的数据,正常情况是使用数据库查询结果的缓存
*/
public static void loadCache(){
Circle circle = new Circle();
Square square = new Square();
Rectangle rectangle = new Rectangle();
circle.setId("1");
square.setId("2");
rectangle.setId("3");
shapeMap.put(circle.getId(),circle);
shapeMap.put(square.getId(),square);
shapeMap.put(rectangle.getId(),rectangle);
}
}
测试运行
public class ExecuteMain {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape shapeClone1 = ShapeCache.getShape("1");
Shape shapeClone2 = ShapeCache.getShape("2");
Shape shapeClone3 = ShapeCache.getShape("3");
System.out.println("[Shape] "+shapeClone1.getType());
System.out.println("[Shape] "+shapeClone2.getType());
System.out.println("[Shape] "+shapeClone3.getType());
}
}
[Shape] Circle
[Shape] Square
[Shape] Rectangle
Process finished with exit code 0