Android[高級教程] 設計模式之二 策略模式

接上一篇文章,這次我們來講一下策略模式,什麼是策略模式呢?這裡我們還是拿《西遊記》來打比方,唐僧被抓走瞭,就會叫人來救,但誰去救呢?當然是唐僧叫誰去救,誰就去救啦,呵呵,但一般最後都是悟空救出來的。好,讓我們先來看一下UML例圖:

 

 

首先抽象瞭救人的方法,因為每個人救的方法都不同,而唐僧隻要叫人救他就行瞭,他不管你具體怎麼去救,好,我們接下來看代碼:

[java] public interface Person { 
 
    public String save(); 
 

public interface 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.simple_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.simple_list_item_1, lists);
  
  listView.setAdapter(adapter);

 }
}這裡面的界面也隻加瞭個ListView,相信同學們應該都能看懂,最後就是運行過後的圖瞭:

 

 

好瞭,這一章也寫完瞭,謝謝大傢關註。

 

摘自 kangkangz4的專欄

發佈留言