用java代码举例MVP和MVVM的具体区别
时间: 2024-04-24 09:25:42 浏览: 96
以下是使用 Java 代码举例 MVP 和 MVVM 的具体区别:
MVP 示例代码:
Model.java:
```java
public class Model {
private String data;
public void setData(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
```
View.java:
```java
public interface View {
void showData(String data);
}
public class MainActivity implements View {
private Presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presenter = new Presenter(this);
presenter.loadData();
}
@Override
public void showData(String data) {
// 在视图中显示数据
textView.setText(data);
}
}
```
Presenter.java:
```java
public class Presenter {
private Model model;
private View view;
public Presenter(View view) {
this.view = view;
this.model = new Model();
}
public void loadData() {
// 从模型获取数据
String data = model.getData();
// 通过视图显示数据
view.showData(data);
}
}
```
MVVM 示例代码:
Model.java:
```java
public class Model {
private MutableLiveData<String> data;
public LiveData<String> getData() {
if (data == null) {
data = new MutableLiveData<>();
// 模拟异步获取数据
fetchData();
}
return data;
}
private void fetchData() {
// 异步获取数据
// ...
// 数据获取成功后更新 LiveData
data.setValue("Hello MVVM");
}
}
```
ViewModel.java:
```java
public class ViewModel extends AndroidViewModel {
private Model model;
public ViewModel(Application application) {
super(application);
model = new Model();
}
public LiveData<String> getData() {
return model.getData();
}
}
```
View.java:
```java
public class MainActivity extends AppCompatActivity {
private TextView textView;
private ViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
viewModel = new ViewModelProvider(this).get(ViewModel.class);
viewModel.getData().observe(this, new Observer<String>() {
@Override
public void onChanged(String data) {
// 在视图中显示数据
textView.setText(data);
}
});
}
}
```
在 MVP 中,Presenter 负责协调 Model 和 View,通过接口将 View 注入到 Presenter 中,Presenter 通过调用 View 的方法来更新视图。而在 MVVM 中,ViewModel 负责协调 Model 和 View,ViewModel 使用 LiveData 来观察数据的变化,一旦数据发生变化,ViewModel 就会通知 View 更新视图。这样,View 不再直接与 Model 交互,而是通过 ViewModel 来获取和展示数据。
阅读全文