开发者

Android App Architecture: how to share behavior between all screens

开发者 https://www.devze.com 2023-04-10 10:03 出处:网络
Hi fellow Android coders, that\'s a problem I struggle with every time when I make a new app. Imagine you have sub classes of Activity, ListActivity and MapActivity in your app. Now I want that every

Hi fellow Android coders,

that's a problem I struggle with every time when I make a new app. Imagine you have sub classes of Activity, ListActivity and MapActivity in your app. Now I want that every screen has the same options menu showing up when the user clicks the menu button. So I made a BaseActivity with that beh开发者_运维知识库avior. But because Java doesn't allow multiple inheritance I have to write three BaseActivities for every type of Activity. That is ugly because I have three times the same code... The only solution I can think of is make some of the behavior static in one of those BaseActivities and refer to that in the other BaseActivites. But there are still a lot of duplicates... Anyone has a more elegant solution for that problem?

Cheers


This is one of the trade-offs for a single-inheritance language. Rather than duplicating code through inheriting various Activity sub-classes use a delegate. This is also called inheritance by delegation. You will get the features of multiple inheritance without the liabilities.

This is a accomplished by creating a delegate class that has all the shared functionality you'd like then having the "super" class call the delegate. This will still require a small level of copy-and-paste code but it will be minimal. Wikipedia has a good example of the Delegation pattern. If you have a background in C# this form of delegation is similar but not restricted to single methods and for more than events.

0

精彩评论

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

关注公众号