我有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实现(它应该是基类中的实现的重写)。对于所有提到的派生类都是相同的。
最佳解决方案是什么?(我会在问题解决后立即分享我所有的想法。因为如果我把我的实现放在这里,讨论很可能会按照我的方向进行,但我不太确定我是否正确)。
谢谢你的好点子!
发布于 2009-07-09 10:54:40
所以你想对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) {}
}我在这里用一个接口实现了这个模式,但是你也可以用委托来做同样的事情。
发布于 2009-07-09 10:59:16
a)。如果你确实发布了你的实现,那就更好了,不管你认为它会扭曲什么。
b)。拥有一个class A和一个通用表单class A<T>的概念似乎真的很陌生。这就像你的泛型类对一个特定的情况有一个排除,这意味着它比其他泛型类更不泛型,比如wierd。
c)。如果你想让每个基类都有相同的方法,为什么不让所有4个基类都从更高的类X继承,或者如果你只是想让它们实现这个公共方法,为什么不从一个接口继承呢?似乎太明显了,我是不是在你的问题中漏掉了什么?
发布于 2009-07-09 11:02:12
那么接口和组合而不是继承呢?
例如,您创建了一个新接口
interface myinterface
{
void doSomethingCool();
}而不是一个实现它的新类
class interfaceImpl: myinterface
{
public void doSomethingCool()
{
... some code
}
}而不是
class A : myinterface
{
private interfaceImpl interf = MyInterfaceFactory.Build(args);
public void doSomethingCool()
{
interf.doSomethingCool();
}
}所以你可以在类A,B和所有派生类中有相同的行为,你也可以覆盖它。
hth
https://stackoverflow.com/questions/1103154
复制相似问题