我正在嘗試在 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));
理想情況下,上面的呼叫代碼只會傳遞值 - 但我無法讓它接受任何東西......
uj5u.com熱心網友回復:
完成這項作業的最簡單答案是有效地什么都不做。
嘗試這個:
public class FactoryClass
{
private Dictionary<Type, object> _instances = new();
public T CreateNewClass<T>(Func<T> createWithValue) where T : class
{
var success = _instances.TryGetValue(typeof(T), out object instance);
if (!success)
{
instance = createWithValue();
_instances[typeof(T)] = instance;
}
return (T)instance;
}
}
你可以像這樣使用它:
var factory = new FactoryClass();
var instance = factory.CreateNewClass(() => new ClassToCreate("Hello"));
簡單的。
或者,您可以定義一堆方法來為您硬編碼:
public T CreateNewClass<P, T>(P p, Func<P,T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p));
public T CreateNewClass<P1, P2, T>(P1 p1, P2 p2, Func<P1, P2, T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p1, p2));
public T CreateNewClass<P1, P2, P3, T>(P1 p1, P2 p2, P3 p3, Func<P1, P2, P3, T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p1, p2, p3));
public T CreateNewClass<P1, P2, P3, P4, T>(P1 p1, P2 p2, P3 p3, P4 p4, Func<P1, P2, P3, P4, T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p1, p2, p3, p4));
// etc
現在你可以這樣稱呼它:
var factory = new FactoryClass();
var instance = factory.CreateNewClass("Hello", p => new ClassToCreate(p));
uj5u.com熱心網友回復:
請注意,Activator.CreateInstance 的替代品性能更高,但對于您的基本場景,我們可以使用它并傳遞一個引數(作為建構式引數注入到實體化程序中。
首先我們有工廠:
public class FactoryClass
{
private object _instance = null;
public T CreateNewClass<T>(string value) where T : class
{
if (_instance == null)
{
_instance = (T)Activator.CreateInstance(typeof(T), value);
}
return (T)_instance;
}
}
這是一個使用這種方法通過的 NUnit 測驗:
[Test]
[TestCase("hullo world")]
public void CreateNewClassReturnsFieldValue(string greeting)
{
var factory = new FactoryClass();
var instance = factory.CreateNewClass<ClassToCreate>(greeting);
string myValue = typeof(ClassToCreate).GetField("myValue", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(instance) as string;
myValue.Should().Be(greeting);
}
我正在看一門帶有工廠模式的在線課程,所以你的問題很有趣,因為它與我現在正在做的課程有關。
注意 - 我放棄了 new() 約束,這迫使我添加一個無引數的建構式,你的 ClassToCreate 無論如何都缺少它。

uj5u.com熱心網友回復:
嘗試創建工廠類的另一種方法是創建一個更抽象的版本,它允許您在運行時定義工廠并將工廠組件與實體化實體的代碼分開。
所以,這種工廠可以這樣使用:
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";
}
現在,令人難以置信的是,您可以使用它來實體化介面。
試試這個代碼:
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;
}
現在我可以像這樣注冊和創建介面:
// 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
即時除錯!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449954.html
標籤:C#
