#import <Foundation/Foundation.h>
typedef enum {
kCircle,
kRectangle,
kEgg } ShapeType;
typedef enum {
kRedColor,
kGreenColor,
kBlueColor } ShapeColor;
typedef struct{
int x,y,width,height;
} ShapeRect;
typedef struct{
ShapeType type;
ShapeColor fillColor;
ShapeRect bounds;
} Shape;
NSString *colorName (ShapeColor colornamek)
{
switch (colornamek)
{
casekRedColor:
return@"red";
break;
casekGreenColor:
return@"green";
break;
casekBlueColor:
return@"blue";
break;
}
return@"no clue";
}
void drawCircle (ShapeRect bounds,ShapeColor fillColor)
{
NSLog (@"drawing a circle at (%d %d %d %d) in %@",
bounds.x, bounds.y,
bounds.width, bounds.height,colorName(fillColor));
} // drawCircle
void drawRectangle(ShapeRect bounds,ShapeColor fillColor)
{
NSLog(@"drawing a rectangle at (%d %d %d %d) in %@",
bounds.x,bounds.y,
bounds.width,bounds.height,colorName(fillColor));
}
void drawEgg(ShapeRect bounds,ShapeColor fillColor)
{
NSLog(@"drawing a drawEgg at (%d %d %d %d) in %@",
bounds.x,bounds.y,
bounds.width,bounds.height,colorName(fillColor));
}
void drawShapes (Shape shapes[],int count)
{
for (int i =0; i < count; i++){
switch (shapes[i].type) {
casekCircle:
drawCircle (shapes[i].bounds,
shapes[i].fillColor);
break;
casekRectangle:
drawRectangle (shapes[i].bounds,
shapes[i].fillColor);
break;
casekEgg:
drawEgg (shapes[i].bounds,
shapes[i].fillColor);
break;
}
}
} // drawShapes
int main (int argc,constchar * argv[])
{
Shape shapes[3];
ShapeRect rect0 = {0, 0,10, 30};
shapes[0].type =kCircle;
shapes[0].fillColor =kRedColor;
shapes[0].bounds = rect0;
ShapeRect rect1 = {30, 40,50, 60};
shapes[1].type =kRectangle;
shapes[1].fillColor =kGreenColor;
shapes[1].bounds = rect1;
ShapeRect rect2 = {15, 18,37, 29};
shapes[2].type =kEgg;
shapes[2].fillColor =kBlueColor;
shapes[2].bounds = rect2;
drawShapes(shapes,3);
return (0);
} // main
输出结果:
2014-11-30 00:57:08.270 count-1[4765:377292] drawing a circle at (0 0 10 30) in red
2014-11-30 00:57:08.271 count-1[4765:377292] drawing a rectangle at (30 40 50 60) in green
2014-11-30 00:57:08.272 count-1[4765:377292] drawing a drawEgg at (15 18 37 29) in blue
有关术语:
1、类 class 是一种表示对象类型的结构体,对象通过它的类来获取自身的各种信息,尤其是执行每个操作需要运行的代码。
2、对象 object 是一种包含值好的指向其类的隐藏指针的结构体。运行中的程序通常都包含成百上千个对象。指向对象的变量通常不需要首字母大写。
3、实例 instance 是 对象的另一种称呼。
4、消息 message 是对象可以执行的操作,用于通知对象去做什么。在【shape draw】的代码中,通过向shape对象发烧哦给你draw消息来通知对象绘制自身。对象接收消息后,将查询相应的类,以便找到正确的代码来运行。
5、方法 method 是为响应消息而运行的代码。根据对象的类,消息(比如draw)可以调用不同的方法。
6、方法调度 method dispatcher 是objective-c 使用的一种机制,用于推测执行什么方法以响应某个特定的消息。
7、接口 interface 是类为对象提供的特性描述。
8、实现 implementation 是使接口能正常工作的代码。