Skip to content

Commit

Permalink
add code
Browse files Browse the repository at this point in the history
  • Loading branch information
VentureQ committed Jul 8, 2021
1 parent c907562 commit 90e49c4
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
32 changes: 32 additions & 0 deletions code/Design_Pattern/原型模式/Computer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package Design_Pattern.原型模式;

//浅复制
public class Computer implements Cloneable{
private String cpu;
private String memory;
private String disk;

public Computer(String cpu, String memory, String disk) {
this.cpu = cpu;
this.memory = memory;
this.disk = disk;
}

@Override
public String toString() {
return "Computer{" +
"cpu='" + cpu + '\'' +
", memory='" + memory + '\'' +
", disk='" + disk + '\'' +
'}';
}

public Object clone(){
try {
return (Computer)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
52 changes: 52 additions & 0 deletions code/Design_Pattern/原型模式/ComputerDetail.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package Design_Pattern.原型模式;

public class ComputerDetail implements Cloneable{
private String cpu;
private String memory;
private Disk disk;

public ComputerDetail(String cpu, String memory, Disk disk) {
this.cpu = cpu;
this.memory = memory;
this.disk = disk;
}

@Override
public String toString() {
return "ComputerDetail{" +
"cpu='" + cpu + '\'' +
", memory='" + memory + '\'' +
", disk=" + disk +
'}';
}

public Object clone(){
try {
ComputerDetail computerDetail= (ComputerDetail) super.clone();
computerDetail.disk=(Disk) this.disk.clone();
return computerDetail;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}


class Disk implements Cloneable{
private String ssd;
private String hhd;

public Disk(String ssd, String hhd) {
this.ssd = ssd;
this.hhd = hhd;
}
public Object clone(){
try {
return (Disk)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
15 changes: 15 additions & 0 deletions code/Design_Pattern/原型模式/Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package Design_Pattern.原型模式;

public class Test {
public static void main(String[] args) {
Computer computer=new Computer("8core","16G","1TB");
Computer computerClone=(Computer) computer.clone();
Disk disk=new Disk("28G","2TB");

ComputerDetail computerDetail=new ComputerDetail("12core","64G",disk);
System.out.println(computerDetail);

ComputerDetail computerDetailClone=(ComputerDetail) computerDetail.clone();
System.out.println(computerDetailClone);
}
}

0 comments on commit 90e49c4

Please sign in to comment.