gpt4 book ai didi

c# - C#中的工厂模式

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:35 25 4
gpt4 key购买 nike

我有点理解工厂模式并想出了这个实现。

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the fruit name to get the Fruit!");
string fruit = Console.ReadLine();

FruitsList fruits;
if (Enum.TryParse(fruit, true, out fruits))
{
var fruitWeight = GetFruitWeight(fruits);
Console.ReadLine();
}
else
{
Console.WriteLine("Fruit Name is undefined!");
Console.ReadLine();
}
}

private static object GetFruitWeight(FruitsList fruitNumber)
{
switch (fruitNumber)
{
case FruitsList.Banana:
return new Banana();
case FruitsList.Apple:
return new Apple();
}

return null;
}
}

internal class Banana : IFruits
{
public float ReturnFruitWeight()
{
return (float)10.00;
}
}

public interface IFruits
{
float ReturnFruitWeight();
}

public class Apple : IFruits
{
public float ReturnFruitWeight()
{
return (float)30.00;
}
}

public enum FruitsList
{
Apple,
Banana,
}

我的整个想法(从理论上的理解)是 GetFruitWeights 函数应接受枚举类型,然后返回水果重量。我能够获得特定 Fruit 的对象,但现在无法从 Fruit 对象获得水果的重量。

此外,添加到我的疑惑列表中,我是否真的在这个实现中遵循了工厂模式?而且,互联网上的一些资料也使用抽象类?我应该遵循什么?接口(interface)实现还是应该使用抽象类并重写它?

预先感谢您的帮助。

最佳答案

如果您不打算在返回时使用 fruit 对象,那么我会直接返回重量而不是 fruit 对象。工厂方法名称实际上确实说它返回重量,而不是对象,所以理论上这是正确的方法,即

const float AppleWeight = 10;
const float BananaWeight = 10.4;
...
public static float GetFruitWeight(FruitList fruitType)
{
switch (fruitType)
{
case FruitsList.Apple:
return AppleWeight;
case FruitsList.Banana:
return BananaWeight;
default:
return 0;
}
}

但是,如果您打算使用 fruit 对象,那么我会将您的方法重命名为 GetFruit,返回 IFruits(不要框)并在 fruit 实例上调用 ReturnFruitWeight 以获得重量。

Am I really following Factory pattern in this implementation?

工厂模式的要点是允许您在不知 Prop 体类型的情况下创建对象,所以是的,您这里拥有的是工厂方法模式的一个相当基本的示例。

some materials in the internet uses an abstract class too ? What should I follow ? A interface implementation or should I use an abstract class and override it ?

这完全取决于您的应用程序设计。例如,我个人只会在以下情况下引入抽象基类:

  • 我可以在类(class)间共享通用代码
  • 我需要一些方法来确定特定类属于特定类型的家族,即香蕉是一种水果

除此之外,我可能几乎总是选择接口(interface)类型方法。请记住,您可以同时拥有两者,没有理由不能拥有支持特定接口(interface)的抽象基类...

关于c# - C#中的工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16394724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com