Requirement Description:

  1. Duck
  2. A variety of ducks (redhead, green feather, toy duck)
  3. Multiple behaviors (croak, fly, display)

How do you design it?

Common design patterns:

  1. Duck is the parent class, which defines methods such as the quack flight appearance display
    public class Duck {
     public String guagua(){// ribbit} public Stringfly(){
         //飞翔
     }
     public String display(){// appearance display}}Copy the code
  2. Multiple varieties of ducks are designed to subclass duck
    Public class RedHeadDuck extend Duck{// Overwrite the parent class's appearance method public Stringdisplay(){// I am a red head duck}}Copy the code

The design problem was that all the ducks had the ability to fly and quack, but the toy ducks had no ability to fly

Modified design:

  1. Duck is still the parent class
    public class Duck {
     public String guagua(){// ribbit} public Stringdisplay(){// appearance display}}Copy the code
  2. Design interface flyBehavior
    public interface FlyBehavior {
     Stirng fly();
    }
    public class FlyDuck extend Duck implements FlyBehavior {
     public String fly(){// I can fly}} public ToyDuck extend Duck {public Stringdisplay() {// I am a toy duck}}Copy the code

    You will need to implement the fly subclass to implement the interface flyBehavior

    In this way, the problem of flying is solved only by the toy duck not implementing the interface

But the problem is that if flying is subclassed into flying by force and flying against the wind and other different ways of implementing interfaces you need different ways of implementing them, you have more code and you can’t reuse it

Upgrade the design

  1. Duck for the parent class
  2. Design interface flyBehavior
  3. Design behavior classes to implement flyBehavior
  4. Duck references behavior classes
    public class Duck {
     private FlyBehavior flyBehavior;
     public setFlyBehavior(FlyBehavior f){
         this.flyBehavior = f;
     }
     public String fly() {return flyBehavior.fly();
     }
    }
    public class NoFly implements FlyBehavior {
     public String fly() {// can't fly}} public class CanFly implements FlyBehavior {public Stringfly() {// can fly}} // can also define a variety of ways to fly...Copy the code

    This gives the design flexibility to modify the class

Conclusion: The strategy pattern is to extract the behavior class that is easy to change things more combination less inheritance for interface programming not for implementation programming