如何定义其实现可能接受不同数量参数的工厂?
public abstract class CarFactory
{
public abstract void countStuff(??); //not sure how to define this
}
我希望工厂能够创建不同的对象,如:
public class BMW : CarFactory
{
public override void countStuff(param1, param2) {}
}
public class Ford : CarFactory
{
public override void countStuff(param1) {}
}
答案 0 :(得分:4)
不确定" countStuff"应该是工厂的责任,但你可以这样得到类似的东西:
public interface ICountParam {}
public class BmwParam : ICountParam
{
public BmwParam(string a)
{
A = a;
}
public string A { get; set; }
}
public class FordParam : ICountParam
{
public FordParam(string a, string b)
{
A = a;
B = b;
}
public string A { get; set; }
public string B { get; set; }
}
public interface ICarFactory<in T> where T : ICountParam
{
void CountStuff(T param);
}
public class BMW : ICarFactory<BmwParam>
{
public void CountStuff(BmwParam param) { }
}
public class Ford : ICarFactory<FordParam>
{
public void CountStuff(FordParam param) { }
}
用法:
bmw.CountStuff(new BmwParam("A"));
ford.CountStuff(new FordParam("A", "B"));