【发布时间】:2016-11-04 10:00:23
【问题描述】:
我看到一些代码是这样定义原型模式的:
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
扩展上述类的两个具体类:
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
创建一个类以从数据库中获取具体的类并将它们存储在 Hashtable 中:
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
public static void loadCache() {
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(), rectangle);
}
}
我的问题是在 getShape 方法中,这两种实现有什么区别和好处:
实施1:
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
并且: 实施 2:
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
// return (Shape) cachedShape.clone();
return cachedShape ;
}
我尝试了这两个实现,它们运行良好只是我想知道如果我使用第一个实现会带来什么好处
【问题讨论】:
标签: java design-patterns