从两个类继承 [英] Inherit from two classes

查看:70
本文介绍了从两个类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个通用的iOS应用,即它将在iPhone和iPad上运行.我现在有一个UIViewController,将同时显示在两者上,但有所不同.在iPhone上,它将包含UITableView,在iPad上将包含AQGridView.数据将是相同的.因此,两个控制器将共享许多方法和实例变量.

I am creating an universal iOS app, i.e. it will run on the iPhone and iPad. I now have a UIViewController that will be displayed on both, but differently. On the iPhone, it will contain a UITableView, on the iPad an AQGridView. The data will be the same. Both controllers will therefore share a lot of methods and instance variables.

通常,我将使用方法和实例变量创建一个UIViewController子类,然后创建该类的两个子类,并在其中放置特定于设备的内容.

Usually, I would create a UIViewController subclass with my methods and instance variables and then create two subclasses of this class where I put the stuff specific for the device.

我现在面临的问题是我的子类的iPhone版本也应该使用一些不错的方法从另一个类继承:

The problem I'm facing now is that the iPhone version of my subclass should also inherit from an other class with some nice methods:

            UIViewController sublcass                   Some Other Class
                        |                                      |
            -------------------------------    -----------------
            |                             |    |
      iPad sublcass                 iPhone subclass

无法将iPad版本作为iPhone sublcass的子类添加,因为Some Other Class被设计为与UITableView一起使用.

Adding the iPad version as a subclass of the iPhone sublcass is not possible as Some Other Class is designed to be used with a UITableView.

我非常确定这在Objective-C中是不可能的,但是我想问一遍,然后再创建一个巨大的复制粘贴粘贴混乱.那么:关于如何使我的代码保持简单的任何建议?

I'm pretty sure this is not possible in Objective-C but I wanted to ask before going ahead and creating a huge copy-&-paste mess. So: any suggestions on how to keep my code simple?

推荐答案

是的,在Objective C中不可能进行多重继承.但是,使用简洁,逻辑的设计是没有必要的,可以用协议代替.但是,如果不是这种情况(但是,对此我有一些疑问),建议您检查装饰器设计模式.

Yes, multiple inheritance is not possible in Objective C. However with clean and logical design it is not necessary and could be replaced with protocols. However if it is not the case for you (however, I have some doubts about that) I suggest you to check the decorator design pattern.

即使装饰器模式不能满足您的需求,我还是建议您使用聚合而不是继承(嗯,这就是装饰器实际使用的方式).

Even if decorator pattern doesn't fit your needs I suggest you to use aggregation instead of inheritance (well, that is what decorator actually uses).

这篇关于从两个类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆