复合:将多个组件组合在一起,形成一个整体,然后使用整体来进行工作,这种组合行为称为复合
复合后的整体功能更加强大
编写一个房屋类,由门,窗户等组成,门和窗有自己的开关方法,然后将门和窗这些复合在一起称为房屋类 调用房屋类的进出方法实际调用到门的开关 调用房屋的换气方法,实际调用到窗户的开关
// 由多个类的对象组成一个大类,就是一个组合的过程 #import <Foundation/Foundation.h> #import "Widow.h" #import "Door.h" @interface House : NSObject @property (nonatomic, strong) Door *door; @property (nonatomic, strong) Widow *widow; -(void)inouthouse; -(void)exchangair; @end
#import "House.h" @implementation House -(void)inouthouse{ [_door open ];NSLog(@"进屋"); [_door close]; NSLog(@"出屋"); } -(void)exchangair{ [_widow open]; NSLog(@"开始换气"); [_widow close]; NSLog(@"换气结束"); } @end
#import <Foundation/Foundation.h>
@interface Widow : NSObject -(void)open; -(void)close; @end #import "Widow.h" @implementation Widow -(void)open{ NSLog(@"开窗"); } -(void)close{ NSLog(@"关窗"); } @end
#import <Foundation/Foundation.h> @interface Door : NSObject -(void)open; -(void)close; @end #import "Door.h" @implementation Door -(void)open{ NSLog(@"开门"); } -(void)close{ NSLog(@"关门"); } @end
#import <Foundation/Foundation.h> #import "House.h" int main(int argc, const char * argv[]) { @autoreleasepool { House *h=[[House alloc]init]; h.door=[[Door alloc]init]; h.widow=[[Widow alloc]init]; [h inouthouse]; [h exchangair]; } return 0; }
时间: 2024-10-24 12:33:08