Android[高级教程] 设计模式之六 中介者模式(二)
我们还是接着上一章节的中介者模式,这次我们来重构一下,唐僧只告诉小妖让他的徒弟们来救他,至于小妖通知谁,他不管,反正就是三个徒弟,小妖也想省事,就看见谁就通知谁呗。于是,我们的代码修改成:
[java] public class Monster {
private Person person;
private String message;
public Monster() {
}
public void setPerson(String name) {
if (name.equals("悟空")) {
person = new Wukong();
} else if (name.equals("八戒")) {
person = new Bajie();
} else if (name.equals("沙僧")){
person = new Shaseng();
}
person.setMessage(message);
}
public String getMessage() {
return person.getMessage();
}
public void setMessage(String message) {
this.message = message;
}
}
public class Monster {
private Person person;
private String message;
public Monster() {
}
public void setPerson(String name) {
if (name.equals("悟空")) {
person = new Wukong();
} else if (name.equals("八戒")) {
person = new Bajie();
} else if (name.equals("沙僧")){
person = new Shaseng();
}
person.setMessage(message);
}
public String getMessage() {
return person.getMessage();
}
public void setMessage(String message) {
this.message = message;
}
}首先是小妖的代码,他看见谁就通知谁,至于消息就是唐僧需要转达的消息。接下来看一下唐僧的代码:
[java] public class Tangseng {
private Monster monster;
public void sendMessage(Monster monster, String message) {
this.monster = monster;
monster.setMessage(message);
}
public String getMessage() {
return monster.getMessage();
}
}
public class Tangseng {
private Monster monster;
public void sendMessage(Monster monster, String message) {
this.monster = monster;
monster.setMessage(message);
}
public String getMessage() {
return monster.getMessage();
}
}里面只有小妖这个对象,他只跟小妖接触,只对小妖说话。然后就是悟空的类了:
[java] public class Wukong implements Person {
private String name;
private String message;
public Wukong() {
this.name = "孙悟空";
}
@Override
public void setMessage(String message) {
this.message = message;
}
@Override
public String getMessage() {
return name + "收到" + message;
}
}
public class Wukong implements Person {
private String name;
private String message;
public Wukong() {
this.name = "孙悟空";
}
@Override
public void setMessage(String message) {
this.message = message;
}
@Override
public String getMessage() {
return name + "收到" + message;
}
}
这里三个实现类基本完成了,最后就是调用了,最终实现如下:
[java] public class XiyoujiActivity extends Activity {
private ListView listView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView1);
ArrayList<String> lists = new ArrayList<String>();
Tangseng tangseng = new Tangseng();
Monster monster = new Monster();
tangseng.sendMessage(monster,"'徒弟救我'的消息");
monster.setPerson("悟空");
lists.add(tangseng.getMessage());
monster.setPerson("八戒");
lists.add(tangseng.getMessage());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.易做图_list_item_1, lists);
&nbs
补充:移动开发 , Android ,