我有以下课程
@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),我该如何实现?如果我使用EncryptedDocument将ExtendedDocument子类化,则默认情况下扩展文档将变为加密。
如何解决这个设计问题?我可以用哪种模式来解决这类问题。看起来我错过了什么。
答案 0 :(得分:1)
您可以在EncryptedDocument初始值设定项中接收中间接口引用。为此,您必须找出在公开要加密的文档信息所需的所有类接口之间的最小接口。 Document可能会发生这种情况。如果没有,您应该创建此接口并从中扩展所有其他接口,或创建协议,并使您的类实现它。然后,只需为EncryptedDocument添加一个专门的初始化程序:
@interface EncryptedDocument
- (id)initWith:(Document*)document;
// whatever else an encrypted document has to expose in its interface ...
@end
这样做的好处是可以保持原始普通文档不受影响,如果您不再需要它,可以将其释放以进行垃圾回收。
但是在这种情况下,您可能希望将实际实现加密的责任(这是算法实现的工作)与EncryptedDocument表示分开,后者更加依赖于此类文档的数据模型。实现这一目标的一种方法是使用策略设计模式并从EncryptedDocument中删除加密工作。也许您可以从层次结构中完全删除EncryptedDocument,更改 encrypt 方法的返回值。但这更多地取决于您的数据模型和应用程序域。 (https://en.wikipedia.org/wiki/Strategy_pattern)。
@interface DocumentCypher
- (id)initWithMethod:(id<CypherMethod>)method;
- (EncryptedDocument*)encrypt:(Document*)plainText;
@end;
但这取决于你要解决的问题的复杂性,更多的是天真的&#34;当需要引入更复杂的行为时,可以轻松地重构简单的解决方案。
答案 1 :(得分:0)
你遗失的是继承不是编程的瑞士军刀。在该特定情况下,诸如Encryptable之类的协议可以帮助支持接口实现并通过参考协议类型来调用对象的实例。请检查以下链接: