设计模式总结:策略模式

栏目: 后端 · 发布时间: 5年前

内容简介:策略模式属于行为型设计模式,策略模式中,提供一组策略,每种策略都封装为一个类,每个策略可以相互替换,由客户端决定使用哪种策略在系统中提供一组策略,并将每个策略封装成类,使他们可以相互转换,具体策略的选择由客户端决定,这就叫策略模式,当系统中有很多if…else的时候可以考虑使用策略模式,策略模式可以灵活的增加策略类,进行扩展,但是可能会由于策略过多导致,策略类太多

策略模式属于行为型设计模式,策略模式中,提供一组策略,每种策略都封装为一个类,每个策略可以相互替换,由客户端决定使用哪种策略

什么是策略模式

在系统中提供一组策略,并将每个策略封装成类,使他们可以相互转换,具体策略的选择由客户端决定,这就叫策略模式,当系统中有很多if…else的时候可以考虑使用策略模式,策略模式可以灵活的增加策略类,进行扩展,但是可能会由于策略过多导致,策略类太多

类图

设计模式总结:策略模式

  1. TripStrategy:策略接口
  2. BicycleTripStrategy,CarTripStraregy:实现了策略接口的具体策略类
  3. TripContext:使用某种策略的类

实现

TripStrategy

/**
 * @author: chenmingyu
 * @date: 2019/2/21 18:15
 * @description: 出行策略
 */
public interface TripStrategy {

    /**
     * 出行方式
     */
    void tripMode();
}

BicycleTripStrategy

/**
 * @author: chenmingyu
 * @date: 2019/2/21 18:19
 * @description: 自行车出行策略类
 */
public class BicycleTripStrategy implements TripStrategy{

    @Override
    public void tripMode() {
        System.out.println("选择骑自行车出行");
    }
}

CarTripStraregy

/**
 * @author: chenmingyu
 * @date: 2019/2/21 18:21
 * @description: 开车出行策略类
 */
public class CarTripStraregy implements TripStrategy {

    @Override
    public void tripMode() {
        System.out.println("选择开车出行");
    }
}

TripContext

/**
 * @author: chenmingyu
 * @date: 2019/2/21 18:22
 * @description: 策略context
 */
public class TripContext {

    /**
     * 出行策略
     */
    private TripStrategy tripStrategy;

    public TripContext(TripStrategy tripStrategy) {
        this.tripStrategy = tripStrategy;
    }

    /**
     * 选择出行策略
     */
    public void chooseTripMode(){
        this.tripStrategy.tripMode();
    }
}

测试

public static void main(String[] args) {

    TripContext tripContext = new TripContext(new BicycleTripStrategy());
    tripContext.chooseTripMode();
    System.out.println("换一种出行方案");
    tripContext = new TripContext(new CarTripStraregy());
    tripContext.chooseTripMode();
}

输出

选择骑自行车出行
换一种出行方案
选择开车出行

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computing Patterns in Strings

Computing Patterns in Strings

Bill Smyth / Addison Wesley / 2003 / $ 75.00

The computation of patterns in strings is a fundamental requirement in many areas of science and information processing. The operation of a text editor, the lexical analysis of a computer program, the......一起来看看 《Computing Patterns in Strings》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具