iOS 中的多重继承设计问题

Multiple inheritance design issue in iOS

我有以下类

@interface Document : NSObject
//Root document
@end

@interface ExtendedDocument1 : Document
//sublcass of document, with specific behaviour
@end

@interface ExtendedDocument2 : Document
 //sublcass of document, with specific behaviour
@end

@interface EncryptedDocument : Document
//Supports encryption of document
@end

如果我想加密ExtendedDocument(1/2),我该如何实现?如果我将 ExtendedDocument 子类化为 EncryptedDocument,则扩展文档将默认加密。

如何解决这个设计问题?我可以使用哪种模式来解决此类问题。看来我错过了什么。

你缺少的是继承不是编程的瑞士军刀。在这种特定情况下,诸如 Encryptable 之类的协议可以帮助支持接口实现并通过引用协议类型来调用对象的实例。检查以下 link:

Working with Protocols

您可以在 EncryptedDocument 初始值设定项中收到中间接口引用。为此,您必须找出在所有 class 接口之间哪个接口是最低限度的,足以公开要加密的文档的信息。 Document 可能会完成这项工作。如果没有,您应该创建此接口并从中扩展所有其他接口,或者创建一个协议,并让您的 classes 实现它。然后,只需为 EncryptedDocument 添加一个专门的初始化器:

@interface EncryptedDocument
- (id)initWith:(Document*)document;
// whatever else an encrypted document has to expose in its interface ...
@end

这样做的好处是可以保持原来的普通文档不受影响,如果您不再需要它,可以将其释放以进行垃圾回收。

但在这种情况下,您可能希望将实际实现加密的责任(算法实现的工作)与 EncryptedDocument 表示分开,后者更依赖于此类文档的数据模型。实现这一目标的一种方法是采用策略设计模式并从 EncryptedDocument 中删除加密工作。也许您可以从层次结构中完全删除 EncryptedDocument,更改下面 encrypt 方法的 return 值。但这更多取决于你的数据模型和应用领域。 (https://en.wikipedia.org/wiki/Strategy_pattern).

@interface DocumentCypher
- (id)initWithMethod:(id<CypherMethod>)method;
- (EncryptedDocument*)encrypt:(Document*)plainText;
@end;

但这取决于您要解决的问题的复杂性,当需要引入更复杂的行为时,"naive"和简单的解决方案越容易重构。