有一个Baby类,有Cry行为(方法,意为“哭”),Baby可以配一个保姆,但是作为保姆,必须遵守保姆协议:能够处理Baby类Cry的行为。请根据以上描述设计一套代理设计模式(Objective-C)
// Baby.h
#import<Foundation/Foundation.h>
#import"LookAfterBaby.h"
@interface Baby: NSObject
- (void)cry;
@property(nonatomic retain) id<LookAfterBaby> delegate;
@end
// Baby.m
@implementation Baby
- (void)cry
{
[_delegate stopCry];
}
- (void)dealloc
{
[_delegate release];
[super release];
}
@end
//protocol.h
@protocol LookAfterBaby <NSObject>
- (void)stopCry;
@end
// Nanny.h
#import<Foundation/Foundation.h>
#import"LookAfterBaby"
@interface Nanny:NSObject <LookAfterBaby>
@end
// Nanny.m
@implementation Nanny
- (void)stopCry
{
NSLog(@"通过保姆代理,照顾Baby,不让Baby哭");
}
// .m
#import<Foundation/Foundation.h>
#import"LookAfterBaby.h"
#import"Nanny.h"
int main()
{
@autoreleasepool{
Baby *b = [[Baby alloc]init];
Nanny *n = [[Nanny alloc]init];
b.delegate = n;
[b cry];
[n release];
[b release];
}
return 0;
}
电脑上没有装黑苹果,所以不知道程序能不能正常运行,请装了的朋友帮忙运行一下,看程序有没有错误,谢谢!
|
|