c# - 使用参数在 C# 中创建通用工厂

标签 c#

我正在尝试用 C# 创建一个非常简单的工厂类。唯一的障碍是我需要传递一个参数。

这是我要创建的类:

public class ClassToCreate
{
    private readonly string myValue;

    public ClassToCreate(string myValue)
    {
        this.myValue = myValue;
    }
}

首先我打算像这样创建工厂方法

public T CreateNewClass<T>(string value) where T : class, new()

但是你不能传递参数 - 所以我试过了

public class FactoryClass
{
    private object _instance = null;

    public T CreateNewClass<T>(Func<string, T> createWithValue) where T : class
    {
        if (_instance == null)
            _instance = createWithValue(??string here??);

        return (T)_instance;
    }
}

调用它的类

string somestring = "hello world";
var factory = new FactoryClass();
var myclass = factory.CreateNewClass<ClassToCreate>(_ => new ClassToCreate(somestring));

理想情况下,上面的调用代码只会传递值 - 但我无法让它接受任何东西...

最佳答案

尝试创建工厂类的另一种方法是创建一个更抽象的版本,它允许您在运行时定义工厂并将工厂组件与实例化实例的代码分开。

所以,这种工厂可以这样使用:

var factory = new AbstractFactoryClass();
factory.Register<string, ClassToCreate>(p => new ClassToCreate(p));
factory.Register<string, int, Person>((name, age) => new Person(name, age));

然后,稍后在您的代码中,您可以编写此代码来实际实例化您的实例:

var instance = factory.Create<string, ClassToCreate>("Hello");
var person = factory.Create<string, int, Person>("Fred", 99);

这是你需要的类:

public class AbstractFactoryClass
{
    private Dictionary<Type, Delegate> _factories = new();

    public void Register<T>(Func<T> factory) => _factories[typeof(Func<T>)] = factory;
    public void Register<P, T>(Func<P, T> factory) => _factories[typeof(Func<P, T>)] = factory;
    public void Register<P1, P2, T>(Func<P1, P2, T> factory) => _factories[typeof(Func<P1, P2, T>)] = factory;
    public void Register<P1, P2, P3, T>(Func<P1, P2, P3, T> factory) => _factories[typeof(Func<P1, P2, P3, T>)] = factory;

    public T Create<T>() => ((Func<T>)_factories[typeof(Func<T>)])();
    public T Create<P, T>(P p) => ((Func<P, T>)_factories[typeof(Func<P, T>)])(p);
    public T Create<P1, P2, T>(P1 p1, P2 p2) => ((Func<P1, P2, T>)_factories[typeof(Func<P1, P2, T>)])(p1, p2);
    public T Create<P1, P2, P3, T>(P1 p1, P2 p2, P3 p3) => ((Func<P1, P2, P3, T>)_factories[typeof(Func<P1, P2, P3, T>)])(p1, p2, p3);
}

public class ClassToCreate
{
    private readonly string myValue;

    public ClassToCreate(string myValue)
    {
        this.myValue = myValue;
    }

    public override string ToString() => myValue;
}

public class Person
{
    private readonly string name;
    private readonly int age;

    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public override string ToString() => $"{name} is {age} years old";
}

现在,您可以用它来实例化接口(interface),因为这非常酷。

试试这段代码:

public interface IFoo
{
    string Name { get; }
}

public class Foo1 : IFoo
{
    private readonly string name;

    public Foo1(string name)
    {
        this.name = name;
    }

    public string Name => name;
}

public class Foo2 : IFoo
{
    private readonly string name;

    public Foo2(string name)
    {
        this.name = name;
    }

    public string Name => name;
}

现在我可以像这样注册和创建接口(interface)了:

// during set up
factory.Register<string, IFoo>(n => new Foo1(n));

// somewhere later in my code:
IFoo foo = factory.Create<string, IFoo>("Fred");

我现在可以轻松地将我的 Register 调用更改为 n => new Foo2(n) 以及稍后调用 Create 方法的代码没有改变。它刚刚得到一个 Foo2

您可以轻松交换不同的存储库 - 从文件或数据库中读取 - 或向界面添加装饰器。

让我们试试这些类:

public interface IBar
{
    string Name { get; }
}

public class BarCore : IBar
{
    public string Name { get; private set; }

    public BarCore(string name)
    {
        this.Name = name;
    }
}

public class BarDecorator : IBar
{
    private IBar _bar;

    public BarDecorator(IBar bar)
    {
        this._bar = bar;
    }

    public string Name
    {
        get
        {
            Console.WriteLine($"You called Name on {_bar.GetType().Name}");
            return _bar.Name;
        }
    }
}

我可以这样运行:

// during set up
factory.Register<string, IBar>(n => new BarCore(n));

// somewhere later in my code:
IBar bar = factory.Create<string, IBar>("Fred");

Console.WriteLine($"{bar.Name} from {bar.GetType().Name}");

我得到这个输出:

Fred from BarCore

但是,如果我将我的注册码更改为:

factory.Register<string, IBar>(n => new BarDecorator(new BarCore(n)));

我不需要更改我的后续代码,但是当我运行它时,我现在得到这个:

You called Name on BarCore
Fred from BarDecorator

即时调试!

关于c# - 使用参数在 C# 中创建通用工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71630469/

相关文章:

c# - 描述.net 的速记符号的含义? ("+=","=>")

c# - FileHelpers 嵌套引号和逗号 - 解析错误

c# - WPF 列表框在拖动时自动滚动

c# - 无需删除 XML 声明即可读取 XML 文件的内容

c# - 如何创建位图深拷贝

c# - EF 6 - 包括为什么我没有 linq 选择?

c# - 奥尔良工作分配

c# - 如何将对象作为可绑定(bind)属性传递给 Xamarin.Forms 自定义控件

c# - 流畅的 NHibernate : Index was out of range exception with ReferencesAny mapping

c# - 在 C# 中使用超时的通用尝试和重试?