( 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,135评论 9 62
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,854评论 2 17
  • 1 场景问题 1.1 报价管理 向客户报价,对于销售部门的人来讲,这是一个非常重大、非常复杂的问题,对不同的客户要...
    4e70992f13e7阅读 3,128评论 2 16
  • 设计模式汇总 一、基础知识 1. 设计模式概述 定义:设计模式(Design Pattern)是一套被反复使用、多...
    MinoyJet阅读 3,984评论 1 15
  • 设计模式基本原则 开放-封闭原则(OCP),是说软件实体(类、模块、函数等等)应该可以拓展,但是不可修改。开-闭原...
    西山薄凉阅读 3,891评论 3 14