Design Patterns (1)--Strategy Patterns

Strategy mode : defines algorithm families and encapsulates them separately so that they can be converted to each other. This mode makes algorithm changes independent of the customers who use the algorithm.

Design Principles:

1. Find out where changes may be needed in the application, isolate them, and don't mix them with code that doesn't need changes.

2. Program against the interface (for the superclass) rather than against the implementation.

3. Use more composition and less inheritance.

 

Abstracted flight behavior:

public interface FlyBehavior {
    void fly();
}

 

Specific different flight behaviors:

public class FlyWithLag implements FlyBehavior{

    @Override
    public void fly() {
        System.out.println("Fly with your feet~");
    }
}

 

public class FlyWithSwing implements FlyBehavior {

    @Override
    public void fly() {
        System.out.println("will fly with wings~");
    }
}

 

Abstract Duck class

public abstract  class Duck {
    // use the combined method
    private FlyBehavior flyBehavior;

    public Duck(FlyBehavior flyBehavior) {
        this.flyBehavior = flyBehavior;
    }

    public void displayFlay(){
        flyBehavior.fly();
    }

}

 

Specific Different Kinds of Ducks

public class YellowDuck extends Duck{
    public YellowDuck(FlyBehavior flyBehavior) {
        super (flyBehavior);
    }
}

 

public class BlackDuck extends Duck {
    public BlackDuck(FlyBehavior flyBehavior) {
        super (flyBehavior);
    }

}

 

Test class:

public class DuckTest {
    public static void main(String[] args) {
        Duck blackDuck = new BlackDuck(new FlyWithSwing());
        blackDuck.displayFlay(); //Output: can fly with wings~
        Duck yellowDuck = new YellowDuck(new FlyWithLag());
        yellowDuck.displayFlay(); //Output: Fly with your feet~
    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326698831&siteId=291194637