factoryMethod

来源:互联网 发布:asp商城网站系统源码 编辑:程序博客网 时间:2024/06/05 07:31
factory.h//****************************************/*define operate abstract class*/typedef struct _operate{int numA;int numB;int(*getresult)(struct _operate *this);}Operate;/*declare concrete operate method*/int get_add_result(struct _operate *this);int get_sub_result(struct _operate *this);int get_mul_result(struct _operate *this);int get_div_result(struct _operate *this);/*define concrete operate subclass*/struct _add{Operate operate;}Add = {0,0,get_add_result};struct _sub{Operate operate;}Sub = {0,0,get_sub_result};struct _mul{Operate operate;}Mul={0,0,get_mul_result};struct _div{Operate operate;}Div={0,0,get_div_result};/*implement operate method*/int get_add_result(struct _operate *this){return this->numA+this->numB;}int get_sub_result(struct _operate *this){return this->numA-this->numB;}int get_mul_result(struct _operate *this){return this->numA*this->numB;}int get_div_result(struct _operate *this){return this->numA/this->numB;}//************************************//************************************/*define factory method interface*/typedef struct _opt_factory{Operate *(*creat_operate)(struct _opt_factory *this);}Ifactory;/*declare factory method*/Operate *pro_add();Operate *pro_sub();Operate *pro_mul();Operate *pro_div();/*define concrete operate factory class*/struct _add_factory{Ifactory add_factory;}Add_factory={.add_factory=pro_add};struct _sub_factory{Ifactory sub_factory;}Sub_factory={pro_sub};struct _Mul_factory{Ifactory mul_factory;}Mul_factory={pro_mul};struct _div_factory{Ifactory div_factory;}Div_factory={pro_div};/******************************************implement concrete factory method*******************************************/ Operate *pro_add(){struct _add *add = (struct _add *)malloc(sizeof(struct _add));memset(add,0,sizeof(struct _add));add->operate.getresult = get_add_result;return add;}Operate *pro_sub(){struct _sub *sub = (struct _sub *)malloc(sizeof(struct _sub));memset(sub,0,sizeof(struct _sub));sub->operate.getresult = get_sub_result;return sub;}Operate *pro_mul(){struct _mul *mul = (struct _mul *)malloc(sizeof(struct _mul));memset(mul,0,sizeof(struct _mul));mul->operate.getresult = get_mul_result;return mul;}Operate *pro_div(){struct _div *div = (struct _div *)malloc(sizeof(struct _div));memset(div,0,sizeof(struct _div));div->operate.getresult = get_div_result;return div;}

main.c

#include<stdio.h>#include<stdlib.h>#include"factory.h"void main(){#if 0struct _operate *opt = &Add;opt->numA = 3;opt->numB = 6;printf("ret is %d\n",opt->getresult(opt));#endifIfactory *factory = NULL; factory = (Ifactory *)&Mul_factory;Operate *operate = factory->creat_operate(factory);operate->numA = 2;operate->numB = 9;printf("%d\n",operate->getresult(operate));}




0 0
原创粉丝点击