I’ve a easy code base with few ‘weapon’ concrete lessons which implements completely different contracts with the intention to be utilized by its purchasers.
My contracts:
public interface IWeaponPrimaryAttack
{
void DoAttack();
}
public interface IWeaponSecondaryAttack
{
void DoSecondaryAttack();
}
public interface IReloadable
{
void Reload();
}
Concrete implementation or the precise weapons:
public class Katana : IWeaponPrimaryAttack, IWeaponSecondaryAttack
{
public void DoAttack(){Console.WriteLine ("Swing");}
public void DoSecondaryAttack() {Console.WriteLine ("Stab");}
}
public class ShotGun : IWeaponPrimaryAttack, IReloadable
{
public void DoAttack(){Console.WriteLine ("Swing");}
public void Reload() {//reload it}
}
Shoppers that makes use of these concrete lessons:
public class PrimaryAttack
{
non-public IWeaponPrimaryAttack _attack;
public PrimaryAttack(IWeaponPrimaryAttack assault)
{
_attack = assault;
}
public void DoAttack()
{
_attack.DoAttack();
}
}
public class SecondaryAttack
{
non-public IWeaponSecondaryAttack _attack;
public SecondaryAttack(IWeaponSecondaryAttack assault)
{
_attack = assault;
}
public void DoSecondaryAttack()
{
_attack.DoSecondaryAttack();
}
}
public class WeaponReload
{
non-public IReloadable _reloader;
public WeaponReload(IReloadable reloader)
{
_reloader = reloader;
}
public void Reload()
{
_reloader.Reload();
}
}
New after all the instantiation of concrete class solely be recognized when the person selects one amongst many weapons(one amongst ShotGun, Katana, and many others).
Let say the use has chosen ShotGun because the weapon, primarily based on the choice it would go like this:
IWeaponPrimaryAttack weapon = new ShotGun(); // get it from a manufacturing facility
PrimaryAttack primaryAttack = new PrimaryAttack(weapon);
primaryAttack.DoAttack();
Now for the WeaponReload should do a typecast right here with the intention to use it.
WeaponReload reloader = new WeaponReload ((IReloadable)weapon);
reloader.Reload();
I’ve questions round it,
-
Ought to I actually have to finish up typecasting ultimately?
-
Or there’s a higher solution to deal with this object creation half.
-
Or there’s solely a greater design that I can give you which
doesn’t essentially leads to casting. -
Or casting it like that is completely advantageous.