OC学习 第四章 复合
复合: 由多个类的对象组成一个大类,就是一个组合的过程。(也就是一个类的属性是另外一个类的对象)
例如:编写一个房屋类,由门,窗户等组成,门和窗户有自己的开关方法,然后将门和窗户这些复合在一起成为房屋类调用房屋类的进出方法实际调用到门的开关调用房屋的换气方法,实际调用到窗户的开关提供属性。
#import <Foundation/Foundation.h>
#import "Door.h"
#import "Window.h"
@interface House : NSObject
@property (nonatomic, strong) Door *door;
@property (nonatomic, strong) Window *window;
-(void)inHouse;
-(void)outHouse;
-(void)changeAir;
@end
#import "House.h"
@implementation House
-(void)inHouse{
NSLog(@"进屋");
[_door open];
}
-(void)outHouse{
NSLog(@"出屋");
[self.door close];
}
-(void)changeAir{
[_window open];
NSLog(@"开始换气");
[_window close];
NSLog(@"换气结束");
}
@end
#import <Foundation/Foundation.h>
@interface Door : NSObject
@property (nonatomic, strong) NSString *color;
-(void)open;
-(void)close;
@end
#import "Door.h"
@implementation Door
-(void)open{
NSLog(@"开门");
}
-(void)close{
NSLog(@"关门");
}
@end
#import <Foundation/Foundation.h>
@interface Window : NSObject
-(void)open;
-(void)close;
@end
#import "Window.h"
@implementation Window
-(void)open{
NSLog(@"开窗户");
}
-(void)close{
NSLog(@"关窗户");
}
@end