分类: Java
2009-03-31 15:43:52
public abstract class AbstractFurniture
implements Cloneable {
public abstract void draw();
// 在Design Pattern上,以下的clone是抽象未实作的
// 实际上在Java中class都继承自Object
// 所以在这边我们直接重新定义clone()
// 这是为了符合Java现行的clone机制
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
import java.awt.*;
public class CircleTable extends AbstractFurniture {
protected Point center;
public void setCenter(Point center) {
this.center = center;
}
protected Object clone ()
throws CloneNotSupportedException {
Object o = super.clone();
if(this.center != null) {
((CircleTable) o).center = (Point) center.clone();
}
return o;
}
public void draw() {
System.out.println("\t圆桌\t中心:(" + center.getX()
+ ", " + center.getY()+ ")");
}
}
import java.awt.*;
public class SquareTable extends AbstractFurniture {
protected Rectangle rectangle;
public void setRectangle(Rectangle rectangle) {
this.rectangle = rectangle;
}
protected Object clone ()
throws CloneNotSupportedException {
Object o = super.clone();
if(this.rectangle != null) {
((SquareTable) o).rectangle = (Rectangle) rectangle.clone();
}
return o;
}
public void draw() {
System.out.print("\t方桌\t位置:(" + rectangle.getX()
+ ", " + rectangle.getY()+ ")");
System.out.println(" / 宽高:(" +
rectangle.getWidth()
+ ", " + rectangle.getHeight()+ ")");
}
}
import java.util.*;
public class House {
private Vector vector;
public House() {
vector = new Vector();
}
public void addFurniture(AbstractFurniture furniture) {
vector.addElement(furniture);
System.out.println("现有家具....");
Enumeration enumeration = vector.elements();
while(enumeration.hasMoreElements()) {
AbstractFurniture f =
(AbstractFurniture) enumeration.nextElement();
f.draw();
}
System.out.println();
}
}
import java.awt.*;
public class Application {
private AbstractFurniture circleTablePrototype;
public void setCircleTablePrototype(
AbstractFurniture circleTablePrototype) {
this.circleTablePrototype = circleTablePrototype;
}
public void runAppExample() throws Exception {
House house = new House();
CircleTable circleTable = null;
// 从工具列选择一个家具加入房子中
circleTable =
(CircleTable) circleTablePrototype.clone();
circleTable.setCenter(new Point(10, 10));
house.addFurniture(circleTable);
// 从工具列选择一个家具加入房子中
circleTable =
(CircleTable) circleTablePrototype.clone();
circleTable.setCenter(new Point(20, 30));
house.addFurniture(circleTable);
}
public static void main(String[] args) throws Exception {
Application application = new Application();
application.setCircleTablePrototype(
new CircleTable());
application.runAppExample();
}
}