我目前有两个(核心)类:
public abstract class BO where TConfig : BOConfigBase
{
protected TConfig Config { get; set; }
internal List _BCs { get; set; }
public abstract void Init();
public void Process() => _BCs.ForEach(bc => bc.Process());
}
public class BOOne : BO
{
public BOOne(BOConfigOne config)
{
Config = config;
}
public override void Init()
{
_BCs = new List()
{
BCA.Init(Config),
BCB.Init(Config),
BCC.Init(Config),
BCOneA.Init(Config)
};
}
}然后我的BCs代码
public abstract class BC
{
protected BOConfigBase Config { get; set; }
public abstract void Process();
}
public class BCA : BC
{
private BCA()
{
}
public static BCA Init(BOConfigBase config)
{
BCA ret = new BCA { Config = config };
return ret;
}
public override void Process()
{
Config.Counter += 1;
}
}我要这么说:
static void Main()
{
{
var boConfigOne = new BOConfigOne()
{
A = "one",
B = "one",
C = "one",
One = "one"
};
var testBO = new BOOne(boConfigOne);
testBO.Init();
testBO.Process();
Console.WriteLine(
$"A = {boConfigOne.A}, B = {boConfigOne.B}, C = {boConfigOne.C}, One = {boConfigOne.One}, Counter = {boConfigOne.Counter}");
}
{
var boConfigTwo = new BOConfigTwo()
{
A = "two",
B = "two",
C = "two",
Two = "two"
};
var testBOTwo = new BOTwo(boConfigTwo);
testBOTwo.Init();
testBOTwo.Process();
Console.WriteLine(
$"A = {boConfigTwo.A}, B = {boConfigTwo.B}, C = {boConfigTwo.C}, Two = {boConfigTwo.Two}, Counter = {boConfigTwo.Counter}");
}
Console.ReadKey();
}BO代表业务编排,BC代表Business。BC将执行单个功能,BO将包含其中几个可重用的BCs。
我想改变BO,使其能够泛化所有BCs,类似于Init => BCs.Foreach(bc => bc.Init(Config));。问题是我的BC的Init是静态的,所以我不能把它放在一个接口中,在接口上调用它,也不能把它放在基本的抽象方法中,然后重写它。
有没有人能给我更好的解决方案?
发布于 2019-04-23 14:00:28
老实说,这样抽象的类名和POC很难理解。您所描述的根源是您有一个工厂方法来创建您的类之一。幸运的是,似乎所有的工厂方法都有相同的方法签名。我们可以让这件事简单一点。
需要将工厂方法存储在要由Init方法使用的私有字段中。还添加了一个“助手”方法来简化工厂的存储。
public abstract class BO where TConfig : BOConfigBase
{
protected TConfig Config { get; set; }
internal List _BCs { get; set; }
private Func[] _factories = new Func[0];
protected void SetFactories(params Func[] factories)
{
_factories = factories;
}
public void Init()
{
_BCs = _factories.Select(b => b(Config)).ToList();
}
public void Process() => _BCs.ForEach(bc => bc.Process());
}现在,BOOne类可以将其称为
public class BOOne : BO
{
public BOOne(BOConfigOne config)
{
Config = config;
SetFactories(BCA.Init, BCB.Init, BCC.Init, BCOneA.Init);
}
}我假设每个BO类将接受不同的BC类,如果不是,那么您可以将所有工厂注入构造器。
https://codereview.stackexchange.com/questions/217933
复制相似问题