Android[進階教程] 設計模式之四 適配器模式

來源:互聯網
上載者:User

這次我們主要來介紹適配器模式,適配器模式主要是根據傳入的物件類型來匹配使用的方法,這裡還是以《西遊記》為主題,詳細介紹一下唐僧每個徒弟使用的武器,孫悟空用"金箍棒",八戒用"九齒釘耙",沙僧用"降妖寶仗",每個人使用的武器都不一樣,這樣就通過適配器的方法來適配每個人使用的武器。好了,接下來我們看代碼,首先定義了一個Person介面,實現了取得名字的方法:

public interface Person {public String getName();}

然後就是三個徒弟類了:

public class Wukong implements Person {@Overridepublic String getName() {return "孫悟空";}}
public class Bajie implements Person {@Overridepublic String getName() {return "八戒";}}
public class Shaseng implements Person {@Overridepublic String getName() {return "沙僧";}}

好,定義好,接下來就是武器類了:

public class Weapon {public Weapon() {}public String getWeapon(Wukong wukong) {return wukong.getName() + "使用金箍棒";}public String getWeapon(Bajie bajie) {return bajie.getName() + "使用九齒釘耙";}public String getWeapon(Shaseng shaseng) {return shaseng.getName() + "使用降妖寶仗";}}

這裡面就對調用的每個對象分別進行了區分。最後就是調用類了:

public class XiyoujiActivity extends Activity {private ListView listView;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);listView = (ListView) findViewById(R.id.listView1);Weapon weapon = new Weapon();ArrayList<String> lists = new ArrayList<String>();lists.add(weapon.getWeapon(new Wukong()));lists.add(weapon.getWeapon(new Bajie()));lists.add(weapon.getWeapon(new Shaseng()));ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, lists);listView.setAdapter(adapter);}}

OK,最後看一下執行的效果呢,


好,接下來,我們對武器類進行重構呢,將傳入的對象進行抽象化,通過判斷每個傳入類的類型來區別武器

public class Weapon {public Weapon() {}public String getWeapon(Person p) {String weapon = null;if (p.getClass() == Wukong.class) {weapon = "使用金箍棒";} else if (p.getClass() == Bajie.class) {weapon = "使用九齒釘耙";} else if (p.getClass() == Shaseng.class) {weapon = "使用降妖寶仗";}return p.getName() + weapon;}}

OK,再運行一下看看呢?是不是結果跟上次的一樣,但這次我們只使用了一個方法,通過這個方法裡的判斷語句確認誰應該用什麼武器。好了,這一章就結束了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.