状态模式(State Pattern)

百度词条的解释 http://baike.baidu.com/view/3589977.htm
<?php
//状态模式
//心情
abstract class MoodState {

	abstract function doSomething();

	public function changeState($mood) {
		$this->person->setState(new $mood($this->person));
	}

}

//生气
class Angry extends MoodState {

	protected $person;

	public function __construct(Person $person) {
		$this->person = $person;
	}

	public function doSomething() {
		echo 'I\'m angry!<br/>';
	}

}

//高兴
class Happy extends MoodState {

	protected $person;

	public function __construct(Person $person) {
		$this->person = $person;
	}

	public function doSomething() {
		echo 'I\'m happy!<br/>';
	}

}

//发狂
class Mad extends MoodState {

	protected $person;

	public function Mad(Person $person) {
		$this->person = $person;
	}

	public function doSomething() {
		echo 'I\'m Mad!<br/>';
	}

}

//Person
class Person {

	private $state;

	public function __construct($mood) {
		$this->state = new $mood($this);
	}

	public function setState(MoodState $state) {
		$this->state = $state;
	}

	public function doSomething($mood) {
		$this->state->doSomething();
		$this->state->changeState($mood);
	}

}

$person = new Person('Mad');
$person->doSomething('Happy');
$person->doSomething('Angry');
?>

你可能感兴趣的:(function,Class)