坦克大战(一期)-设计模式版-prototype模型(不完整版)

DesignPatterns
bingor_yhj 2 years ago
parent a568aa8241
commit b45b55167a

@ -0,0 +1,53 @@
package com.msb.prototype.v1;
/**
* @Author bingor
* @Date 2022-10-18 22:25
* @Description: com.msb.prototype.v1
* @Version: 1.0
*/
public class Person implements Cloneable {
int id;
String name;
Location location;
public Person(int id, String name, Location location) {
this.id = id;
this.name = name;
this.location = location;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
return clone;
}
}
class Location {
String street;
String roomNo;
public Location(String street, String roomNo) {
this.street = street;
this.roomNo = roomNo;
}
@Override
public String toString() {
return "Location{" +
"street='" + street + '\'' +
", roomNo='" + roomNo + '\'' +
'}';
}
}
class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Location location = new Location("机场路", "8号");
Person person1 = new Person(1, "bingor", location);
Person person2 = (Person) person1.clone();
person1.location.street = "龙水路";
System.out.println(person2.location);
}
}

@ -0,0 +1,59 @@
package com.msb.prototype.v2;
/**
* @Author bingor
* @Date 2022-10-18 22:25
* @Description: com.msb.prototype.v1
* @Version: 1.0
*/
public class Person implements Cloneable {
int id;
String name;
Location location;
public Person(int id, String name, Location location) {
this.id = id;
this.name = name;
this.location = location;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
clone.location = (Location) location.clone();
return clone;
}
}
class Location implements Cloneable {
String street;
String roomNo;
public Location(String street, String roomNo) {
this.street = street;
this.roomNo = roomNo;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Location{" +
"street='" + street + '\'' +
", roomNo='" + roomNo + '\'' +
'}';
}
}
class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Location location = new Location("机场路", "8号");
Person person1 = new Person(1, "bingor", location);
Person person2 = (Person) person1.clone();
person1.location.street = "龙水路";
System.out.println(person2.location);
}
}
Loading…
Cancel
Save