Reputation: 1
So, I'm in the case were I have an interface called "IDamageable" Now, I want to have multiple uses for that interface, for example, a method called TakeDamage, but with different options.
(TakeDamage(int) for the damage amount, TakeDamage(culprit) for who did it etc etc).
The thing is that I only want to implement one of there since I don't need the others in the class, and if they are in the same interface I must implement every case.
What would be the best way to do this? Multiple interfaces like IDamageable01, IDamageable02 etc etc or there is a better way?
Thanks
Upvotes: 0
Views: 1632
Reputation: 2417
Create a new interface IDamager to handle this.
public class Bullet : IDamager
{
}
public class Char : IDamager , IDamageable
{
public TakeDamage(int val, IDamager damager)
{
//here to do like:
if(IDamager is Char)
{
Char c = IDamager as Char;
//....
}
if(IDamager is Bullet)
{
Bullet b = IDamager as Bullet;
//....
}
}
}
public interface IDamager
{
}
public interface IDamageable
{
TakeDamage(int val , IDamager damager)
}
Upvotes: 0
Reputation: 4224
You coud create a base class implementing interface, then your "real" calss extends base class and implement what you want.
Also, in order to avoid too many method you can use optional parameters when possible:
void foo(string x, string y=null);
Upvotes: 1
Reputation: 151588
No, you definitely don't need numbered interfaces nor interfaces that you partially implement. If you think you need that, you need to revisit your design.
You need one interface IDamageable { void TakeDamage(int damage); }
and one interface:
public interface IDamageCalculator
{
void ApplyDamage(IDamageable subject, int damage);
void ApplyDamage(IDamageable subject, Culprit damager);
}
Or something like that. You haven't explained enough about your domain to make this more specific.
Upvotes: 2