开发者

Android OOP design basics

This may be pretty basic, but I've started to lose my grasp on OOP principles...

I want to design a few classes to reduce the amount of code in my main activity class, which has grown to 1000+ lines. (Class for handling UI events, class for message handling, class for alarms/broadcasts, etc).

However, these classes will need access to protected Activity methods, like findViewById.

I don't think it makes sense to design these classes using inheritanc开发者_如何转开发e, because they're not really activities themselves... I'm looking for something like a friend class in java.

Any advice? Sorry if that sounded quite vague.


For GUI applications, one of the most important design patterns you should try to follow is the Model-View-Controller (MVC) pattern.

Android does a good job of leaning toward an MVC style. The Activity can be thought of as the Controller portion and your XML markup is your View portion.

If your new classes make a lot of calls to findViewById, you may not be splitting responsibilities well. If you're doing a lot of view manipulation, you may consider subclassing your View classes and referencing them in your XML. If you're adding a lot of event listeners, you should probably continue to do that in the Activity subclass and, instead, pass the data you retrieved to your helper classes--not the view object itself.


Why don't you just implement message handlers in a separate class and pass "this" (instance of your current class) to that handler class so that you can call these methods. Also have a look at Dependency Injection Design Pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜