讀完後我的理解是他讓兩個繼承的類別有上下級關係,可以做階層的應用
public class ApplyRequest {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public abstract class Mall {
protected String name;
protected Mall superior;
public Mall(String name) {
this.name = name;
}
public void setSuperior(Mall superior) {
this.superior = superior;
}
public String getName() {
return name;
}
abstract public String apply(ApplyRequest applyRequest);
}
public class FamilyMark extends Mall {
public FamilyMark(String name) {
super(name);
}
@Override
public String apply(ApplyRequest applyRequest) {
String text;
if ("超商".equals(applyRequest.getType())) {
text = "這是超商類別,執行";
} else {
text = "這不是超商類別,不執行";
if (null != superior) {
superior.apply(applyRequest);
}
}
return text;
}
}
public class Carrefour extends Mall{
public Carrefour(String name) {
super(name);
}
@Override
public String apply(ApplyRequest applyRequest) {
String text;
if ("商場".equals(applyRequest.getType())) {
text = "這是商場類別,執行";
} else {
text = "這不是商場類別,不執行";
if (null != superior) {
superior.apply(applyRequest);
}
}
return text;
}
}
public class JavaTest {
@Test
public void show() {
StringBuilder text;
text = new StringBuilder();
text.append("\n");
Mall familyMark = new FamilyMark("全家");
Mall carrefour = new Carrefour("家樂福");
text.append("店名:");
text.append(familyMark.getName());
familyMark.setSuperior(carrefour);
text.append("\n");
ApplyRequest applyRequest = new ApplyRequest();
applyRequest.setType("超商");
text.append(familyMark.apply(applyRequest));
text.append("\n");
applyRequest.setType("商場");
text.append(familyMark.apply(applyRequest));
assertEquals("測試", text.toString());
}
}