php 示例
最后更新于:2022-04-02 04:21:37
[TOC]
## 示例
### 概念示例
输出 ``` AbstractClass: baseOperation1 ConcreteClass1:requiredOperations1 AbstractClass: baseOperation2 ConcreteClass1:requiredOperation2 AbstractClass: baseOperation3 AbstractClass: baseOperation1 ConcreteClass2:requiredOperations1 AbstractClass: baseOperation2 ConcreteClass2:hook1 ConcreteClass2:requiredOperations2 AbstractClass: baseOperation3 ``` ## 社交网络的算法框架 在本例中, 模版方法模式定义了在社交网络上发布消息的算法框架。 每个子类都代表一个不同的社交网络, 它们虽以不同方式实现所有步骤, 但却会复用基本的算法。
';
main.go
``` baseOperation1(); $this->requiredOperations1(); $this->baseOperation2(); $this->hook1(); $this->requiredOperation2(); $this->baseOperation3(); $this->hook2(); } protected function baseOperation1(): void { echo "AbstractClass: baseOperation1\n"; } protected function baseOperation2(): void { echo "AbstractClass: baseOperation2\n"; } protected function baseOperation3(): void { echo "AbstractClass: baseOperation3\n"; } abstract protected function requiredOperations1(): void; abstract protected function requiredOperation2(): void; protected function hook1(): void { } protected function hook2(): void { } } class ConcreteClass1 extends AbstractClass { protected function requiredOperations1(): void { echo "ConcreteClass1:requiredOperations1\n"; } protected function requiredOperation2(): void { echo "ConcreteClass1:requiredOperation2\n"; } } class ConcreteClass2 extends AbstractClass { protected function requiredOperations1(): void { echo "ConcreteClass2:requiredOperations1\n"; } protected function requiredOperation2(): void { echo "ConcreteClass2:requiredOperations2\n"; } protected function hook1(): void { echo "ConcreteClass2:hook1\n"; } } function clientCode(AbstractClass $class) { // ... $class->templateMethod(); // ... } clientCode(new ConcreteClass1()); echo "\n"; clientCode(new ConcreteClass2()); ```输出 ``` AbstractClass: baseOperation1 ConcreteClass1:requiredOperations1 AbstractClass: baseOperation2 ConcreteClass1:requiredOperation2 AbstractClass: baseOperation3 AbstractClass: baseOperation1 ConcreteClass2:requiredOperations1 AbstractClass: baseOperation2 ConcreteClass2:hook1 ConcreteClass2:requiredOperations2 AbstractClass: baseOperation3 ``` ## 社交网络的算法框架 在本例中, 模版方法模式定义了在社交网络上发布消息的算法框架。 每个子类都代表一个不同的社交网络, 它们虽以不同方式实现所有步骤, 但却会复用基本的算法。