使用@protocol进行依赖注入?

时间:2012-02-19 21:46:49

标签: objective-c interface protocols

我可以使用@protocol进行类之间的接口吗?我的主要目标是像Java一样进行依赖注入(使用接口和工具)。

我有以下课程:SignUpServiceImpl(其界面名为SignUpService)和ServiceHelperImpl(界面为ServiceHelper)。

我不想将两个实现硬连接在一起,因此我在@protocol中使用了由ServiceHelper实现的ServiceHelperImpl。然后使用SignUpServiceImpl初始化ServiceHelper,如下所示:

- (id)initWithHelper:(ServiceHelper *)myServiceHelper

我正在努力实现的目标是什么?它在Java中看起来更容易....

3 个答案:

答案 0 :(得分:0)

要接受符合协议的对象,init方法应如下所示:

- (id)initWithHelper:(id<ServiceHelper>)myServiceHelper

答案 1 :(得分:0)

如果你想在统一的类接口后面保留许多不同的实现,在Objective-C中执行此操作的一种方法是创建一个抽象类SignUpService,然后在init方法中SignUpService,而不是返回self,您实际上返回了要实现它的类的实例,因此在您的情况下,SignUpServiceImpl

这就像Cocoa中的某些类集群一样,如NSString。

如果您需要更多信息,请与我们联系。

答案 2 :(得分:0)

objc协议与Java接口非常相似。

您的阻止点可能是您希望事物实际上捆绑在一起的方式 - 或协议语法。

宣布协议:

@protocol ServiceHelperProtocol
- (void)help;
@end

在课堂上使用它:

@interface SomeClass : NSObject
- (id)initWithServiceHelper:(id<ServiceHelperProtocol>)inServiceHelper;
@end

@implementation SomeClass

- (id)initWithServiceHelper:(id<ServiceHelperProtocol>)inServiceHelper
{
  self = [super init];
  if (nil != self) {
    [inServiceHelper help];
  }
  return self;
}

@end

MONHelper采用协议:

@interface MONHelper : NSObject < ServiceHelperProtocol > 
...
@end

@implementation MONHelper
- (void)help { NSLog(@"helping..."); }
@end

使用中:

MONHelper * helper = [MONHelper new];
SomeClass * someClass = [[SomeClass alloc] initWithServiceHelper:helper];
...