gpt4 book ai didi

c# - 棘手的架构问题。 4 基类需要一点可扩展性

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:50 25 4
gpt4 key购买 nike

我有 4 个基类:

class A { virtual SomeMethod () { <code> } }
class A<T> { virtual SomeMethod () { <code> } }

class B { virtual SomeMethod () { <code> } }
class B<T2> { virtual SomeMethod () { <code> } }

现在,我有 4 个实现(每个实现都派生自相应的基类型)。

class Aa : A { override SomeMethod () { <code> } }
class Aa<Tt> : A<T> { override SomeMethod () { <code> } }

class Bb : b { override SomeMethod () { <code> } }
class Bb<Tt2> : B<T2> { override SomeMethod () { <code> } }

现在,我需要添加 SomeMethod 实现(它应该是来自基类的一个重写)。所有提到的派生类的同一个。

什么是最好的解决方案? (我会在问题解决后立即分享我的所有想法。因为如果我将我的实现放在这里,讨论很可能会朝着我的方向发展,但我不太确定我是否正确)。

谢谢你的好主意!!

最佳答案

所以您想要对某些 ​​4 个类使用一个实现,而对其他 4 个类使用不同的实现?也许是 Strategy pattern会工作。

interface ISomeMethodStrategy {
string SomeMethod(string a, string b);
}

class DefaultStrategy : ISomeMethodStrategy {
public string SomeMethod(string a, string b) { return a + b; }
public static ISomeMethodStrategy Instance = new DefaultStrategy();
}
class DifferentStrategy : ISomeMethodStrategy {
public string SomeMethod(string a, string b) { return b + a; }
public static ISomeMethodStrategy Instance = new DifferentStrategy();
}

class A {
private ISomeMethodStrategy strategy;
private string a, b, c;
public A() : this(DefaultStrategy.Instance) {}
protected A(ISomeMethodStrategy strategy){
this.strategy = strategy;
}
public void SomeMethod() {
a = strategy.SomeMethod(b, c);
}
}

class Aa : A {
public Aa() : base(DifferentStrategy.Instance) {}
}

我在此处使用接口(interface)实现了该模式,但您也可以对委托(delegate)执行相同的操作。

关于c# - 棘手的架构问题。 4 基类需要一点可扩展性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1103154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com