简体   繁体   中英

What is the optimal way to share code between Activities with different base classes?

I have the following problem:
I have an abstract Activity class, lets call it MyAbstractActivity , that contains some code I'd like to reuse (for example: a standard service binder, common menu items, common initialization code, etc. etc.). Normally I would just use it to subclass my concrete activities and be done with it.

However, I occasionally need to use another supertype, such as a ListActivity or a MapActivity .

So the question is: how do I avoid duplicating that support code within an Activity, if I have to use another base class?

I have thought up of a solution based on the decorator pattern, like this one:
活动装饰器 .

However, I see a problem with this approach: What to do with protected methods (like onCreate() )? Should I introduce an additional "bridge" class that makes them public for the purpose of the decorator, similarly to the way presented below (starting to look a bit byzantine...)?

边缘情况

Any other way?

I hope I made myself relatively clear. Thanks in advance for any feedback!

PS. Using static utility classes is not a good solution in my opinion, since it introduces a possibility of hard-to-identify programming bugs.

If I understand correctly, neither Fragments nor the Decorator Pattern are clean or appropriate solutions for what you want to accomplish. They were designed to solve other problems.

I find myself moving "support" code, or "framework" code, or "all that verbose, repetitive, boilerplate crap" to static utility methods. This isn't necessarily the approach I'd take on a non-Android project, but in my Android projects, it works pretty darn well.

Also, know that you don't need to subclass ListActivity to have a ListView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM