abstract class Journey {
final public function takeATrip() {
$this->buyAFlight();
$this->takePlane();
$this->enjoyVacation();//!!!
$this->buyGift();
$this->takePlane();
}
//key feature
abstract protected function enjoyVacation();
//optional.
protected function buyGift() {
}
/**
* This method will be unknown by subclasses (better)
*/
private function buyAFlight() {
echo "Buying a flight\n";
}
final protected function takePlane() {
echo "Taking the plane\n";
}
}
class CityJourney extends Journey {
protected function enjoyVacation() {
echo "Eat, drink, take photos and sleep\n";
}
}
class BeachJourney extends Journey{
protected function enjoyVacation() {
echo "Swimming and sun-bathing\n";
}
}
$journey = new BeachJourney();
$journey->takeATrip();
//Buying a flight
//Taking the plane
//Swimming and sun-bathing
$journey = new CityJourney();
$journey->takeATrip();
php-设计模式-模板方法模式
最新推荐文章于 2024-09-27 21:35:31 发布