轉接器模式在 Android 開發一定會知道,因為做列表一定會用到,但有其他的情況下會用到 Adapter 嗎?
假如我有兩個會員系統
今天接到一個需求
public interface Carrefour {
String getLevel();
}
public interface Family {
void setAge(int age);
int getAge();
}
public class CarrefourMember implements Carrefour {
@Override
public String getLevel() {
return "Gold";
}
}
public class FamilyMember implements Family {
private int age;
@Override
public void setAge(int age) {
this.age = age;
}
@Override
public int getAge() {
return age;
}
}
public class Adapter implements Carrefour {
private final Family family;
public Adapter(Family family) {
this.family = family;
}
@Override
public String getLevel() {
}
}
public class Adapter implements Carrefour {
private final Family family;
public Adapter(Family family) {
this.family = family;
}
@Override
public String getLevel() {
String level;
if (family.getAge() > 36) {
level = "Old";
} else {
level = "young";
}
return level;
}
}
@Test
public void show() {
//建立老會員
FamilyMember familyOld = new FamilyMember();
familyOld.setAge(40);
Carrefour carrefourOld = new Adapter(familyOld);
String levelOld = carrefourOld.getLevel();
//建立新會員
FamilyMember familyYoung = new FamilyMember();
familyYoung.setAge(25);
Carrefour carrefourYoung = new Adapter(familyYoung);
String levelYoung = carrefourYoung.getLevel();
StringBuilder text = new StringBuilder();
text.append("\n");
text.append("40歲會員等級:");
text.append(levelOld);
text.append("\n");
text.append("25歲會員等級:");
text.append(levelYoung);
text.append("\n");
assertEquals("測試", text.toString());
}
40歲會員等級:Old
25歲會員等級:young