Android OOP 设计基础
这可能是非常基本的,但我已经开始失去对 OOP 原则的掌握...
我想设计一些类来减少我的主要活动类中的代码量,该类已增长到 1000 多行。 (用于处理 UI 事件的类、用于消息处理的类、用于警报/广播的类等)。
但是,这些类需要访问受保护的 Activity 方法,例如 findViewById。
我认为使用继承来设计这些类是没有意义的,因为它们本身并不是真正的活动...我正在寻找类似于java中的友元类的东西。
有什么建议吗?抱歉,如果这听起来很模糊。
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 inheritance, 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 GUI 应用程序,您应该尝试遵循的最重要的设计模式之一是 模型-视图-控制器 (MVC) 模式。
Android 在倾向于 MVC 风格方面做得很好。活动可以被认为是控制器部分,而 XML 标记是视图部分。
如果您的新类对 findViewById 进行大量调用,您可能无法很好地划分职责。如果您正在进行大量视图操作,您可以考虑 对您的视图进行子类化类并在 XML 中引用它们。如果要添加大量事件侦听器,您可能应该继续在 Activity 子类中执行此操作,并将检索到的数据传递给帮助器类,而不是视图对象本身。
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.
为什么不在一个单独的类中实现消息处理程序并将“this”(当前类的实例)传递给该处理程序类,以便您可以调用这些方法。
另请参阅依赖注入设计模式。
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.