今天,我们来实现如下UML,并作为objective-c的第二个例子,介绍如何自己构造类,实现继承,并如何实例化,赋值等:
+--------------------------+
| Phone |
|--------------------------|
| LCDSize |
| Color |
+-------------------------+
| SetLCDSize |
| SetColor |
| Performance |
+--------------------------+
^ ^
| |
| |
+-----------+-------------+ +-+--------------+
| miPhone | | mPearPhone |
|-------------------------| |----------------|
| | | |
| | | |
+-------------------------+ | |
+ | | |
| | +----------------+
| | + |
| Performance | | Performance |
+-------------------------+ | |
+----------------+
代码实现如下:
#import <Foundation/Foundation.h>
typedef enum {
RED,
WHITE,
BLACK
}PHONECOLOR;
NSString *getColorStr(PHONECOLOR c)
{
switch(c)
{
case RED: return @"red";
case WHITE: return @"white";
case BLACK: return @"black";
default: return @"no color";
}
}
@interface Phone: NSObject
{
float LCDSize;
PHONECOLOR color;
}
-(void) SetLCDSize : (float)size;
-(void) SetColor : (PHONECOLOR)c;
@end
@implementation Phone
-(void) SetLCDSize : (float)size
{
LCDSize = size;
}
-(void) SetColor : (PHONECOLOR)c
{
color = c;
}
//empty
-(void) Performance
{
}
@end
//-----iPhone "is a" Phone. it has all feature what a phone posess
@interface iPhone: Phone
@end
@implementation iPhone
-(void) Performance
{
NSLog(@"iPhone performance: LCD-%1.1f Color-%@", LCDSize, getColorStr(color));
}
@end
//----PearPhone "is a" Phone too.
@interface PearPhone: Phone
@end
@implementation PearPhone
-(void) Performance
{
NSLog(@"Pear Phone performance: LCD-%1.1f Color-%@", LCDSize, getColorStr(color));
}
@end
int main(int argc, const char *argv[])
{
PHONECOLOR mcolor = WHITE;
id iphone;
iphone = [iPhone new];
[iphone SetLCDSize: 4.0];
[iphone SetColor: mcolor];
[iphone Performance];
id pearphone;
pearphone = [PearPhone new];
[pearphone SetLCDSize: 4.5];
mcolor = BLACK;
[pearphone SetColor: mcolor];
[pearphone Performance];
return (0);
}