Composite composition
In Object-c, a composite is implemented by including an object pointer that is an instance variable. Strictly speaking, only the combination between objects is called compound.
In the case of car models, 1 cars (CAR) require 1 engines and 4 tires (Tire), which do not study the physical models of real tires and engines, but only the class of methods to output the meaning of their respective representatives: The Tires ' objects say they are tires, and the object of the engine says they are engines.
1 @interface Car:nsobject 2 {3 Engine *engine; 4 Tyre *Tire; 5 }6@end//Car
As can be seen from the above code, engine and tire are combined to form car.
1 @interfaceEngine:nsobject2 @end //Engine3 4 @implementationEngine5-(nsstring) descroption6 {7 return(@"I am engine. Vroom");8}//Description9 @end //Engine
Engine class has only one description method
1 @interface Car:nsobject 2 {3 Engine *engine; 4 Tire *tires[4]; 5 }6 -(void) print; 7 @end // Car
Car has an engine object and an array of 4 tire objects that assemble itself in a composite way, and car also has a print method that uses NSLog () to output a description of tires and engines.
Because engine and tires are instance variables of car, they are composite.
Let's take a look at car implementation:
1 @implementationCar2-(ID) Init3 {4 if(self =[Super Init]) {5engine = [engineNew];6tires[0] = [TireNew];7tires[1] = [TireNew];8tires[2] = [TireNew];9tires[3] = [TireNew];Ten } One return(self); A}//InitCar's Init method creates 4 tyres and assigns them to the tires array, and also creates an engine-assigned instance variable. self = [super Init],[super init] assignment to self is a object-c convention, and this is done to prevent objects returned by the superclass during initialization from being inconsistent with the beginning of the creation. Next, the Print method for the car class:
1-(void) Print2 {3NSLog (@"%@", engine);4NSLog (@"%@", tires[0]);5NSLog (@"%@", tires[1]);6NSLog (@"%@", tires[2]);7NSLog (@"%@", tires[3]);8}//Print9 @end//Car
Print is via NSLog
1 int Main (int argc,constChar *argv[])2 {3 car *car; 4 New ]; 5 [car print]; 6 return (0); 7 }//main
After running the program output:
"Object-c Study Notes", chapter 5th compound