Android[高级教程] 设计模式之二 策略模式
接上一篇文章,这次我们来讲一下策略模式,什么是策略模式呢?这里我们还是拿《西游记》来打比方,唐僧被抓走了,就会叫人来救,但谁去救呢?当然是唐僧叫谁去救,谁就去救啦,呵呵,但一般最后都是悟空救出来的。好,让我们先来看一下UML例图:
首先抽象了救人的方法,因为每个人救的方法都不同,而唐僧只要叫人救他就行了,他不管你具体怎么去救,好,我们接下来看代码:
[java] public inte易做图ce Person {
public String save();
}
public inte易做图ce Person {
public String save();
}这是抽象方法,每个具体类都要去实现这个方法
接下来就是具体类了,首先是悟空
[java] public class Wukong implements Person {
@Override
public String save() {
return "大徒弟孙悟空来救师傅";
}
}
public class Wukong implements Person {
@Override
public String save() {
return "大徒弟孙悟空来救师傅";
}
}接下来是八戒
[java] public class Bajie implements Person {
@Override
public String save() {
return "二徒弟猪八戒来救师傅";
}
}
public class Bajie implements Person {
@Override
public String save() {
return "二徒弟猪八戒来救师傅";
}
}最后就是沙僧
[java] public class Shaseng implements Person {
@Override
public String save() {
return "三徒弟沙僧来救师傅";
}
}
public class Shaseng implements Person {
@Override
public String save() {
return "三徒弟沙僧来救师傅";
}
}好了,三个具体类都完成了救人的方法,接下去就是唐僧了
[java] public class Tangseng {
public String help(Person p) {
return p.save();
}
}
public class Tangseng {
public String help(Person p) {
return p.save();
}
}
唐僧会喊悟空,八戒,沙僧来救我,那听到的就会去救他,呵呵,最后就是Android中的实现了
[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);
Tangseng tangseng = new Tangseng();
ArrayList<String> lists = new ArrayList<String>();
lists.add(tangseng.help(new Wukong()));
lists.add(tangseng.help(new Bajie()));
lists.add(tangseng.help(new Shaseng()));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.易做图_list_item_1, lists);
listView.setAdapter(adapter);
}
}
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);
Tangseng tangseng = new Tangseng();
ArrayList<String> lists = new ArrayList<String>();
lists.add(tangseng.help(new Wukong()));
lists.add(tangseng.help(new Bajie()));
lists.add(tangseng.help(new Shaseng()));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.易做图_list_item_1, lists);
listView.setAdapter(adapter);
}
}这里面的界面也只加了个ListView,相信同学们应该都能看懂,最后就是运行过后的图了:
好了,这一章也写完了,谢谢大家关注。
摘自 kangkangz4的专栏
补充:移动开发 , Android ,