標籤:cat 鑽石 資訊 else bsp cas bar 符號 mba
裝飾模式:
<?phpabstract class Tile { abstract function getWealthFactor();}class Plains extends Tile { private $wealthfactor = 2; function getWealthFactor() { return $this->wealthfactor; }}abstract class TileDecorator extends Tile { // 裝飾 protected $tile; function __construct( Tile $tile ) { $this->tile = $tile; }}class DiamondDecorator extends TileDecorator { // 鑽石裝飾 function getWealthFactor() { return $this->tile->getWealthFactor()+2; }}class PollutionDecorator extends TileDecorator { // 汙染裝飾 function getWealthFactor() { return $this->tile->getWealthFactor()-4; }}$tile = new Plains();print $tile->getWealthFactor(); // 2$tile = new DiamondDecorator( new Plains());print $tile->getWealthFactor(); // 4$tile = new PollutionDecorator( new DiamondDecorator( new Plains()));print $tile->getWealthFactor(); // 0?> 組合模式:
<?phpabstract class Unit { abstract function bombardStrength();}class Archer extends Unit { function bombardStrength() { return 4; }}class LaserCannonUnit extends Unit { function bombardStrength() { return 44; }}class Army { private $units = array(); private $armies= array(); function addUnit( Unit $unit ) { array_push( $this->units, $unit ); } function addArmy( Army $army ) { array_push( $this->armies, $army ); } function bombardStrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardStrength(); } foreach( $this->armies as $army ) { $ret += $army->bombardStrength(); } return $ret; }}$unit1 = new Archer();$unit2 = new LaserCannonUnit();$army = new Army();$army->addUnit( $unit1 );$army->addUnit( $unit2 );print $army->bombardStrength();print "\n";$army2 = clone $army; // 複製軍隊$army->addArmy( $army2 );print $army->bombardStrength();print "\n";?> 原廠模式
<?php /** * 操作類 * 因為包含有抽象方法,所以類必須聲明為抽象類別 */ abstract class Operation{ //抽象方法不能包含函數體 abstract public function getValue($num1,$num2);//強烈要求子類必須實現該功能函數 } /** * 加法類 */ class OperationAdd extends Operation { public function getValue($num1,$num2){ return $num1+$num2; } } /** * 減法類 */ class OperationSub extends Operation { public function getValue($num1,$num2){ return $num1-$num2; } } /** * 乘法類 */ class OperationMul extends Operation { public function getValue($num1,$num2){ return $num1*$num2; } } /** * 除法類 */ class OperationDiv extends Operation { public function getValue($num1,$num2){ try { if ($num2==0){ throw new Exception("除數不能為0"); }else { return $num1/$num2; } }catch (Exception $e){ echo "錯誤資訊:".$e->getMessage(); } } /** * 工廠類,主要用來建立對象 * 功能:根據輸入的運算子號,工廠就能執行個體化出合適的對象 * */ class Factory{ public static function createObj($operate){ switch ($operate){ case ‘+‘: return new OperationAdd(); break; case ‘-‘: return new OperationSub(); break; case ‘*‘: return new OperationSub(); break; case ‘/‘: return new OperationDiv(); break; } } } $test=Factory::createObj(‘/‘); $result=$test->getValue(23,0); echo $result;?>
PHP常用設計模式匯總