在Android開發中,設計模式是非常重要的一個方面。它們為開發人員提供了一種可復用、可維護和可擴展的解決方案,許多常見的問題已經有了設計模式的解決方案。在本篇文章中,將會介紹在Android開發中常用的設計模式及其應用場景。
一、單例模式
單例模式是一種經典的設計模式,它確保了一個類在任何情況下都只能有一個實例,並提供了一個全局訪問點來訪問該實例。
在Android開發中,單例模式通常用於管理應用程序的全局狀態,例如:應用程序的配置信息、網路連接對象、資料庫連接對象等。
下面是單例模式的示例代碼:
public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
在該示例代碼中,該類的構造函數被聲明為私有的,防止在類外部創建它的實例。在getInstance()方法中,使用double-check locking方式來確保只有在instance為空的情況下才創建對象,並使用volatile修飾符確保線程安全性。
二、觀察者模式
觀察者模式是一種行為型模式,它定義了一種一對多的依賴關係,使得多個觀察者對象可以同時監聽一個主題對象的狀態變化。
在Android開發中,觀察者模式通常用於實現UI的數據更新,例如當一個數據模型的狀態發生變化時,所有觀察該模型的界面可以同時更新。
下面是觀察者模式的示例代碼:
public interface Observer { void onUpdate(Observable observable); } public interface Observable { void addObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(); } public class DataModel implements Observable { private List observers = new ArrayList(); private int data; public int getData() { return data; } public void setData(int data) { if (this.data != data) { this.data = data; notifyObservers(); } } @Override public void addObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.onUpdate(this); } } } public class MainActivity implements Observer { @Override public void onUpdate(Observable observable) { if (observable instanceof DataModel) { DataModel dataModel = (DataModel) observable; // Update UI with new data } } }
在該示例代碼中,DataModel實現了Observable介面,MainActivity實現了Observer介面。當DataModel中的data屬性發生變化時,DataModel會調用notifyObservers()方法通知所有觀察者,包括MainActivity。然後MainActivity可以在onUpdate()方法中更新UI來反映數據的變化。
三、策略模式
策略模式是一種行為型模式,它定義了一系列演算法,將每個演算法都封裝起來,並且使它們可以互換。策略模式讓演算法的變化獨立於使用它的客戶端。
在Android開發中,策略模式通常用於實現複雜演算法或業務邏輯,例如:在表單中實現輸入驗證或者在計算器應用中實現計算功能。
下面是策略模式的示例代碼:
public interface CalculationStrategy { int calculate(int num1, int num2); } public class AddStrategy implements CalculationStrategy { @Override public int calculate(int num1, int num2) { return num1 + num2; } } public class SubtractStrategy implements CalculationStrategy { @Override public int calculate(int num1, int num2) { return num1 - num2; } } public class Calculator { private CalculationStrategy strategy; public Calculator(CalculationStrategy strategy) { this.strategy = strategy; } public int calculate(int num1, int num2) { return strategy.calculate(num1, num2); } public void setStrategy(CalculationStrategy strategy) { this.strategy = strategy; } } // Usage example Calculator calculator = new Calculator(new AddStrategy()); int result = calculator.calculate(5, 3); calculator.setStrategy(new SubtractStrategy()); result = calculator.calculate(5, 3);
在該示例代碼中,AddStrategy和SubtractStrategy類都實現了CalculationStrategy介面,分別實現了加法和減法的演算法。Calculator類使用構造函數來接收一個CalculationStrategy實例,並在calculate()方法中調用該實例的calculate()方法來實現具體的演算法。然後,該類提供了一個setStrategy()方法,可以在運行時動態地更改演算法。
四、建造者模式
建造者模式是一種創建型模式,它將一個複雜對象的構建過程與其表示分離,使得同樣的構建過程可以創建不同的表示。
在Android開發中,建造者模式通常用於創建複雜的對象,例如:AlertDialog等。
下面是建造者模式的示例代碼:
public class AlertDialog { private String title; private String message; private boolean cancelable; private List buttons; private AlertDialog(String title, String message, boolean cancelable, List buttons) { this.title = title; this.message = message; this.cancelable = cancelable; this.buttons = buttons; } public String getTitle() { return title; } public String getMessage() { return message; } public boolean isCancelable() { return cancelable; } public List getButtons() { return buttons; } public static class Builder { private String title; private String message; private boolean cancelable; private List buttons = new ArrayList(); public Builder setTitle(String title) { this.title = title; return this; } public Builder setMessage(String message) { this.message = message; return this; } public Builder setCancelable(boolean cancelable) { this.cancelable = cancelable; return this; } public Builder addButton(AlertDialogButton button) { buttons.add(button); return this; } public AlertDialog build() { return new AlertDialog(title, message, cancelable, buttons); } } } public class AlertDialogButton { private String text; private View.OnClickListener listener; public AlertDialogButton(String text, View.OnClickListener listener) { this.text = text; this.listener = listener; } public String getText() { return text; } public View.OnClickListener getListener() { return listener; } } // Usage example AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle("Title") .setMessage("Message") .setCancelable(false) .addButton(new AlertDialogButton("OK", new View.OnClickListener() { @Override public void onClick(View v) { // Handle button click } })) .addButton(new AlertDialogButton("Cancel", new View.OnClickListener() { @Override public void onClick(View v) { // Handle button click } })) .build(); alertDialog.show();
在該示例代碼中,AlertDialog類聲明了一個Builder類,該類使用流暢介面風格的API來創建AlertDialog對象,並提供了setXXX()方法來設置各種屬性。當所有屬性都設置完成後,調用build()方法來創建AlertDialog對象,這個過程可以看作是具體構建者的實現。Builder類同時也聲明了AlertDialogButton類來實現對按鈕的封裝。然後,通過調用AlertDialog.Builder類的靜態方法,可以使用Builder類創建AlertDialog類的實例。
五、適配器模式
適配器模式是一種結構型模式,它允許不兼容介面之間進行合作。
在Android開發中,適配器模式通常用於顯示列表數據,例如:ListView或RecyclerView中的數據適配器。
下面是適配器模式的示例代碼:
public interface Item { int getItemType(); } public interface ItemViewBinder { void onBindItemView(ItemViewHolder viewHolder, T item); } public class ItemViewHolder extends RecyclerView.ViewHolder { private SparseArray views = new SparseArray(); public ItemViewHolder(View itemView) { super(itemView); } public T getView(int viewId) { View view = views.get(viewId); if (view == null) { view = itemView.findViewById(viewId); views.put(viewId, view); } return (T) view; } } public class MultipleTypeAdapter extends RecyclerView.Adapter { private List items = new ArrayList(); private SparseArray<ItemViewBinder> viewBinders = new SparseArray(); public void register(Class clazz, ItemViewBinder binder) { viewBinders.put(clazz.hashCode(), binder); } public void setItems(List items) { this.items = items; notifyDataSetChanged(); } @Override public int getItemViewType(int position) { return items.get(position).getItemType(); } @NonNull @Override public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { ItemViewBinder binder = viewBinders.get(viewType); View itemView = LayoutInflater.from(parent.getContext()) .inflate(binder.getLayoutRes(), parent, false); return new ItemViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) { Item item = items.get(position); ItemViewBinder binder = viewBinders.get(item.getItemType()); binder.onBindItemView(holder, item); } @Override public int getItemCount() { return items.size(); } } public class TextItem implements Item { private String text; public TextItem(String text) { this.text = text; } @Override public int getItemType() { return TextItem.class.hashCode(); } public String getText() { return text; } } public class TextViewBinder implements ItemViewBinder { @Override public void onBindItemView(ItemViewHolder viewHolder, TextItem item) { TextView textView = viewHolder.getView(R.id.text_view); textView.setText(item.getText()); } @LayoutRes @Override public int getLayoutRes() { return R.layout.item_text; } } // Usage example MultipleTypeAdapter adapter = new MultipleTypeAdapter(); adapter.register(TextItem.class, new TextViewBinder()); List items = new ArrayList(); items.add(new TextItem("Hello, world!")); items.add(new TextItem("Hello, Android!")); adapter.setItems(items); recyclerView.setAdapter(adapter);
在該示例代碼中,Item介面定義列表項,ItemViewBinder介面定義視圖綁定器,負責將Item綁定到RecyclerView.ViewHolder中,而ItemViewHolder則表示ViewHolder對象。MultipleTypeAdapter使用SparseArray保存視圖綁定器,這樣只需要使用Item的類名的hashCode作為key,就可以方便地獲取到它對應的視圖綁定器。
沒有註冊的Item類型將會引發運行時異常,因此最好提供默認的視圖綁定器。然而這個例子沒有提供默認的視圖綁定器,因為它只是用來演示適配器的工作原理。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/184816.html