一、问题

  模拟不同课程有不同的收费方式,并且能灵活改变(新增或删减),如讲座可以固定收费也可改为按时收费,研讨会也是。

二、模式简介及关键点

1.在父类代码中使用条件语句是一种退倒,可以用多态来代替条件语句。条件语句有时被称作实现了一个“模拟继承”

2.策略模式适用于将一组算法移入到一个独立的类型中。如例子通过移走费用计算的相关代码,可以简化Lesson类型

3.在合理的模式中,Lesson类不负责计费,而是把计费任务“委托”给CostStrategy类。这种显式调用另一个对象的方法来执行一个请求的方式便是所谓的“委托”

4.让类专注自己的职责。CostStrategy负责计费,Lesson类负责管理课程数据

5.把变化的概念封装起来,本例变化的概念便是费用算法。变化的元素可被提取出来形成子类,而这些元素共同拥有一个抽象父类CostStrategy,这个类可以被其他类使用

三、不好的设计方式

1.定价策略被不同的子类重复实现,我们不得不重复开发功能 ,即使用if语句把定价逻辑移到父类中,也与多态替换条件的重构思想背道而驰

使用if语句把定价逻辑移到父类中后的结构

代码如下:

<?php
abstract class Lesson {
protected $duration;
const FIXED = 1;
const TIMED = 2;
private $costtype; function __construct( $duration, $costtype=1 ) {
$this->duration = $duration;
$this->costtype = $costtype;
} function cost() {
switch ( $this->costtype ) {
CASE self::TIMED :
return (5 * $this->duration);
break;
CASE self::FIXED :
return 30;
break;
default:
$this->costtype = self::FIXED;
return 30;
}
} function chargeType() {
switch ( $this->costtype ) {
CASE self::TIMED :
return "hourly rate";
break;
CASE self::FIXED :
return "fixed rate";
break;
default:
$this->costtype = self::FIXED;
return "fixed rate";
}
} // more lesson methods...
} class Lecture extends Lesson {
// Lecture-specific implementations ...
} class Seminar extends Lesson {
// Seminar-specific implementations ...
} $lecture = new Lecture( 5, Lesson::FIXED );
print "{$lecture->cost()} ({$lecture->chargeType()})\n"; $seminar= new Seminar( 3, Lesson::TIMED );
print "{$seminar->cost()} ({$seminar->chargeType()})\n";
?>

 运行结果:

30 (fixed rate) 15 (hourly rate)

  

 

四、策略模式(组合模式)-》把变化的部分(定价)封装

代码如下:

<?php
abstract class Lesson {
private $duration;
private $costStrategy; function __construct( $duration, CostStrategy $strategy ) {
$this->duration = $duration;
$this->costStrategy = $strategy;
} function cost() {
return $this->costStrategy->cost( $this );
} function chargeType() {
return $this->costStrategy->chargeType( );
} function getDuration() {
return $this->duration;
} // more lesson methods...
} abstract class CostStrategy {
abstract function cost( Lesson $lesson );
abstract function chargeType();
} class TimedCostStrategy extends CostStrategy {
function cost( Lesson $lesson ) {
return ( $lesson->getDuration() * 5 );
}
function chargeType() {
return "hourly rate";
}
} class FixedCostStrategy extends CostStrategy {
function cost( Lesson $lesson ) {
return 30;
} function chargeType() {
return "fixed rate";
}
} class Lecture extends Lesson {
// Lecture-specific implementations ...
} class Seminar extends Lesson {
// Seminar-specific implementations ...
} $lessons[] = new Seminar( 4, new TimedCostStrategy() );
$lessons[] = new Lecture( 4, new FixedCostStrategy() ); foreach ( $lessons as $lesson ) {
print "lesson charge {$lesson->cost()}. ";
print "Charge type: {$lesson->chargeType()}\n";
}
?>

运行结果:

lesson charge 20. Charge type: hourly rate lesson charge 30. Charge type: fixed rate

  

  

五、另一方面,降低耦合

代码如下:

<?php
abstract class Lesson {
private $duration;
private $costStrategy; function __construct( $duration, CostStrategy $strategy ) {
$this->duration = $duration;
$this->costStrategy = $strategy;
} function cost() {
return $this->costStrategy->cost( $this );
} function chargeType() {
return $this->costStrategy->chargeType( );
} function getDuration() {
return $this->duration;
} // more lesson methods...
} abstract class CostStrategy {
abstract function cost( Lesson $lesson );
abstract function chargeType();
} class TimedCostStrategy extends CostStrategy {
function cost( Lesson $lesson ) {
return ( $lesson->getDuration() * 5 );
} function chargeType() {
return "hourly rate";
}
} class FixedCostStrategy extends CostStrategy {
function cost( Lesson $lesson ) {
return 30;
} function chargeType() {
return "fixed rate";
}
} class Lecture extends Lesson {
// Lecture-specific implementations ...
} class Seminar extends Lesson {
// Seminar-specific implementations ...
} class RegistrationMgr {
function register( Lesson $lesson ) {
// do something with this Lesson // now tell someone
$notifier = Notifier::getNotifier();
$notifier->inform( "new lesson: cost ({$lesson->cost()})" );
}
} abstract class Notifier { static function getNotifier() {
// acquire concrete class according to
// configuration or other logic if ( rand(1,2) == 1 ) {
return new MailNotifier();
} else {
return new TextNotifier();
}
} abstract function inform( $message );
} class MailNotifier extends Notifier {
function inform( $message ) {
print "MAIL notification: {$message}\n";
}
} class TextNotifier extends Notifier {
function inform( $message ) {
print "TEXT notification: {$message}\n";
}
}
$lessons1 = new Seminar( 4, new TimedCostStrategy() );
$lessons2 = new Lecture( 4, new FixedCostStrategy() );
$mgr = new RegistrationMgr();
$mgr->register( $lessons1 );
$mgr->register( $lessons2 ); ?>

 运行结果:

TEXT notification: new lesson: cost (20) MAIL notification: new lesson: cost (30)

  

PHP组合模式、策略模式的更多相关文章

  1. 3.js模式-策略模式

    1. 策略模式 策略模式定义一系列的算法,把它们封装起来,并且可以互相替换. var strategies = { isNonEmpty: function(value,errMsg){ if(val ...

  2. 命令模式 & 策略模式 & 模板方法

    一.策略模式 策略模式:封装易变化的算法,可互相替换. GoF<设计模式>中说道:定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换.该模式使得算法可独立于它们的客户变化. 比如 ...

  3. 工厂模式&策略模式。

    抽象.封装,具体事情做得越多,越容易犯错误.这每个做过具体工作的人都深有体会,相反,官做得越高,说出的话越抽象越笼统,犯错误可能性就越少.好象我们从编程序中也能悟出人生道理.(百度百科) 不断抽象封装 ...

  4. 简单工厂模式&策略模式-简介与区别

    不得不说,这两种模式真的很像. 相似点:都用到了面向对象的继承.多态.抽象,都拥有相似的结构. 不同点:工厂模式仅提供具体的实例对象,怎么使用这个对象是client的自由,策略模式client可以通过 ...

  5. java设计模式--行为型模式--策略模式

    策略模式: 策略模式 概述 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换.本模式使得算法可独立于使用它的客户而变化. 适用性 1.许多相关的类仅仅是行为有异.“策略”提供了一种用多个行 ...

  6. [Python模式]策略模式

    策略模式 定义了算法族,分别封装起来,让它们之间可以互相替换.此模式让算法的变化独立于使用算法的客户. 作为动态语言,Python实现策略模式非常容易,只要所有算法提供相同的函数即可. import ...

  7. <大话设计模式>工厂模式,策略模式

    第一章:工厂模式: 通过封装,继承,多态解耦合 业务逻辑和界面逻辑分开 用单独的类创造实例,工厂:创造实例 工厂模式还可以用反射来实现,nsstringFromClass UML类图 聚合表示一众弱的 ...

  8. 设计模式之——浅谈strategy模式(策略模式)

    strategy模式,即策略模式.个人觉得吧,策略模式更多的是一种思维方式. 首先我们要知道,为什么需要策略模式.举个例子,比如用程序输出今天下午去玩什么. PlayGame 玩游戏 package ...

  9. [19/05/01-星期三] GOF23_行为型模式(策略模式、模板方法模式)

    一.策略模式(strategy) [策略接口] /*** * "策略"接口 */ package cn.sxt.strategy; public interface Strateg ...

  10. Go---设计模式(策略模式)

    策略模式定义了算法家族,在调用算法家族的时候不感知算法的变化,客户也不会受到影响. 下面用<大话设计模式>中的一个实例进行改写. 例:超市中经常进行促销活动,促销活动的促销方法就是一个个策 ...

随机推荐

  1. asf与vga视频为何无法同步播放?我来给你解释!

    因为你的笔记本可以,所以你的台式机不可以,当然跟深刻的原因是,你的笔记本有什么特别硬件

  2. sublime mac快捷键

    ^是control ⌥是option 打开/前往 ⌘T 前往文件 ⌘⌃P 前往项目 ⌘R 前往 method ⌘⇧P 命令提示 ⌃G 前往行 ⌘KB 开关侧栏 ⌃ ` python 控制台 ⌘⇧N 新 ...

  3. [无人值守安装操作系统]__RHEL6__FTP+TFTP+DHCP+Kickstart+PXE

    实验环境 1.实验平台:VMware Workstation 10 2.实验OS:RHEL6 3.服务器A: (1) 10.0.10.158 (2) DHCP/FTP/TFTP (3) 有可使用的yu ...

  4. JPA学习---第九节:JPA中的一对多双向关联与级联操作

    一.一对多双向关联与级联操作 1.创建项目,配置文件代码如下: <?xml version="1.0" encoding="UTF-8"?> < ...

  5. asdoc 档案

    1.asdoc air项目会出现无法找到NativeApplication等错误 解决办法:add args   -load-config ....../frameworks/air-config.x ...

  6. linux free 命令

    命 令: free 功能说明:显示内存状态. 语 法: free [-bkmotV][-s <间隔秒数>] 补充说明:free指令会显示内存的使用情况,包括实体内存,虚拟的交换文件内存,共 ...

  7. AlarmManager使用注意事项

    在使用AlarmManager实现闹钟需要注意的是,intent和pendingintend的context如果是activity,那么当activity回收之后,context对象则不能被Alarm ...

  8. javascript与DOM -- 深入理解javascript

    /* 一.文档对象模型Document Object Model DOM(Document Object Model,文档对象模型)是一个通过和JavaScript进行内容交互的API */ /* 注 ...

  9. HDU 1598 find the most comfortable road 并查集+贪心

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1598 find the most comfortable road Time Limit: 1000 ...

  10. 临时文档9--dfs

    #include<iostream> #include<stdio.h> #include<math.h> #include<string.h> usi ...