【C言語によるデザインパターン】Template Method

Template Methodの概要

Template Methodとは,「振る舞いのパターン」の一つ. その目的は,ある一連の処理アルゴリズムを予め決めておいて,そのアルゴリズムの具体的な設計をサブクラスに任せることである.

詳細は下記参考. yusuke-ujitoko.hatenablog.com

Cでの実装

関数ポインタを用いて,処理をラッピングしている

#include <stdio.h>

typedef void (* step1)(void);
typedef void (* step2)(void);
typedef void (* step3)(void);
typedef void (* step4)(void);

struct Drive{
  step1 one;
  step2 two;
  step3 three;
  step4 four;
};

void carStep1(void){printf("車に乗る¥n");}
void carStep2(void){printf("エンジンかける¥n");}
void carStep3(void){printf("周囲を確認¥n");}
void carStep4(void){printf("アクセル踏む¥n");}

void planeStep1(void){printf("飛行機に乗る¥n");}
void planeStep2(void){printf("地上を確認¥n");}
void planeStep3(void){printf("上空を確認¥n");}
void planeStep4(void){printf("離陸する¥n");}

void driveAutomobile(struct Drive drive){
  drive.one();
  drive.two();
  drive.three();
  drive.four();
}

int main(){
  printf("車動かす¥n");
  struct Drive car, plane;
  car.one = carStep1;
  car.two = carStep2;
  car.three = carStep3;
  car.four = carStep4;
  driveAutomobile(car);

  printf("飛行機動かす¥n");
  plane.one = planeStep1;
  plane.two = planeStep2;
  plane.three = planeStep3;
  plane.four = planeStep4;
  rivdeAutomobile(plane);
  return 0;

}

yusuke-ujitoko.hatenablog.com