Home  >  Article  >  Backend Development  >  Example code sharing of PHP template method pattern

Example code sharing of PHP template method pattern

黄舟
黄舟Original
2017-03-17 09:55:471462browse

Template Method Pattern:

The Template Method pattern defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps. Template method pattern: Define the skeleton of an

algorithm in a method, and defer some steps to subclasses. The template method allows subclasses to Redefine certain steps in the algorithm.

##

<?php
// 模板方法模式

function echoLine($msg) {
	echo $msg, &#39;<br/>&#39;;
}

abstract class TemplateBase
{
	abstract function step1();
	abstract function step2();
	abstract function step3();
	
	public function doAction() {
		$this->step1();
		if(!$this->skipStep2()) {
			$this->step2();
		}
		$this->step3();
	}
	
	/**
	 * 钩子方法
	 */
	public function skipStep2() {
		return false;
	}
}

class ConcreteTemplate extends TemplateBase
{
	public function step1() {
		echoLine(&#39;This is step 1&#39;);
	}
	
	public function step2() {
		echoLine(&#39;This is step 2&#39;);
	}
	
	public function step3() {
		echoLine(&#39;This is step 3&#39;);
	}
	
	// 用来控制是否跳过某些步骤
	public function skipStep2() {
		return false;
	}
}

// test code
$ct = new ConcreteTemplate();
$ct->doAction();

The above is the detailed content of Example code sharing of PHP template method pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn