2012-02-19 231 views
1

我可以使用@protocol在類之間進行接口連接嗎?我的主要目標是像Java一樣進行一些依賴注入(使用接口和實現)。依賴注入@protocol?

我有以下類:SignUpServiceImpl(它有一個名爲SignUpService的接口)和ServiceHelperImpl(接口是ServiceHelper)。

我不想將兩個實現硬連接在一起,所以我使用@protocol中的ServiceHelper,它由ServiceHelperImpl實現。

- (id)initWithHelper:(ServiceHelper *)myServiceHelper 

就是我要完成的可能:然後SignUpServiceImplServiceHelper這樣的初始化?它看起來是那麼Java中容易得多....

+0

你的目標不明確。 – bneely 2012-02-19 21:49:05

+0

我不知道你在做什麼... – 2012-02-19 21:50:15

回答

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]; 
... 
0

接受符合協議的對象,您init方法應該是這樣的:

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

如果你想保留一些不同的實現在Objective-C中執行此操作的一種方法是創建一個抽象類SignUpService,然後在SignUpServiceinit方法中,不是返回自己,而是實際返回要實現它的類的實例,所以在你的情況下,SignUpServiceImpl

這就是Cocoa中的某些類集羣如NSString的工作方式。

讓我知道你是否需要更多信息。