问题php
若是类的相关操做须要根据环境变化而变化,那么可能会须要将类分解为子类,可是若是经过继承数建立多个子类的话就会产生一些问题,致使继承树体系中的每一个分支中相关操做重复。当类必须支持同一个接口的多种实现时,最好的办法就是提取这些实现,并将他们防止在本身的类型中,而不是经过继承原有的类去支持这些实现。this
umlspa
代码实现code
<?php //strategy.php 策略模式 abstract class Question{ protected $prompt; protected $marker; function __construct($prompt,Marker $marker) { $this->prompt = $prompt; $this->marker = $marker; } function mark($response){ return $this->marker->mark($response); } } //文本问题 class TextQuestion extends Question{ } //语音问题 class AVquestion extends Question{ } abstract class Marker{ protected $test; abstract function mark($response); function __construct($test){ $this->test = $test; } } class MarkLogicMarker extends Marker{ function mark($response){ } } class MatchMarker extends Marker{ function mark($response){ return ($this->test==$response); } } class RegexpMarker extends Marker{ function mark($response){ return (preg_match($this->test,$response)); } } //client两个策略对象 $markers = array( new RegexpMarker('/f.ve/'), new MatchMarker('five') ); foreach ($markers as $marker) { echo get_class($marker)."<br>"; $questio = new TextQuestion("how many beans make five",$marker); foreach (array('five','four') as $response) { echo "\tresponse: $response: "; if($questio->mark($response)){ echo "well done<br>"; }else{ echo "never mind<br>"; } } } ?>