面试题答案
一键面试1. 代码结构优化
- 使用协议(Protocols):
- 在Presenter和Interactor之间定义清晰的协议。例如,Presenter向Interactor请求数据时,Interactor遵循一个协议,该协议定义了提供数据的方法。这样Presenter只依赖于协议而不是具体的Interactor类,降低耦合度。
@protocol MyInteractorOutputProtocol <NSObject> - (void)provideDataSuccess:(id)data; - (void)provideDataFailure:(NSError *)error; @end @interface MyInteractor : NSObject @property (nonatomic, weak) id<MyInteractorOutputProtocol> presenter; - (void)fetchData; @end @interface MyPresenter : NSObject <MyInteractorOutputProtocol> - (instancetype)initWithInteractor:(MyInteractor *)interactor; @end
- 依赖注入(Dependency Injection):
- 在Presenter的初始化方法中注入Interactor,而不是在Presenter内部创建Interactor实例。这样在测试Presenter时可以很容易地替换成模拟的Interactor,也使得Presenter与具体的Interactor创建逻辑解耦。
- (instancetype)initWithInteractor:(MyInteractor *)interactor { self = [super init]; if (self) { _interactor = interactor; _interactor.presenter = self; } return self; }
- 分层和模块化:
- 将相关功能进一步拆分到更小的模块中。例如,如果Interactor中有多个不同类型的业务逻辑,可以将其拆分成多个子Interactor,每个子Interactor负责单一的业务逻辑,Presenter与这些子Interactor分别进行通信,使通信逻辑更加清晰。
2. 设计原则遵循
- 单一职责原则(SRP):
- 确保Presenter和Interactor都只负责单一的职责。Presenter专注于处理用户界面相关的逻辑,如更新UI、处理用户交互等;Interactor专注于处理业务逻辑,如数据获取、处理和存储等。避免Presenter或Interactor承担过多职责导致通信复杂。
- 开闭原则(OCP):
- 设计Presenter和Interactor时要考虑到未来的扩展性。例如,当有新的业务逻辑需要添加到Interactor中时,应该通过扩展Interactor类或实现新的协议方法来实现,而不是修改现有的Presenter与Interactor之间的通信代码。
- 迪米特法则(LoD):
- 限制Presenter和Interactor之间的直接交互,只让它们通过必要的接口进行通信。Presenter不应该了解Interactor内部过多的细节,只关心从Interactor获取到的数据或结果,从而降低耦合度。