Duck example strategy pattern - Head first design pattern

前端 未结 4 1452
鱼传尺愫
鱼传尺愫 2020-12-16 22:01

I want to ask something about duck example on this book that made me confused and I feel contradictions.

  1. Problem

4条回答
  •  感情败类
    2020-12-16 22:48

    You're correct. The solution offered by the book suffers from one huge problem: "FlyNoWay" is not a sub case of "FlyBehaviour". To have any meaning, FlyBehaviour must require the ability to fly. Classes that inherit from it will specify the behaviour (fly using wings etc.). A sub class cannot contain less than the class it inherits from.

    Taking a closer look, "FlyNoWay" is just a pseudo class that was introduced to solve the problem of polymorphism in an inappropriate way.

    The right method is to use interfaces.

    class Duck
    {
        swim();
    }
    
    class MallardDuck : IFlyable
    {
        fly();
    }
    
    class RedheadDuck : IFlyable, IQuackable
    {
        fly();
        quack();
    }
    

    What about code reuse? Well you have to make the interface as strict as possible, assuring that most changes in the interface will cause the program to not compile.

提交回复
热议问题