I'm making a weapon/shooting system so that each Hero will be provided with it's own logic at compile time.
An example would look like:
class MageHero : Hero {
MageHero(){
base(new SingleShotAttackStrategy>());
}
}
class BowmanHero : Hero {
BowmanHero(){
base(new MultishotAttackStrategy>());
}
}
Each strategy has it's own logic for spawning bullets.
Then, when I call Hero's Attack()
, attached logic would be executed.
To the point
I come from Java
. In Java
, I can do that:
// there will be a different attack input for different shot types (single shot, multi shot...)
public class BaseAttackInput{}
class SingleShotInput extends BaseAttackInput{
public int x, y;
public int dirX, dirY;
public int bulletSpeed;
}
public interface IAttackStrategy<T extends BaseAttackInput> {
void attack(T input);
}
// specific strategy for a single shot
public class SingleShotStrategy implements IAttackStrategy<SingleShotInput>
{
@Override
public void attack(SingleShotInput input) {
// spawn one bullet from the input's data
}
}
public class MultiShotStrategy{...}
public class Hero{
public IAttackStrategy strategy;
void initialize(IAttackStrategy strategy){
this.strategy = strategy;
}
}
void testHero(){
Hero hero = new Hero();
hero.initialize(new SingleShotStrategy());
}
In the equivalent code in C#, I can't do that:
public class Hero{
// ERROR, This needs to have specified generic types!
public IAttackStrategy strategy;
// this aswell...
void initialize(IAttackStrategy strategy){
this.strategy = strategy;
}
}
And then comes the fun, because I have to add generic parameters to the Hero class, and then, provide generic parameters in each subclass of the Hero class etc...
What to do?