面试题答案
一键面试// 图形类
class Shape implements Cloneable {
private String color;
public Shape(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
protected Shape clone() throws CloneNotSupportedException {
return (Shape) super.clone();
}
}
// 圆形类
class Circle extends Shape {
public Circle(String color) {
super(color);
}
@Override
protected Circle clone() throws CloneNotSupportedException {
return (Circle) super.clone();
}
}
// 矩形类
class Rectangle extends Shape {
public Rectangle(String color) {
super(color);
}
@Override
protected Rectangle clone() throws CloneNotSupportedException {
return (Rectangle) super.clone();
}
}
你可以通过以下方式测试:
public class PrototypePatternDemo {
public static void main(String[] args) {
try {
Circle circle = new Circle("red");
Circle clonedCircle = circle.clone();
System.out.println("Original Circle Color: " + circle.getColor());
System.out.println("Cloned Circle Color: " + clonedCircle.getColor());
Rectangle rectangle = new Rectangle("blue");
Rectangle clonedRectangle = rectangle.clone();
System.out.println("Original Rectangle Color: " + rectangle.getColor());
System.out.println("Cloned Rectangle Color: " + clonedRectangle.getColor());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}