type-safe enum pattern
- From: Brieuc Desoutter
- Date: Sun, 29 Jul 2007 14:28:16 +0200
Hi everyone,
Does anybody has ever implemented some kind of type-safe enum pattern in Objective-C, like the one used in Java before the introduction of Enums in the language.
The idea is to have something similar to C enums but with object members instead of integers. For instance, I'd like to have a enum for length units whose member are instances of a LengthUnit class.
The requirements are :
1) The enums should allow access a enum member by name like :
LengthUnit *mile = [LengthUnit mile];
2) The enums should allow user to retrieve all members like :
NSArray *lengthUnits = [LengthUnit members];
3) It should not be possible to create new members of an enum type.
// should generate a compile time error
LengthUnit *newUnit = [[LengthUnit alloc] initWithName:@"my unit" symbol:@"U" toMeters:0.0.254"];
I've looked at the Class Cluster pattern but it seems better suited for "value" objects.
I've come up with a partial solution which is not really satisfying :
1) I defined protocols Unit and LengthUnit to prevent member object creation :
@protocal Unit
- (NSString*)name;
- (NSString*)symbol;
@end
@protocol LengthUnit <Unit>
- (double)toMeters:(double)value;
- (double)fromMeters:(double)value;
@end
2) I defined a class LengthUnits as follow :
@interface LengthUnits : NSObject
+ (id<LengthUnit>)meter;
+ (id<LengthUnit>)foot;
+ (id<LengthUnit>)mile:
+ (id<LengthUnit>)fathom;
....
@end
3) The implementations of LengthUnits static methods meter, foot, .... return instances of a "private" class to conform to the LengthUnit protocol
However I not quite satisfied with this ( the use involved ids instead of typed pointer to LengthUnit ), it doesn't implement the members method, and it might have a lot of default I've overlooked...
If anyone as a better solution, I would really appreciate if he could share it.
thanks
Brieuc
.
- Prev by Date: Re: windowDidLoad won't get called
- Next by Date: Re: windowDidLoad won't get called
- Previous by thread: Re: windowDidLoad won't get called
- Next by thread: Simplest bridge between JavaScript and SQLite
- Index(es):
Relevant Pages
|