mercredi 7 août 2019

Pattern for interface with multiple optional methods

For interfaces with an optional method, such as in the question C# Interfaces with optional methods, the answer is: Use two interfaces

What would be the common design pattern in case of multiple (5+ or 10+) optional methods?

Example

Let's say we have an interface without methods:

public interface IAnimal {}

An animal may, or may not, be able to do many things, such as: Jump, Fly, Dig, Swim, etc.

By defining single method interfaces for each method, IJumpable, IFlyable, IDigable, ISwimable, etc., we can check if an animal has a specific method before calling it:

IAnimal animal; // + initialize variable
if (animal is ISwimable swimmer)
{
    swimmer.Swim();
}

This may lead to class definition with a large amount of implemented interface:

class Bear: IWalkable, IHuntable, IHibernatable, IClimbable, IRunable

Is this the common solution, or are there better ways to handle multiple optional methods where it should be possible to tell if a method is implemented or not?

Aucun commentaire:

Enregistrer un commentaire