在c中实现一个基本的策略模式

Implement a basic stratergy pattern in c

我正在尝试实现一个基本的策略模式以供理解。我是编程新手。我在以下代码中做错了什么。

有人可以提前给出策略 pattern.Thanks 的基本 c 实现吗


#include <stdio.h>
#include <stdlib.h>

typedef int (*CustomerPriceStrategy)(int);
int bronzePriceStrategy(int);
int silverPriceStrategy(int);
int goldPriceStrategy(int);


struct Customer
{
 const char* name;
 CustomerPriceStrategy priceStrategy;

};
void placeOrder(struct Customer* customer)
{
    int a;
a=customer->priceStrategy(3);
printf("%d",a);

}

int main(void) {
    struct Customer *customer;
    customer->name="bronze";
    customer->priceStrategy=&bronzePriceStrategy;
    placeOrder(customer);
    return EXIT_SUCCESS;
}
int bronzePriceStrategy(int a)
{
 printf(" 40+ shipping");
 return (a+40);
}
int silverPriceStrategy(int a)
{
 printf(" 25+ shipping");
 return (a+25);
}
int goldPriceStrategy(int a)
{
 /* Free shipping for gold customers. */
 printf(" no shipping fee");
 return a;
}



struct Customer *customer;

是一个未初始化的指针所以:

customer->name="bronze";
customer->priceStrategy=&bronzePriceStrategy;

将调用未定义的行为。

您可以将其替换为:

struct Customer customer;
customer.name="bronze";
customer.priceStrategy=&bronzePriceStrategy;
placeOrder(&customer);