标签:gets lenovo date 缓存 类继承 return bst out pat
当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。
我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
/**
* @author Lenovo
* @date 2020/7/4 19:25
* 原型模式:
* 第一步,定义实现Cloneable接口的抽象类
* 第二步,写实现类继承抽象类
* 第三步,缓存起来可以克隆的实体,并提供获取方法,返回原实体的克隆版本
* 说白了就是,内存中保留对象的缓存,每次获取时提供克隆版本。
* 适用场景,初始化复杂对象或者需要多次查库,开销比较高时,使用原型模式快速创建对象。
*
* 思考:深浅克隆问题?
*/
public abstract class Shape implements Cloneable{
private String id;
public String type;
abstract void draw();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public Object clone(){
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
public class Circle extends Shape {
public Circle() {
type = "Circle";
}
public void draw(){
System.out.println("draw circle");
}
}
public class Rectangle extends Shape {
public Rectangle() {
type = "Rectangle";
}
public void draw(){
System.out.println("draw rectangle");
}
}
public class Square extends Shape{
public Square() {
type = "squre";
}
public void draw(){
System.out.println("draw square");
}
}
public class ShapeCache {
private static Hashtable<String,Shape> shapeCache = new Hashtable<>();
public static Shape getShapeByID(String ID){
final Shape shape = shapeCache.get(ID);
return (Shape) shape.clone();
}
//模拟从数据库加载数据后,生成对象
public static void loadCache(){
final Circle circle = new Circle();
circle.setId("1");
shapeCache.put(circle.getId(),circle);
final Square square = new Square();
square.setId("2");
shapeCache.put(square.getId(),square);
final Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeCache.put(rectangle.getId(),square);
}
}
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
final Shape cloneShape = ShapeCache.getShapeByID("1");
System.out.println("Shape:" + cloneShape.getType());
final Shape cloneShape2 = ShapeCache.getShapeByID("2");
System.out.println("Shape:" + cloneShape2.getType());
final Shape cloneShape3 = ShapeCache.getShapeByID("3");
System.out.println("Shape" + cloneShape3.getType());
}
}
标签:gets lenovo date 缓存 类继承 return bst out pat
原文地址:https://www.cnblogs.com/xingrui/p/13236392.html