原型设计模式
原型模式应用场景:创建一个对象比较复杂,当前存在一个和需要创建的对象极其相似,我们就可以采用原型模式,在原来的对象上进行一个修改。
修改方案:在原来的基础上进行拷贝,在进行部分的修改。(具体采用深拷贝和浅拷贝根据具体的业务场景进行选择)就像我们写一段文本时,前面已经写过一段极其相似的文本,我们可以直接拷贝,然后进行修改。提高了写文本的效率。
package com.obstar.prototype;public class MachineStatus {public String stable;public String getStable() {return stable;}public MachineStatus(String stable) {this.stable = stable;}public void setStable(String stable) {this.stable = stable;}@Overridepublic String toString() {return "MachineStatus{" +"stable='" + stable + '\'' +'}';}
}
package com.obstar.prototype;public class Machine implements Cloneable{private String model;private String speed;private String weight;private String power;private MachineStatus status;public Machine(String model, String speed, String weight, String power, MachineStatus status) {this.model = model;this.speed = speed;this.weight = weight;this.power = power;this.status = status;}public MachineStatus getStatus() {return status;}public void setStatus(MachineStatus status) {this.status = status;}public String getModel() {return model;}public void setModel(String model) {this.model = model;}public String getSpeed() {return speed;}public void setSpeed(String speed) {this.speed = speed;}public String getWeight() {return weight;}public void setWeight(String weight) {this.weight = weight;}public String getPower() {return power;}public void setPower(String power) {this.power = power;}@Overridepublic String toString() {return "Machine{" +"model='" + model + '\'' +", speed='" + speed + '\'' +", weight='" + weight + '\'' +", power='" + power + '\'' +", status='" + status + '\'' +'}';}@Overrideprotected Object clone() throws CloneNotSupportedException {Machine machine = (Machine)super.clone();MachineStatus machineStatus = new MachineStatus(this.status.stable);machine.setStatus(machineStatus);return machine;}
}
DEMO:
public class Demo {public static void main(String[] args) throws CloneNotSupportedException {Machine machine1 = new Machine("A19", "3600", "1000KG","5000W", new MachineStatus("稳定"));Machine machine2 = (Machine) machine1.clone();machine2.setModel("A20");System.out.println(machine1);System.out.println(machine2);}
}