( Design Patterns ) Behavioral Design Patterns 2 -- Strategy pattern

Definition

Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary indenpendently from clients that use it.

Components

  1. Client: this class uses interchangeable algorithms. It maintains a reference to StrategyBase object.
  2. StrategyBase: declares an interface common to all supported algorithms.
  3. ConcreteStrategy:inherited from the StrategyBase Class, provides a different algorithm.
( Design Patterns ) Behavioral Design Patterns 2 -- Strategy pattern_第1张图片
Strategy pattern uml

Sample code

public interface Istrategy {
    public void operate();
}

public class Strategy1 implements Istrategy{ 
    public void operate(){
        System.out.println("operate 1");
    }
}

public class Strategy2 implements Istrategy {
    public void operate(){
        System.out.println("operate 2");
    }
}

public class Context {
    private Istrategy strategy;
 
    public Context(Istrategy strategy) {
        this.strategy = strategy;
    }

    public void operate() {
        this.strategy.operate();
    }
}

public class Client {
    public static void main(string args[]) {
        Context context;
        context = new Context (new Strategy1());
        context.operate();

        context = new Context (new Strategy2());
        context.operate();
    }
}

Advantages

  1. Provides design where client and strategies are loosely coupled.
  2. Easy to add or replace or reuse clients or strategies.

Reference

Design Patterns 1 of 3 - Creational Design Patterns - CodeProject
Head First Design Patterns - O'Reilly Media

你可能感兴趣的:(( Design Patterns ) Behavioral Design Patterns 2 -- Strategy pattern)