deep copy, swallow copy
This commit is contained in:
28
design-pattern/src/Prototype/copy/Age.java
Normal file
28
design-pattern/src/Prototype/copy/Age.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package Prototype.copy;
|
||||
|
||||
public class Age {
|
||||
|
||||
private int year;
|
||||
private int value;
|
||||
|
||||
public Age(int year, int value) {
|
||||
this.year = year;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(int year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
29
design-pattern/src/Prototype/copy/Cat.java
Normal file
29
design-pattern/src/Prototype/copy/Cat.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package Prototype.copy;
|
||||
|
||||
public class Cat implements Cloneable{
|
||||
|
||||
private String name;
|
||||
private Age age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Age getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Age age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Cat copy() throws CloneNotSupportedException {
|
||||
Cat cat = (Cat) this.clone();
|
||||
cat.setAge(new Age(this.age.getYear(), this.age.getValue()));
|
||||
return cat;
|
||||
}
|
||||
}
|
||||
21
design-pattern/src/Prototype/copy/Main.java
Normal file
21
design-pattern/src/Prototype/copy/Main.java
Normal file
@@ -0,0 +1,21 @@
|
||||
package Prototype.copy;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) throws CloneNotSupportedException {
|
||||
|
||||
Cat navi = new Cat();
|
||||
navi.setName("navi");
|
||||
navi.setAge(new Age(2018, 3));
|
||||
|
||||
Cat tom = navi.copy();
|
||||
tom.setName("tom");
|
||||
tom.getAge().setYear(2020);
|
||||
tom.getAge().setValue(1);
|
||||
|
||||
System.out.println(navi.getName());
|
||||
System.out.println(navi.getAge().getYear());
|
||||
System.out.println(tom.getName());
|
||||
System.out.println(tom.getAge().getYear());
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user