我看到一些代碼的好處定義這樣的原型模式:什麼是原型模式在這種情況下
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 m ethod的是這兩種實現之間的區別和好處:我嘗試了兩種實現方式,他們
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
// return (Shape) cachedShape.clone();
return cachedShape ;
}
:
實現1:
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
和: 實施2工作得很好,只是我想知道如果我使用第一個實施方案的好處
我其實很喜歡你解釋;) – Jay
我不是OP:P – Jay