我有以下行动:
abstract class AAction
{}
class BlueAction: AAction
{
void Foo1(){// do stuff}
void Foo2(){// do stuff}
}
以及应包含操作的插件:
class APlugin
{
AAction _action;
APlugin(AAction action)
{
_action = action;
}
}
class BluePlugin: APlugin
{
BluePlugin(): base(new BlueAction());
{
}
voif Foo()
{
// do stuff with BlueAction's methods
((BlueAction)_action).Foo1();
((BlueAction)_action).Foo2();
}
}
我试图将这种设计融入设计模式,没有运气。
我只想强迫APlugin
的派生类拥有AAction
我可以做到这一点:
BlueAction act = (BlueAction)_action;
act.Foo1();
act.Foo2();
使用泛型(如建议的)不允许我有一个APlugins列表,这是我真正需要的。
但这对我来说是不行的。有什么想法吗?
答案 0 :(得分:14)
使用泛型:
class APlugin<TAction> where TAction : AAction
{
TAction _action;
APlugin(TAction action)
{
_action = action;
}
}
class BluePlugin: APlugin<BlueAction>
{
BluePlugin(): base(new BlueAction());
{
}
void Foo()
{
// do stuff with BlueAction's methods
_action.Foo1();
_action.Foo2();
}
}
答案 1 :(得分:1)
假设您希望构造函数保持不变,您可以按如下方式执行:
class APlugin
{
public AAction Action { get; private set; }
APlugin(AAction action)
{
Action = action;
}
}
class BluePlugin: APlugin
{
private ActualAction
{
get { return Action as BlueAction; }
}
BluePlugin(): base(new BlueAction());
{
}
void Foo()
{
// do stuff with BlueAction's methods
ActualAction.Foo1();
ActualAction.Foo2();
}
}
答案 2 :(得分:1)
只需保留BlueAction实例:
class APlugin
{
AAction _action;
APlugin(AAction action)
{
_action = action;
}
}
class BluePlugin: APlugin
{
BlueAction _blueAction = new BlueAction();
BluePlugin(): base(_blueAction)
{
}
void Foo()
{
// do stuff with BlueAction's methods
_blueAction.Foo1();
_blueAction .Foo2();
}
}