策略模式

Intent

  1. Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
  2. Capture the abstraction in an interface, bury implementation details in derived classes.

结构图

策略模式_第1张图片

实例Demo

  1. 问题描述:鸭子,叫法不一样;
  2. 结构:


    策略模式_第2张图片
    duck by keith

    代码实现:

//behavior interface
interface QuackBehavior {
    void quack();
}
//quack
class Quack implements QuackBehavior {
    @Override
    public void quack() {
        System.out.println("Quack");
    }
}
// muteQuack
class MuteQuack implements QuackBehavior {
    @Override
    public void quack() {
        System.out.println("Silence");
    }
}
//Squeak
class Squeak implements QuackBehavior {

    @Override
    public void quack() {
        System.out.println("Squeak");
    }
}
//client
abstract class Duck {
    private QuackBehavior quackBehavior;
    public Duck() {
    }
    abstract void display();
    public void performQuack() {
        quackBehavior.quack();
    }

    public void setQuackBehavior(QuackBehavior quackBehavior) {
        this.quackBehavior = quackBehavior;
    }
}
//ModelDuck
class ModelDuck extends Duck {
    @Override
    void display() {
        System.out.println("I am a model duck.");
    }
}
//test
public class Strategy {
    public static void main(String[] args) {
        Duck duck = new ModelDuck();
        //对方法的抽象(也就是algorithm)之后,可以独立的按需调用相应的实现,更加灵活。
        duck.setQuackBehavior(new Quack());
        duck.performQuack();
    }
}

Reference:

  1. Design Patterns
  2. 设计模式

你可能感兴趣的:(策略模式)