Junior — Middle
How can different behaviors for weapons be created in the system?
sobes.tech AI
Answer from AI
To create different types of weapon behavior in a C# system, you can use several approaches:
- Inheritance and method overriding — create a base class
Weaponwith a virtual methodAttack(), and for each weapon type, create a subclass with its own implementation.
public abstract class Weapon {
public abstract void Attack();
}
public class Sword : Weapon {
public override void Attack() {
Console.WriteLine("Sword strikes with a sword");
}
}
public class Bow : Weapon {
public override void Attack() {
Console.WriteLine("Bow shoots an arrow");
}
}
-
Using interfaces — define an
IAttackBehaviorinterface and inject different implementations into weapon classes. -
Strategy pattern — isolate behavior into separate classes and change them dynamically.
This approach allows easy extension of the system by adding new weapon types and behaviors without modifying existing code.