Java設計模式是指在Java語言中使用的一些經典的、被廣泛認可的設計模式。這些模式在很多情況下被稱為設計模式的三大家族:創建型模式、結構型模式和行為型模式。
Android開發中,設計模式也是一個非常重要的概念。Android應用程序中,常常需要對各個組件進行設計,如Activity、Service、BroadcastReceiver、ContentProvider等。Android開發中有很多設計模式可以使用,如MVP、MVC、觀察者模式等。
下面將介紹一些常見的Java設計模式與Android的結合使用:
//單例模式 public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } //建造者模式 public class Person { private final String name; private final int age; private final String gender; private Person(Builder builder) { this.name = builder.name; this.age = builder.age; this.gender = builder.gender; } public static class Builder { private String name; private int age; private String gender; public Builder(String name) { this.name = name; } public Builder age(int age) { this.age = age; return this; } public Builder gender(String gender) { this.gender = gender; return this; } public Person build() { return new Person(this); } } } //策略模式 public interface Strategy { int calculate(int a, int b); } public class AddStrategy implements Strategy { @Override public int calculate(int a, int b) { return a + b; } } public class SubStrategy implements Strategy { @Override public int calculate(int a, int b) { return a - b; } } public class Operation { private Strategy mStrategy; public void setStrategy(Strategy strategy) { mStrategy = strategy; } public int calculate(int a, int b) { return mStrategy.calculate(a, b); } } //觀察者模式 public interface Observer { void onChanged(Object obj); } public interface Observable { void registerObserver(Observer observer); void unregisterObserver(Observer observer); void notifyObservers(Object obj); } public class LoginManager implements Observable { private ListmObservers = new ArrayList<>(); public void login(String username, String password) { // 登錄邏輯 notifyObservers(user); } @Override public void registerObserver(Observer observer) { mObservers.add(observer); } @Override public void unregisterObserver(Observer observer) { mObservers.remove(observer); } @Override public void notifyObservers(Object obj) { for (Observer observer : mObservers) { observer.onChanged(obj); } }
上一篇css在園內填充文字
下一篇css在線實現動畫效果