What's the right way to Object Orient an Android Program?
I've watched many tutorials now about how to program for Android - I have even started to create some programs myself. However, I noticed my programs all look like procedural ones, while Java should be working with object orientation. I have been trying to fix this, but I've found a problem. The primary class of my program - the one that's executed at the start of the application (under com.testprogram.www for example) seems to be a mixture of screen and control layers at the same time.
On all tutorials I found, I see a visual object being recovered from the main.xml
view (for example, 开发者_如何学JAVAa button - this recovery indicates to me that this would be the 'control' layer for treatment) and just after this the object is registered to a listener of some sort (in this case OnClickListener
- this should be done in the screen, not in the control, right?).
Is this meant to be this way? This main class under the www package is what? The 'screen' layer or the 'control' one? Is this class the right place to do what I mentioned above? Is this done this way because the XML-based interface is unable to register Java listeners? Anyone knows a good place for me to go for references on how to OO for Android?
If you use the standard patterns of layout as xml, strings in strings.xml, activity for handlers and place the core logic/algorithms/data store-retrieval in a separate class (the model class) you will be well on your way to writing better code.
To test your architecture,
1) Ask yourself if you can do a unit test on the core logic/algorithm/data store (the model class) separate from the UI. Can you reuse the model class in another project with a different UI without difficulty?
2) Then ask yourself if you could port your app to another language by simply supplying an optional strings.xml file.
So the presentation (View) is primarily in main.xml. The event and system handling code (Controller) is primarily in MyActivity.java The algorithm/data store is primarily in Model.java.
The really big separation is between the core algorithm/data store and the user interface. The core algorithm/data store should be ignorant of details of the user interface. In UNIX this is the INTERFACE (VC)-ENGINE (M) pattern. Separating out the View from the Controller just takes the architecture one step further.
Hope that helps, JAL
You can check two question regarding two different architecture patterns.
- MVC
- MVP
Here are a couple of discussions on the MVC pattern in Android:
MVC pattern on Android
http://groups.google.com/group/android-developers/browse_thread/thread/1c84f6320d007c00?pli=1
MVVM with it's use of Binding is very helpful in Android Programming. It helps lessen the overloaded Activity structure that currently exists in the infrastructure. Below is an open source Binding lib that you can use.
http://code.google.com/p/android-binding/wiki/Motivation
精彩评论