MST

星途 面试题库

面试题:Java中如何实现一个简单的原型模式

请使用Java代码实现一个简单的原型模式,假设存在一个图形类Shape,包含颜色等属性,要求创建Shape的子类Circle和Rectangle,并重写克隆方法实现对象的克隆。
25.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
// 图形类
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();
        }
    }
}