I am trying to implement a basic strategy pattern for understanding. I am new to programming. what am i doing wrong in the following code.
Can some one give a basic c implementation of strategy pattern.Thanks in adavance
#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;
Is an uninialized pointer so:
customer->name="bronze";
customer->priceStrategy=&bronzePriceStrategy;
Will invoke undefined behavior.
You can replace this by:
struct Customer customer;
customer.name="bronze";
customer.priceStrategy=&bronzePriceStrategy;
placeOrder(&customer);