策略模式实例

<?php
class strategy{
	private $strategy;
	public function __construct($strategy){
		$this->strategy = $strategy;
	}

	public function getPrice(){
		return $this->strategy->getPrice();
	}
}

class twoDiscount{
	private $price;
	public function __construct($price){
		$this->price = $price;
	}

	public function getPrice(){
		return $this->price*0.2;
	}
}

class threeDiscount{
	private $price;
	public function __construct($price){
		$this->price = $price;
	}

	public function getPrice(){
		return $this->price*0.3;
	}
}


class Discount{
	private $type;
	public function __construct($type){
		$this->type = $type;		
	}

	public function getDiscountObj(){
		switch($this->type){
			case '2':
				return new strategy(new twoDiscount(10));
			break;
			case '3':
				return new strategy(new threeDiscount(10));
			break;
			default:
				return null;
		}
	}
}

$discount = new Discount(3);
$price =  $discount->getDiscountObj()->getPrice();

  

原文地址:https://www.cnblogs.com/qbyyqhcz/p/4666089.html