原文http://geek.csdn.net/news/detail/81154
if语句的缺点:出现if语句的代码会越改越糟,变得越来越难维护。
1.函数参数中有bool变量
实际上是将两个不同的功能绑定到了一个函数中,解决方法是用两个函数代替一个函数。
1)
void foo(int arg0, bool flag)
{
if(flag)
{
do something;
}
else
{
do other thing;
}
}
2)
void foo(int arg0)
{
do something;
}
void goo(int arg0)
{
do other thing;
}
2.swicth case语句
增加新的类型就要增加一个case,可以用多态来实现。
1)
#include <stdio.h>
enum TYPE
{
CAT,
DOG,
};
struct Animal
{
enum TYPE type;
void (*yell)(struct Animal *);// 叫
};
void yell(struct Animal *a)
{
if(a == NULL) return;
switch(a->type)
{
case CAT:
printf("miao wu ~~\n");
break;
case DOG:
printf("wang wang~~\n");
break;
default:
printf("~~~~~~\n");
break;
}
}
int main()
{
struct Animal dog = {DOG, &yell};
dog.yell(&dog);
struct Animal cat = {CAT, &yell};
cat.yell(&cat);
}
2)
#include <stdio.h>
struct Animal
{
void (*yell)(struct Animal *);// 抽象接口叫
};
struct Cat
{
struct Animal a;//继承父类
};
void catYell(struct Animal *a)
{
struct Cat *c = (struct Cat *)a;
printf("miao wu ~ ~\n");
}
struct Dog
{
struct Animal a;//继承父类
};
void dogYell(struct Animal *a)
{
struct Dog *d = (struct Dog *)a;
printf("wang wang ~ ~\n");
}
int main()
{
struct Dog dog = {0};
dog.a.yell = dogYell;
struct Cat cat = {0};
cat.a.yell = catYell;
struct Animal *pa = NULL;
pa = (struct Animal *)&dog;
pa->yell(pa);
pa = (struct Animal *)&cat;
pa->yell(pa);
}
3)
#include <stdio.h>
#include <string.h>
#define offsetOf(CLASS, MEMBER) ((size_t)&(((CLASS *)0)->MEMBER))
#define containerOf(ptr, CLASS, MEMBER) \
({ \
const typeof(((CLASS *)0)->MEMBER) *__mptr = (ptr); \
(CLASS *)((char *)__mptr - offsetOf(CLASS, MEMBER)); \
})
struct Animal
{
void (*yell)(struct Animal *);// 抽象接口叫
};
struct Cat
{
char color[10];
struct Animal a;//继承父类
};
void catYell(struct Animal *a)
{
struct Cat *c = containerOf(a, struct Cat, a);
printf("miao wu , i am a %s cat\n", c->color);
}
struct Dog
{
int speed;
struct Animal a;//继承父类
};
void dogYell(struct Animal *a)
{
struct Dog *d = containerOf(a, struct Dog, a);
printf("wang wang , i can run at the speed of %d km/h~ ~\n", d->speed);
}
int main()
{
struct Dog dog = {0};
dog.speed = 100;
dog.a.yell = dogYell;
struct Cat cat = {0};
strncpy(cat.color, "red", sizeof(cat.color));
cat.a.yell = catYell;
struct Animal *pa[2];
pa[0] = &dog.a;
pa[1] = &cat.a;
int i = 0;
for(i = 0; i < 2; i++)
{
pa[i]->yell(pa[i]);//多态
}
}
3.if语句树
使用逻辑表达式代替
1)
if(a)
{
if(b)
{
}
}
2)
if(a && b)
{
}