设计模式之原型模式

来源:互联网 发布:php 判断大小 编辑:程序博客网 时间:2024/06/18 07:05

背景

期末作业系列之设计模式

原型模式示例

实现clonable接口并重写clone()方法的类:

public class SonDellOffice implements Cloneable{    private String officeNameString ="dell子公司";    public SonDellOffice(){    }    public String getOfficeNameString() {        return officeNameString;    }    public void setOfficeNameString(String officeNameString) {        this.officeNameString = officeNameString;    }    @Override    public SonDellOffice clone() {        SonDellOffice sonDellOffice = null;        try {            sonDellOffice = (SonDellOffice)super.clone();        } catch (CloneNotSupportedException e) {            // TODO: handle exception            e.printStackTrace();        }        return sonDellOffice;    }}

Main客户端调用

public class client {    public static void main(String[] args) {        DellHeadOffice dellHeadOffice = DellHeadOffice.getDellHeadOffice();        dellHeadOffice.saySomething();        SonDellOffice sonDellOffice = new SonDellOffice();        for(int i=1;i<=3;i++){            SonDellOffice cloneSonDellOffice = sonDellOffice.clone();            cloneSonDellOffice.setOfficeNameString(cloneSonDellOffice.getOfficeNameString()+i);            System.out.println(cloneSonDellOffice.getOfficeNameString());        }        ProductSeller productSeller = new EShopProxy();        productSeller.sellProduct();    }}
原创粉丝点击