摘要:策略模式在构造方法或方法中初始化各自需要的策略模式代码策略接口具体策略具体策略上下文抽象类我理解的这个类的作用是负责策略与用户使用者的连接,也是策略模式的入口持有一个具体策略的对象构造函数,传入一个具体策略对象策略方法具体环境类应用场景多个
策略模式UML:
ContextType1、ContextType2在构造方法或set方法中初始化各自需要的StrategyType
策略模式代码
</>复制代码
/**
* 策略接口
*/
public interface Strategy {
public void strategyInterfaceMethod();
}
/**
* 具体策略A
*/
public class StrategyTypeA implements Strategy {
@Override
public void strategyInterfaceMethod() {
// todo someting
}
}
/**
* 具体策略B
*/
public class StrategyTypeB implements Strategy {
@Override
public void strategyInterfaceMethod() {
// todo someting
}
}
/**
* 上下文抽象类
* 我理解的这个类的作用是:负责策略与用户(使用者)的连接,也是策略模式的入口
*/
public AbstractClass Context {
//持有一个具体策略的对象
private Strategy strategy;
/**
* 构造函数,传入一个具体策略对象
* @param strategy
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
/**
* 策略方法
*/
public void contextMethod(){
strategy.strategyInterfaceMethod();
}
}
/**
* 具体环境类
*/
public Class ContextType1 extends Context{
public void contextMethod(){
strategy.strategyInterfaceMethod();
// todo something
}
}
应用场景: 多个用户购买不同型号电脑
</>复制代码
public class Client {
public static void main(String[] args) {
// 客户需要定制自己需要的策略
// 策略1--购买戴尔电脑
Strategy dell = new StrategyTypeA();
dell.setCPU("AMD");
dell.setScreen("LGD");
// 策略2
Strategy macbook = new StrategyTypeB();
macbook.setCPU("Intel");
macbook.setScreen("sansung");
// 购买的是dell电脑
// 用户将自己需要的策略(电脑配置)交给商家
ContextType1 customer1 = new ContextType1(dell);
// buyComputer方法中的strategy.strategyInterfaceMethod(); = StrategyTypeA.strategyInterfaceMethod();
customer1.buyComputer();
// 购买的是macbook
ContextType2 customer2 = new ContextType2(macbook);
// buyComputer方法中的strategy.strategyInterfaceMethod(); = StrategyTypeB.strategyInterfaceMethod();
customer2.buyComputer();
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71609.html
时间:2017年08月31日星期四说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学源码:https://github.com/zccodere/s...学习源码:https://github.com/zccodere/s... 第一章:策略模式简介 1-1 简介 课程大纲 什么是策略模式 策略模式如何实现 策略模式总结篇 实例案例分享 日常生活中的策略 Wor...
摘要:什么是策略模式策略模式,就是将不同的算法各自封装起来,然后根据程序的不同情况,采用不同的算法,有点像工厂模式。在其他语言中,实现这样的思路也比较费劲,而得函数非常灵活,本来可以当值传递,所以实现策略模式非常轻松,也很灵活。 什么是策略模式 策略模式,就是将不同的算法各自封装起来,然后根据程序的不同情况,采用不同的算法,有点像工厂模式。比如在很多种情况下,都要写ifXXX dosomet...
摘要:本篇主要讲述中使用函数来实现策略模式和命令模式,最后总结出这种做法背后的思想。 《流畅的Python》笔记。本篇主要讲述Python中使用函数来实现策略模式和命令模式,最后总结出这种做法背后的思想。 1. 重构策略模式 策略模式如果用面向对象的思想来简单解释的话,其实就是多态。父类指向子类,根据子类对同一方法的不同重写,得到不同结果。 1.1 经典的策略模式 下图是经典的策略模式的U...
摘要:设计模式系列之入门设计模式是一套被反复使用多数人知晓的经过分类编目的代码设计经验的总结。毫无疑问,设计模式于己于他人于系统都是多赢的设计模式使代码编制真正工程化设计模式是软件工程的基石脉络,如同大厦的结构一样。 PHP设计模式系列之入门 设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易...
阅读 2657·2023-04-26 00:57
阅读 989·2021-11-25 09:43
阅读 2380·2021-11-11 16:55
阅读 2412·2019-08-30 15:53
阅读 3669·2019-08-30 15:52
阅读 1543·2019-08-30 14:10
阅读 3452·2019-08-30 13:22
阅读 1284·2019-08-29 11:18