【问题标题】:Implement a basic stratergy pattern in c在 c 中实现一个基本的策略模式
【发布时间】:2020-03-05 18:53:06
【问题描述】:

我正在尝试实施一种基本的策略模式来进行理解。我是编程新手。我在下面的代码中做错了什么。

谁能给出一个基本的策略模式的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;
}



【问题讨论】:

  • 你的函数没有使用它们的参数int a。此外,printf(" amount * 0.90") 不进行乘法运算,您不妨使用puts()。不清楚为什么这些函数总是return 3;
  • struct Customer *customer; 是一个未初始化的指针。所以customer-&gt;name="bronze"; 是未定义的行为。

标签: c design-patterns procedural-programming


【解决方案1】:
struct Customer *customer;

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

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

将调用未定义的行为。

您可以将其替换为:

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

【讨论】:

  • 谢谢,我知道了。我为该结构分配了内存,然后它就起作用了。而这个实现是一个正确的策略模式实现示例。好吧,我没有做任何背后的逻辑。我写它只是为了对模式工作有一些基本的了解。但我同意你关于 a 的说法。
  • @madhumadi,很高兴为您提供帮助,感谢您对使用最佳实践和模式的关注,这就是要走的路,
  • 让函数参数未使用不一定是“错误的”。这可能表明存在问题,一些编译器会对此发出警告,但偶尔有充分的理由这样做。
  • 另一方面,关于 OP 的策略函数不使用其参数的说法本身就是不正确的。每个都在其return 语句中使用其参数。
  • @JohnBollinger 问题已编辑,a 之前未使用。我承认“错误”可能太强了,但我看不出在这种情况下使用未使用的参数有什么用处。
猜你喜欢
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
相关资源
最近更新 更多