/** * @author :nx014924 * @date :Created in 5/30/2021 2:45 PM * @description: * @modified By: * @version: */ public class Phone implements Cloneable{ private String name; private int price; private Factory factory; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public String toString(){ return new StringBuilder() .append(" name=") .append(this.name) .append(" price=") .append(this.price) .append(" factory name=") .append(this.factory.getName()) .append(" engineer name=") .append(this.factory.getEngineer().getName()) .append(" engineer age=") .append(this.factory.getEngineer().getAge()) .toString(); } private Phone(Builder builder){ this.name = builder.name; this.price = builder.price; this.factory = builder.factory; } public static class Builder{ private String name; private int price; private Factory factory; public static Builder getInstance(){ return new Builder(); } public Builder setName(String name){ this.name = name; return this; } public Builder setPrice(int price){ this.price = price; return this; } public Builder setFactory(Factory factory){ this.factory = factory; return this; } public Phone build(){ return new Phone(this); } } //省略了getter、setter }
/** * @author :nx014924 * @date :Created in 5/30/2021 2:45 PM * @description: * @modified By: * @version: */ public class Factory implements Cloneable{ private String name; private Engineer engineer; protected Factory clone() throws CloneNotSupportedException { //手动实现下clone方法 Factory factory = new Factory(); if (this.name != null) factory.name = this.name; if (this.engineer != null) factory.engineer = (Engineer) this.engineer.clone(); return factory; } public Factory(){} public Factory(String name, Engineer engineer){ this.name = name; this.engineer = engineer; } //省略了getter、setter }
/** * @author :nx014924 * @date :Created in 5/30/2021 2:46 PM * @description: * @modified By: * @version: */ public class Engineer implements Cloneable{ private String name; private int age; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public Engineer(String name, int age){ this.name = name; this.age = age; } //省略了getter、setter }
/** * @author :nx014924 * @date :Created in 5/30/2021 2:46 PM * @description: * @modified By: * @version: */ public class Start { public static void main(String[] args) throws CloneNotSupportedException { Engineer engineer = new Engineer("雷军", 20); Factory factory = new Factory("小米厂", engineer); Phone phone1 = Phone.Builder .getInstance() .setName("小米") .setPrice(1999) .setFactory(factory) .build(); System.out.println("phone1-----" + phone1.toString());//phone1----- name=小米 price=1999 factory name=小米厂 engineer name=雷军 engineer age=20 Phone phone2 = (Phone) phone1.clone(); phone2.setName("红米"); System.out.println("phone2-----" + phone2.toString());//phone2----- name=红米 price=1999 factory name=小米厂 engineer name=雷军 engineer age=20 } }