策略模式

  1. 1. Strategy Pattern Overview
  2. 2. Why use strategy pattern?
  3. 3. Implementation
    1. 3.1 Interface
    2. 3.2 Implementation
    3. 3.3 Test

1. Strategy Pattern Overview

Using composition rather than inheritance

Strategy patten define a set of algorithms, encapsulate each of them and make then exchangable. And we could switch them at run time , decouple the algorithm with the place they are used

2. Why use strategy pattern?

  • when we have a set of classes, they belong to same object, they should could a certain types of actions, but the detail would vary. Then we need a way to regulate they have such type of behaviors, and also differ them in a maintainable manner
  • literaly composition over inheritance
  • 其实主要还是在考虑代码的可扩展性,多考虑下如何应对可能的改动,Design Pattern整个就是为了应对改动来服务的,并不太需要神化,毕竟只是对于常见的一些应用场景的抽象,想要达到的目的也就是抽象出来,以后做的时候会在范式下,更专注在业务逻辑上的问题

3. Implementation

Class Diagram

3.1 Interface

public interface IFlyBehavior {
    void fly();
}

public interface IQuackBehavior {
    void quack();
}

3.2 Implementation

public class Duck {
    IFlyBehavior flyBehavior;
    IQuackBehavior quackBehavior;

    public void fly() {
        flyBehavior.fly();
    }
    public void quack() {
        quackBehavior.quack();
    }
}

public class JetFly implements IFlyBehavior {
    @Override
    public void fly() {
        System.out.println("Jet Fly");
    }
}

public class SimplyFly implements IFlyBehavior {
    @Override
    public void fly() {
        System.out.println("Simple flying");
    }
}

public class LoudQuack implements IQuackBehavior {
    @Override
    public void quack() {
        System.out.println("Make noise!");
    }
}

public class NoQuack implements IQuackBehavior {
    @Override
    public void quack() {
        // do nothing, as no quack exist
    }
}

public class ToyDuck extends Duck {

    public ToyDuck(IFlyBehavior flyBehavior, IQuackBehavior quackBehavior) {
        this.flyBehavior = flyBehavior;
        this.quackBehavior = quackBehavior;
    }
}

3.3 Test

@GetMapping("/strategy")
    public String strategy() {
        Duck testDuck = new ToyDuck(new JetFly(), new LoudQuack());
        testDuck.fly();
        testDuck.quack();

        return "check the log";
    }

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 stone2paul@gmail.com

文章标题:策略模式

文章字数:375

本文作者:Leilei Chen

发布时间:2022-09-25, 14:21:58

最后更新:2022-09-25, 14:23:31

原始链接:https://www.llchen60.com/%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏