gpt4 book ai didi

C#:开关与工厂类中的方法重载

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

给定的类:

enum ThingEnum { A,B,C}

interface IThing { }

class A : IThing { }

class B : IThing { }

class C: IThing { }

我脑子里有两个 IThingFactory 的实现。一个使用 switch:

class ThingFactory
{
public IThing MakeThing(ThingEnum type)
{
switch (type)
{
case ThingEnum.A:
return new A();
break;
case ThingEnum.B:
return new B();
break;
case ThingEnum.C:
return new C();
break;
default:
break;
}
}
}

另一个使用抽象和方法重载:

class ThingFactory
{
public IThing Make(A a)
{
return new A();
}

public IThing Make(B a)
{
return new B();
}

public IThing Make(C a)
{
return new C();
}
}

我的问题是:

  1. 哪个实现更快,
  2. 哪个更易读/更容易理解,
  3. 你会使用哪个?为什么?

最佳答案

我真的建议您将其作为 IoC 容器。无论如何,也许您只是想在某些类中确保 .ctor 之后的类发生某些事情,这种方法将起作用,您不必使用开关。

class IThingFactory
{
public IThing MakeThing<T>() where T : IThing, new()
{
var thing = new T();
thing.Init(); // has to be part of the IThing interface.
return thing;
}
}

更通用的方法是这样

class IThingFactory
{
private IDictionary<Type, Func<IThing>> factories = new Dictionary<Type, Func<IThing>>();

public void Register(Type t, Func<IThing> factory);
{
if(!typeof(IThing).IsAssignableFrom(t))
throw new ArgumentException("This is not a thing");
this.factories.Add(t, factory);
}

public void Register<T>() where T : IThing, new()
{
this.Register<T>(() => new T());
}

public void Register<T>(Func<IThing> factory) where T : IThing
{
this.Register(typeof(T), factory);
}

public IThing MakeThing(Type type);
{
if (!factories.ContainsKey(type))
throw new ArgumentException("I don't know this thing");
return factories[type]();
}
}

public void Main()
{
var factory = new IThingFactory();
factory.Register(typeof(A), () => new A());
factory.Register<B>();
factory.Register<C>(() => new C("Test"));
var instance = factory.MakeThing(typeof(A));
}

关于C#:开关与工厂类中的方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33545014/

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