设计模式【九】原型模式

原型模式:通过原型实例,拷贝创建新的对象。

1、类图:

2、实现:

public abstract class AbstractExport implements Cloneable {

    protected String exportType;

    protected String name;

    public String getExportType() {
        return exportType;
    }

    public void setExportType(String exportType) {
        this.exportType = exportType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public void export() {
        System.out.println("export type:" + this.exportType);
        System.out.println("export name:" + this.name);
    }
}


public class AsyncExport extends AbstractExport {

    public AsyncExport() {
        super.exportType = "ASYNC";
    }

}


public class SyncExport extends AbstractExport {

    public SyncExport() {
        super.exportType = "SYNC";
    }


}


public class ExportTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        AbstractExport asyncExport = new AsyncExport();
        asyncExport.setName("windows");
        asyncExport.export();
        AbstractExport asyncExportNew = (AbstractExport) asyncExport.clone();
        asyncExportNew.export();

        System.out.println("======");

        AbstractExport syncExport = new SyncExport();
        syncExport.setName("windows2");
        syncExport.export();
        AbstractExport syncExportNew = (AbstractExport) syncExport.clone();
        syncExportNew.export();
    }

}

3、clone实现的是浅拷贝,如果需要深拷贝,可以在clone中对相应的对象在次进行拷贝并赋值。

4、原型拷贝在想要保留对象原有数据时非常有用。在java中也有其它工具根据实体对象的get、set方法的反射进行字段复制,当然也可以自己根据反射,获取method、field相关信息并进行设置。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值