1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| #import <Foundation/Foundation.h>
typedef enum { kRedColor, kGreenColor, kBlueColor } ShapeColor;
typedef struct { int x, y, width, height; } ShapeRect;
NSString * colorName(ShapeColor color){ switch (color) { case kRedColor: return @"red"; break; case kGreenColor: return @"green"; break; case kBlueColor: return @"blue"; break; } }
@interface Shape : NSObject { ShapeColor color; ShapeRect bounds; }
- (void)setColor:(ShapeColor)color; - (void)setBounds:(ShapeRect)bounds; - (void)draw; @end
@implementation Shape
- (void)setColor:(ShapeColor)c { color = c; } - (void)setBounds:(ShapeRect)b{ bounds = b; } - (void)draw{ } @end
@interface Circle : Shape @end
@implementation Circle
- (void)draw{ NSLog(@"drawing a circle at (%d %d %d %d) in %@", bounds.x, bounds.y, bounds.width, bounds.height, colorName(color)); } @end
@interface Rectangle : Shape @end
@implementation Rectangle
- (void)draw{ NSLog(@"drawing a rectangle at (%d %d %d %d) in %@", bounds.x, bounds.y, bounds.width, bounds.height, colorName(color)); } @end
@interface Egg : Shape @end
@implementation Egg
- (void)draw{ NSLog(@"drawing an egg at (%d %d %d %d) in %@", bounds.x, bounds.y, bounds.width, bounds.height, colorName(color)); } @end
void drawShapes(id shapes[], int count) { for (int i = 0; i < count; i++) { Shape *shape = shapes[i]; [shape draw]; } }
int main(int argc, const char * argv[]) { @autoreleasepool { id shapes[3]; ShapeRect rect0 = {0, 0, 10, 30}; shapes[0] = [Circle new]; [shapes[0] setBounds:rect0]; [shapes[0] setColor:kRedColor]; ShapeRect rect1 = {30, 40, 50, 60}; shapes[1] = [Rectangle new]; [shapes[1] setBounds:rect1]; [shapes[1] setColor:kGreenColor]; ShapeRect rect2 = {60, 70, 80, 90}; shapes[2] = [Egg new]; [shapes[2] setBounds:rect2]; [shapes[2] setColor:kBlueColor]; drawShapes(shapes, 3); } return 0; }
|