Reputation: 9090
I have the following actions:
abstract class AAction
{}
class BlueAction: AAction
{
void Foo1(){// do stuff}
void Foo2(){// do stuff}
}
and the plugins that should contain an action:
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();
}
}
I am trying to fit this design to a design pattern, with no luck.
What I just want is to force derived classes from APlugin
to have an AAction
I could do simply this:
BlueAction act = (BlueAction)_action;
act.Foo1();
act.Foo2();
Using generics (as suggested) doesn't allow me to have a list of APlugins which is something I really need.
But this is a no-go for me. Any ideas?
Upvotes: 3
Views: 176
Reputation: 8352
Just keep the BlueAction instance:
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();
}
}
Upvotes: 1
Reputation: 17648
Assuming you want the constructors to stay the same, you could do it as follows:
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();
}
}
Upvotes: 1
Reputation:
Use generics:
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();
}
}
Upvotes: 14