Design Patterns - Strategy

Software Engineering
1.0x

Design Patterns - Strategy

Created 3 years ago

Duration 0:03:29
lesson view count 549
Select the file type you wish to download
Slide Content
  1. Design Patterns: Strategy

    Slide 1 - Design Patterns: Strategy

    • Emerson Murphy-Hill
  2. Strategy Pattern:

    Slide 2 - Strategy Pattern:

    • Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients (aka contexts) that use it.
    • Strategy myStrategy = new Strategy1();
    • myStrategy.getAction(input);
    • Strategy myStrategy = new Strategy2();
    • myStrategy.getAction(input);
  3. Strategy Pattern: Example

    Slide 3 - Strategy Pattern: Example

    • public class Context {
    • public static final Strategy s1 = new Strategy1();
    • public static final Strategy s2 = new Strategy2();
    • private Strategy strategy;
    • public Context(Strategy strategy) {
    • this.strategy = strategy;
    • }
    • public void getAction(Object inputs) {
    • this.strategy.getAction(inputs);
    • }
    • public static void main(String[] args) {
    • Context context; Object inputs = new Object();
    • context = new Context(Context.s1);
    • context.getAction(inputs);
    • context = new Context(Context.s2);
    • context.getAction(inputs);
    • }
    • }
  4. Pros and Cons

    Slide 4 - Pros and Cons

    • Pros
    • Families of related algorithms
    • Delegate the behavior to a concrete strategy class
    • Reduce complex conditional statements in algorithm implementations
    • Cons
    • The application must be aware of all the strategies to select the right one for the right situation.
    • Increased number of objects
    • http://ootips.org/strategy-vs-case.html
    • getAction2(Object inputs) {
    • switch (type) {
    • 0: getAction2OfStrategy1(inputs);
    • 1: getAction2OfStrategy2(inputs);
    • ….
    • }
    • getAction1(Object inputs) {
    • switch (type) {
    • 0: getAction1OfStrategy1(inputs);
    • 1: getAction1OfStrategy2(inputs);
    • ….
    • }