( 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.
Strategy pattern uml
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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1 場景問題# 1.1 報價管理## 向客戶報價,對于銷售部門的人來講,這是一個非常重大、非常復雜的問題,對不同的...
    七寸知架構閱讀 5,130評論 9 62
  • 工廠模式類似于現實生活中的工廠可以產生大量相似的商品,去做同樣的事情,實現同樣的效果;這時候需要使用工廠模式。簡單...
    舟漁行舟閱讀 7,827評論 2 17
  • 1 場景問題 1.1 報價管理 向客戶報價,對于銷售部門的人來講,這是一個非常重大、非常復雜的問題,對不同的客戶要...
    4e70992f13e7閱讀 3,125評論 2 16
  • 設計模式匯總 一、基礎知識 1. 設計模式概述 定義:設計模式(Design Pattern)是一套被反復使用、多...
    MinoyJet閱讀 3,970評論 1 15
  • 設計模式基本原則 開放-封閉原則(OCP),是說軟件實體(類、模塊、函數等等)應該可以拓展,但是不可修改。開-閉原...
    西山薄涼閱讀 3,869評論 3 14