设计模式
This commit is contained in:
@ -0,0 +1,24 @@
|
||||
package com.heibaiying.creational.prototype;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class Phone implements Cloneable {
|
||||
|
||||
private String type;
|
||||
|
||||
Phone(String type) {
|
||||
System.out.println("构造器被调用");
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public void call() {
|
||||
System.out.println(type + "拨打电话");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
System.out.println("克隆方法被调用");
|
||||
return super.clone();
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.heibaiying.creational.prototype;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
public class SmartPhone implements Cloneable {
|
||||
|
||||
private String type;
|
||||
private Date productionDate;
|
||||
|
||||
SmartPhone(String type, Date productionDate) {
|
||||
this.type = type;
|
||||
this.productionDate = productionDate;
|
||||
}
|
||||
|
||||
public void call() {
|
||||
System.out.println(type + "拨打电话");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
SmartPhone smartPhone = (SmartPhone) super.clone();
|
||||
smartPhone.productionDate = (Date) smartPhone.productionDate.clone();
|
||||
return smartPhone;
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.heibaiying.creational.prototype;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class ZTest {
|
||||
public static void main(String[] args) throws CloneNotSupportedException {
|
||||
Phone phone = new Phone("3G手机");
|
||||
Phone clonePhone = (Phone) phone.clone();
|
||||
clonePhone.call();
|
||||
|
||||
SmartPhone smartPhone = new SmartPhone("4G手机", new Date());
|
||||
SmartPhone cloneSmartPhone = (SmartPhone) smartPhone.clone();
|
||||
System.out.println(smartPhone == cloneSmartPhone);
|
||||
System.out.println(smartPhone.getProductionDate() == cloneSmartPhone.getProductionDate());
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user