MVP(Model-View-Presenter):
MVVM(Model-View-ViewModel):
MVP:
MVVM:
MVP:
MVVM:
MVP:
MVVM:
MVP:
MVVM:
MVP示例:
// View接口
public interface MainView {
void showData(String data);
}
// Presenter
public class MainPresenter {
private MainView view;
private Model model;
public MainPresenter(MainView view, Model model) {
this.view = view;
this.model = model;
}
public void fetchData() {
String data = model.getData();
view.showData(data);
}
}
// View实现
public class MainActivity extends AppCompatActivity implements MainView {
private MainPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Model model = new Model();
presenter = new MainPresenter(this, model);
presenter.fetchData();
}
@Override
public void showData(String data) {
TextView textView = findViewById(R.id.textView);
textView.setText(data);
}
}
MVVM示例:
// ViewModel
class MainViewModel : ViewModel() {
private val _data = MutableLiveData<String>()
val data: LiveData<String> get() = _data
fun fetchData() {
val data = Model.getData()
_data.value = data
}
}
// Activity
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
viewModel.data.observe(this, Observer {
textView.text = it
})
viewModel.fetchData()
}
}
领取专属 10元无门槛券
手把手带您无忧上云