当方法接受不同的签名时要实现什么样的工厂模式?

时间:2016-04-18 15:09:11

标签: c# .net visual-studio oop

如何定义其实现可能接受不同数量参数的工厂?

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) {}
}

1 个答案:

答案 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"));