1.通用校验器接口(validator.h)
#ifndef VALIDATOR_H_INCLUDED
#define VALIDATOR_H_INCLUDED #include<stdbool.h> typedef struct _Validator{
bool (*const validate)(struct _Validator *pThis, int value);
}Validator; typedef struct{
Validator isa; //结构体成员
const int min;
const int max;
} RangeValidator; typedef struct{
Validator isa; //结构体成员
bool isEven;
} OddEvenValidator; bool validateRange(Validator *pThis, int value); // 范围校验器函数
bool validateOddEven(Validator *pThis, int value); // 奇偶校验器函数
#define newRangeValidator(min, max) {{validateRange}, (min), (max)} // 初始化RangeValidator
#define newOddEvenValidator(isEven) {{validateOddEven}, (isEven)} // 初始化OddEvenValidator #endif // VALIDATOR_H_INCLUDED
2.通用校验器接口实现(validator.c)
#include "validator.h" bool validateRange(Validator *pThis, int value)
{
RangeValidator *pRangeValidator = (RangeValidator *)pThis;
return pRangeValidator -> min <= value && value <= pRangeValidator -> max;
} bool validateOddEven(Validator *pThis, int value)
{
OddEvenValidator *pOddEvenValidator = (OddEvenValidator *)pThis;
return (!pOddEvenValidator -> isEven && (value % )) || (pOddEvenValidator -> isEven && !(value % ));
}
3.通用校验器使用范例程序
#include <stdio.h>
#include "validator.h" int main()
{
int num;
RangeValidator rangeValidator = newRangeValidator(, );// 初始化RangeValidator
Validator *pValidator = &rangeValidator.isa;
printf("Pease input an integer: ");
scanf("%d",&num);
printf("\n"); if(pValidator->validate(pValidator,num) == true)
{
printf("The %d in range of 1 to 10\n",num);
}
else
{
printf("The %d not in range of 1 to 10\n",num);
}
printf("\n"); OddEvenValidator oddEvenValidator = newOddEvenValidator(true);// 初始化OddEvenValidator
pValidator = &oddEvenValidator.isa; printf("Pease input an integer: ");
scanf("%d",&num);
printf("\n"); if(pValidator->validate(pValidator,num) == true)
{
printf("The %d is an even.\n",num);
}
else
{
printf("The %d is an odd.\n",num);
}
return ;
}