我可以使用@protocol来实现类之间的接口吗?我的主要目标是像Java一样做一些依赖注入(使用接口和实现)。
我有以下类:SignUpServiceImpl (它有一个名为SignUpService的接口)和ServiceHelperImpl (接口是ServiceHelper)。
我不想将两个实现硬连接在一起,所以我在ServiceHelper中使用了一个由ServiceHelperImpl实现的@protocol。然后使用ServiceHelper初始化SignUpServiceImpl,如下所示:
- (id)initWithHelper:(ServiceHelper *)myServiceHelper我想要实现的目标有可能实现吗?在Java中看起来要简单得多……
发布于 2012-02-20 06:03:59
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;
}
@endMONHelper采用以下协议:
@interface MONHelper : NSObject < ServiceHelperProtocol >
...
@end
@implementation MONHelper
- (void)help { NSLog(@"helping..."); }
@end使用中:
MONHelper * helper = [MONHelper new];
SomeClass * someClass = [[SomeClass alloc] initWithServiceHelper:helper];
...发布于 2012-02-20 05:58:42
要接受符合协议的对象,init方法应如下所示:
- (id)initWithHelper:(id<ServiceHelper>)myServiceHelper发布于 2012-02-20 06:03:20
如果你想在一个统一的类接口后面保持许多不同的实现,在Objective-C中的一种方法是创建一个抽象类SignUpService,然后在SignUpService的init方法中,你实际上返回一个你想要实现它的类的实例,所以在你的例子中是SignUpServiceImpl。
这就是Cocoa中某些类集群的工作方式,比如NSString。
如果你需要更多信息,请告诉我。
https://stackoverflow.com/questions/9353564
复制相似问题