c语言中怎么使用模板方法模式
一、什么是模板方法模式
模板方法模式是一种行为型设计模式,它定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。它使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
二、C语言中使用模板方法模式的实现
模板方法模式的实现方式有多种,在C语言中,可以通过定义一个虚函数,然后在模板函数中调用它来实现,具体实现如下:
#include <stdio.h>
//定义抽象类
typedef struct _Abstract
{
void (*TemplateMethod)(struct _Abstract *);
void (*PrimitiveOperation1)(struct _Abstract *);
void (*PrimitiveOperation2)(struct _Abstract *);
}Abstract;
//定义模板函数
void TemplateMethod(Abstract *_this)
{
_this->PrimitiveOperation1(_this);
_this->PrimitiveOperation2(_this);
}
//定义具体子类的具体实现函数
void PrimitiveOperation1(Abstract *_this)
{
printf("PrimitiveOperation1\n");
}
void PrimitiveOperation2(Abstract *_this)
{
printf("PrimitiveOperation2\n");
}
//定义具体子类
typedef struct _Concrete
{
Abstract abstract;
}Concrete;
//定义具体子类的构造函数
void ConcreteCtor(Concrete *_this)
{
_this->abstract.TemplateMethod = TemplateMethod;
_this->abstract.PrimitiveOperation1 = PrimitiveOperation1;
_this->abstract.PrimitiveOperation2 = PrimitiveOperation2;
}
三、C语言中使用模板方法模式的优缺点
C语言中使用模板方法模式可以有效地抽象出一个算法的框架,将一些具体的步骤延迟到子类中去实现,使得子类可以不改变算法的结构即可重定义该算法的某些特定步骤,从而拓展算法的某些步骤。但是,这种实现方式也存在缺点,即每个子类都必须实现抽象类中定义的抽象函数,如果不实现,编译器将报错,这就增加了编程的复杂性。
猜您想看
-
C++ OpenCV特征提取之如何实现Harris角点检测
一、Harri...
2023年05月26日 -
算法中trie怎么实现
Trie的定义...
2023年05月26日 -
LeetCode如何判断随机抽取的扑克牌是否为顺子
中文解答:Le...
2023年07月21日 -
树莓派如何配置
1、准备工作1...
2023年05月26日 -
怎样使用Django suit或Bootstrap美化admin模板
Django提...
2023年07月22日 -
C++11新特性有哪些
1、右值引用和...
2023年05月26日