Prototype Design Pattern

本文介绍了一个抽象家具类及其圆形桌和方形桌两个子类的具体实现。通过实现Cloneable接口并重写clone方法,确保在进行对象复制时能够正确地深拷贝包含的Point和Rectangle对象,避免了对象间引用导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public abstract class AbstractFurniture implements Cloneable {
    public abstract String draw();
   
    protected Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
}

 

 

 

 

public class CircleTable extends AbstractFurniture {
    protected Point center;
   
   
    public Point getCenter() {
        return center;
    }


    public void setCenter(Point center) {
        this.center = center;
    }


    public String draw() {
        return center.toString();
    }
   
    protected Object clone() throws CloneNotSupportedException {
        Object o = super.clone();
        if(this.center != null) {
            ((CircleTable)o).setCenter((Point)center.clone());
        }
        return o;
    }
}

 

 

 

public class SquareTable extends AbstractFurniture {
    protected Rectangle rectangle;
   
   
    public Rectangle getRectangle() {
        return rectangle;
    }

    public void setRectangle(Rectangle rectangle) {
        this.rectangle = rectangle;
    }

    public String draw() {
        return rectangle.toString();
    }

    protected Object clone() throws CloneNotSupportedException {
        Object o = super.clone();
        if(this.rectangle != null) {
            ((SquareTable)o).setRectangle((Rectangle)rectangle.clone());
        }
        return o;
    }
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值