设计模式

This commit is contained in:
罗祥
2019-12-04 16:45:55 +08:00
parent e28071e796
commit f1286d87ae
31 changed files with 438 additions and 0 deletions

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}