比如我现在要制作一台电脑,电脑需要CPU,显示器,鼠标和键盘等。这些东西的研发都是很复杂的过程。如果现在有成型的CPU等组件,就可以直接用这些组件攒一台电脑。复合模式就是这样。
习题2
汽车安装发动机和4个轮胎。
(1)定义三个类:汽车类。
(2)定义发动机类,实例变量(品牌、价格)
(3)定义轮胎类,实例变量(品牌、价格、安装位置)。方法:添加防滑链。
(4)给汽车类添加一个实例变量发动机,添加一个数组(使用Tire * tires[4])管理汽车的4个轮胎。
(5)汽车安装发动机和4个轮胎。
工程解析(@public 懒得写set get方法,主要看复合过程)
Engine.h
#import <Foundation/Foundation.h> @interface Engine : NSObject { @public NSString *_Brand; int _Price; } -(void)Run; @end
Engine.m
#import "Engine.h" @implementation Engine -(void)Run { NSLog(@"发动机(品牌%@,价格%d)启动了",_Brand,_Price); } @end
Tire.h
#import <Foundation/Foundation.h> @interface Tire : NSObject { @public NSString *_Brand; int _Price; int _Location; } -(void)install; -(void)Run; @end
Tire.m
#import "Tire.h" @implementation Tire -(void)install { NSLog(@"在%d上安装防滑链",_Location); } -(void)Run { NSLog(@"位置%d,品牌%@,价格%d的轮胎转动",_Location,_Brand,_Price); } @end
Car.h
#import <Foundation/Foundation.h> #import "Engine.h" #import "Tire.h" @interface Car : NSObject { @public NSString *_Brand; int _Price; Engine *_engine; Tire *tires[4]; } -(void)setEngine:(Engine *)Engine; -(Engine *)Engine; //因为是一个数组,set get 写法有变化 -(void)setTire:(Tire *)tire atIndex:(int)index; -(Tire *)tireAtIndex:(int)index; -(void)start;//汽车启动 @end
Car.m
#import "Car.h" @implementation Car -(void)setEngine:(Engine *)Engine { _engine=Engine; } -(Engine *)Engine { return _engine; } -(void)setTire:(Tire *)tire atIndex:(int)index { tires[index]=tire; } -(Tire *)tireAtIndex:(int)index { return tires[index]; } -(void)start { NSLog(@"汽车(品牌%@,价格%d)启动",_Brand,_Price); [_engine Run]; for (int i=0; i<4; i++) { [tires[i] Run]; [tires[i] install]; } } @end
main.m
#import <Foundation/Foundation.h> #import "Car.h" #import "Engine.h" #import "Tire.h" int main(int argc, const char * argv[]) { @autoreleasepool { Car *p=[[Car alloc]init]; p->_Brand=@"Audi"; p->_Price=600000; Engine *p1=[[Engine alloc]init]; p1->_Brand=@"丰田4Y"; p1->_Price=2000; Tire *tires[4]; for (int i=0; i<4; i++) { tires[i]=[[Tire alloc]init]; tires[i]->_Brand=@"固特异"; tires[i]->_Price=500; tires[i]->_Location=i+1; [p setTire:tires[i] atIndex:i]; } [p setEngine:p1]; [p start]; } return 0; }