Implementing interfaces that "inherit" (implement) a common interface?

interface ITurtle
{        
    void Fight();
    void EatPizza();
}

interface ILeonardo : ITurtle
{
    void UseKatana();
}

interface IRaphael : ITurtle
{
    void UseSai();
}

interface IDonatello : ITurtle
{
    void UseBo();
}

interface IMichelangelo : ITurtle
{
    void UseNunchuku();
}

What if I want to create a great turtle that can do all 4? I want the code:

class GrandTurtle : IMichelangelo, IDonatello, IRaphael, ILeonardo
{
    // Implementation not shown for brevity.
}

Is this possible, because now I feel that I need to implement Fight()and EatPizza()4 times. But I think that these two common functions will be allowed and should only be performed once, right?

I could create 4 intermediate interfaces without inheritance ITurtleand then GrandTurtleimplement ITurtle. This solves the problem of interface inheritance, but now it looks semantically incorrect, because it makes it ITurtlelook like the fifth brother, who is not there. Also, I want to be able to create classes that are specific to turtles, for example class BostonLeonardo : ILeonardo.

- , " " , , , , , .

+4
1

Fight EatPizza , . Fight EatPizza ILeonardo .., , OR , , , TMNT:

interface ILeonardo
{
    void Fight();
    void EatPizza();
    void UseKatana();
}

interface IRaphael
{
    void Fight();
    void EatPizza(); 
    void UseSai();
}

interface IDonatello
{
    void Fight();
    void EatPizza();
    void UseBo();
}

interface IMichelangelo
{
    void Fight();
    void EatPizza();
    void UseNunchuku();
}

class GrandTurtle : IMichelangelo, IDonatello, IRaphael, ILeonardo
{
    // Code that fires when Fight is called on ILeonardo turtle = new GrandTurtle()
    void ILeonardo.Fight()
    {
        UseKatana();
    }

    // Code that fires when Fight is called on IRaphael turtle = new GrandTurtle()
    void IRaphael.Fight()
    {
        UseSai();
    }

    // Code that fires for all other turtles
    public void Fight()
    {
        UseThatCrappyStickThingTheOldActionFiguresCameWith();
    }

    // Implement EatPizza() and such here...
}

, GrandTurtle .

EDIT: , ; , TMNT

+5

Source: https://habr.com/ru/post/1523461/


All Articles