이 멀티 톤 구현을 objective-c 'elegant'이라고할까요? 프로그래밍 방식으로 '허용되지 않음'인 alloc
및 allocWithZone:
을 사용했는지 여부는 키를 기준으로 메모리를 할당하거나 할당하지 않을 것인지 결정해야하기 때문입니다.Objective C에서 우아하고 정확한 '멀티 톤 구현?
저는 두 인스턴스 만 사용해야하므로지도 대신 'switch-case'를 사용하고 있습니다.
#import "Multiton.h"
static Multiton *firstInstance = nil;
static Multiton *secondInstance = nil;
@implementation Multiton
+ (Multiton *) sharedInstanceForDirection:(enum KeyName)direction {
return [[self allocWithKey:direction] init];
}
+ (id) allocWithKey:(enum KeyName)key {
return [self allocWithZone:nil andKey:key];
}
+ (id) allocWithZone:(NSZone *)zone andKey:(enum KeyName)key {
Multiton **sharedInstance;
@synchronized(self) {
switch (key) {
case KEY_1:
sharedInstance = &firstInstance;
break;
case KEY_2:
sharedInstance = &secondInstance;
break;
default:
[NSException raise:NSInvalidArgumentException format:@"Invalid key"];
break;
}
if (*sharedInstance == nil)
*sharedInstance = [super allocWithZone:zone];
}
return *sharedInstance;
}
+ (id) allocWithZone:(NSZone *)zone {
//Do not allow use of alloc and allocWithZone
[NSException raise:NSObjectInaccessibleException format:@"Use allocWithZone:andKey: or allocWithKey:"];
return nil;
}
- (id) copyWithZone:(NSZone *)zone {
return self;
}
- (id) retain {
return self;
}
- (unsigned) retainCount {
return NSUIntegerMax;
}
- (void) release {
return;
}
- (id) autorelease {
return self;
}
- (id) init {
[super init];
return self;
}
@end
PS : 당신은 어떻게 당신이 오직 두 개의 인스턴스를해야합니다 알고, 또는 않습니다이 아직 작동하지만 깔끔하게 컴파일 : 순서
"key"는 char 대신 enum이어야합니다. –
@David : 고정되어 있습니다! – ArjunShankar