我正在尝试使用 PM 设计(MVC + 演示模型)制作我的应用程序,但我已经坚持如何巧妙地将模型类包装在演示模型类中。现在,我编写了一个简单的代码,其中根据 Model 类实例中的值更改图片和文本。
// Disclaimer:
// View and Controller are merged in this sample for clarity's sake.
枚举
Enum AnimalSpecies {
Dog, Cat, Rabbit, Bird,
}
MVC + RM
class Model extends Observable {
// in my actual code Model has 10+ member variables and most of them are Enum
protected AnimalSpecies species;
protected String name;
protected Object update;
public void setSpecies (AnimalSpecies species) {
this.species = species;
notifyUpdate(species);
}
public void setName (String s) {
this.name = s;
notifyUpdate(name);
}
public void notifyUpdate(Object o) {
this.update = o;
this.setChanged();
this.notifyObservers(update);
}
}
MVC 的 RM + RM
class PresentationModel extends Observable implements Observer {
@Override
public void update(Observable model, Object data) {
// Called when notified by Model
// No idea what to write... but what I want to do is,
// a) determine what text for View to display
// b) determine what pics for View to display,
// based on values of Model.
this.setChanged();
this.notifyObservers(update);
}
}
MVC 的 VC + RM
class View extends Activity implements Observer {
// This is View + Controller, so it'd implement some interfaces like onClickListener,
// and in events such as onClick(), values of Model class are changed,
// but for clarity's sake, I keep everything in onCreate() event.
TextView header;
TextView footer
ImageView imgview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
header = (TextView) findViewById(R.id.header);
footer = (TextView) findViewById(R.id.footer);
imgview = (ImageView) findViewById(R.id.imgview);
Model model = new Model();
PresentationModel pm = new PresentationModel();
model.addObserver(pm);
pm.addObserver(this);
model.setSpecies(AnimalSpecies.Cat);
model.setName("Max");
}
@Override
public void update(Observable pm, Object data) {
// Called when notified by PresentationModel
// *** varies based on parameters from PresentationModel
header.setText(***);
footer.setText(***);
imgview.setImageResource(R.drawable.***);
}
}
我的问题:如何在public void update()
课堂上编写逻辑PresentationModel
?我只能从中得到一个Object
变量NotifyObserver()
,即使是嵌套的switch
or if
... else
,我也根本想不出代码...