- MVC(Model-View-Controller)模式
- MVP(Model-View-Presenter)模式
- MVVM(Model-View-ViewModel)模式
- Singleton(单例)模式
- Factory(工厂)模式
- Observer(观察者)模式
- Strategy(策略)模式
- Adapter(适配器)模式
这些设计模式都有不同的特点和用途,在开发 Android 应用程序时可以根据具体的需求进行选择。
- MVC(Model-View-Controller)模式
MVC 模式是一种常见的软件设计模式,它主要包含三个部分:模型(Model)、视图(View)和控制器(Controller)。
- 模型(Model):模型层表示应用程序的数据和业务逻辑。它可以包括数据结构、数据库操作、API 调用等。在 Android 中,模型通常由 Java 类或者使用 Room 框架的数据库表示。
- 视图(View):视图层表示用户界面。它可以包括布局、控件、样式等。在 Android 中,视图通常由 XML 布局文件表示。
- 控制器(Controller):控制器层连接模型和视图。它可以处理用户输入、数据更新等操作。在 Android 中,控制器通常由 Activity 或 Fragment 类表示。
示例代码:
以下是一个简单的 Android 应用程序,其中使用了 MVC 设计模式。
模型:
public class UserModel {
private String name;
private int age;
public UserModel(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
视图:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/ageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
控制器:
public class MainActivity extends AppCompatActivity {
private UserModel userModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView nameTextView = findViewById(R.id.nameTextView);
TextView ageTextView = findViewById(R.id.ageTextView);
userModel = new UserModel("Tom", 25);
nameTextView.setText(userModel.getName());
ageTextView.setText(String.valueOf(userModel.getAge()));
}
}