Epistemology

The truth is out there.

Strategy pattern을 Objective-C 로 만들어봤습니다.

2011-02-10

Head First Design Patterns : 스토리가 있는 패턴 학습법을 읽고, 한번 만들어 봤습니다. 다음 글을 보고, 책에 있는 자바로 만들어진 오리로 만들어 봤습니다. 책을 더 참고하시면 더 확장하실 수 있습니다. 참고로 저는 아직까지 50, 52, 64 번째 줄이 정확히 이해가 안 됩니다. ^^;

How to create a strategy pattern in Objective-C?

 1//
 2// main.m
 3// testing
 4//
 5// Created by Jaehwan on 11. 2. 9..
 6// Copyright 2011 Wireless Air. All rights reserved.
 7//
 8
 9#import
10
11@protocol FlyBehavior
12
13@required
14 (void) fly;
15
16@end
17
18@interface FlyWithWings : NSObject
19{
20// ivars for A
21}
22@end
23
24@implementation FlyWithWings
25
26 (void) fly
27{
28NSLog(@"Fly With Wings!");
29}
30
31@end
32
33@interface FlyNoWay : NSObject
34{
35// ivars for A
36}
37@end
38
39@implementation FlyNoWay
40
41 (void) fly
42{
43NSLog(@"Fly No Way!");
44}
45
46@end
47
48@interface Duck : NSObject
49{
50id flyBehavior;
51}
52@property (assign) id flyBehavior;
53
54 (void) fly;
55
56@end
57
58@implementation Duck
59
60@synthesize flyBehavior;
61
62 (void) fly
63{
64[flyBehavior fly];
65}
66
67@end
68
69int main (int argc, const char * argv[]) {
70
71NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
72// insert code here…
73NSLog(@"Hello, World!");
74
75FlyWithWings * flyWithWings = [[[FlyWithWings alloc] init] autorelease];
76FlyNoWay * flyNoWay = [[[FlyNoWay alloc] init] autorelease];
77Duck * context = [[[Duck alloc] init] autorelease];
78
79
80[context setFlyBehavior:flyWithWings];
81[context fly];
82[context setFlyBehavior:flyNoWay];
83[context fly];
84
85[pool drain];
86return 0;
87}