Using a strategy pattern and a command pattern

后端 未结 7 2126
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 03:56

Both design patterns encapsulate an algorithm and decouple implementation details from their calling classes. The only difference I can discern is that the Strategy pattern

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 04:17

    Command:

    Basic components:

    1. Command declares an interface for abstract commands like execute()
    2. Receiver knows how to execute a particular command
    3. Invoker holds ConcreteCommand, which has to be executed
    4. Client creates ConcreteCommand and assign Receiver
    5. ConcreteCommand defines binding between Command and Receiver

    Workflow:

    Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.

    Advantage : Client is not impacted changes in Command and Receiver. Invoker provide loose coupling between Client and Receiver. You can run multiple commands with same Invoker.

    Command pattern allows you to execute a command on different Receivers by using same Invoker. Invoker is unaware of type of Receiver

    For better understanding of concepts, have a look at this JournalDev article by Pankaj Kumar and dzone article by James Sugrue in addition to Wikipedia link.

    You can use Command pattern to

    1. Decouple the invoker & receiver of command

    2. Implement callback mechanism

    3. Implement undo and redo functionality

    4. Maintain a history of commands

    java.lang.Thread is one good implementation of Command pattern. You can treat Thread as invoker & class implementing Runnable as ConcreteCommonad/Receiver and run() method as Command.

    Undo/Redo version of command pattern can be read at Theodore Norvell's article

    Strategy:

    Strategy pattern is very simple to understand. Use this pattern when

    You have multiple implementations for an algorithm and implementation of algorithm can change at run time depending on particular conditions.

    Take an example of Airline booking system's Fare component

    Airlines would like to offer different Fares during different time periods - Peak and Off Peak months. During Off peak travel days, it would like to stimulate the demand by offering attractive discounts.

    Key takeaways of Strategy pattern:

    1. It's a behavioural pattern
    2. It's based on delegation
    3. It changes guts of the object by modifying method behaviour
    4. It's used to switch between family of algorithms
    5. It changes the behaviour of the object at run time

    Related posts with code examples:

    Using Command Design pattern

    Real World Example of the Strategy Pattern

提交回复
热议问题