LoginSignup
1
0

More than 5 years have passed since last update.

GoFメモ - 1.Template Method

Last updated at Posted at 2018-04-26

ページ説明

PHPのデザインパターンの学習の記録として残すことにしました。

参照

こちらのサイトに大切なことはすべて書いてあります。
Do You PHP はてな

パターン一覧

ページを追記する度にリンクをつなげます

  • 1.Template Method
  • 2.Singleton
  • 3.Adapter
  • 4.Factory Method
  • 5.Façade
  • 6.Iterator
  • 7.Abstract Factory
  • 8.Bridge
  • 9.Builder
  • 10.Chain of Responsibility
  • 11.Command
  • 12.Composite
  • 13.Decorator
  • 14.Flyweight
  • 15.Interpreter
  • 16.Mediator
  • 17.Memento
  • 18.Observer
  • 19.Prototype
  • 20.Proxy
  • 21.State
  • 22.Strategy
  • 23.Visitor

1.Template Method

概要

完全に同じ場合は処理を親クラスに移したり別クラスを作成しメソッドを定義したりするが、一部ことなる場合などに用いるデザインパターン。
異なる処理の部分を分けて、各クラスごとにその処理を実装する。

特徴

  • 親クラスで処理の大枠を定義し、具体的な処理内容はサブクラスで行う。
  • 共通処理は親クラスにまとめるので、変更が発生した場合でも親クラス(AbstractCalss)を修正するだけで済む。
  • 親クラスで定義された抽象メソッドはサブクラス側で実装するので、サブクラスによって処理内容を変更することができる。

クラス構造

AbstractClass

処理の大きな枠食いを定義するクラスで、具体的な処理内容はサブクラスで実装する。

AbstractClass.php
// 処理の大きな枠組みを定義するメソッド
TemplateMethod()

// 抽象メソッドでサブクラスで中身は実装する
PrimitiveOperation1()
PrimitiveOperation2()

// ※抽象メソッドのようにサブクラスで実装することが期待されるメソッドの名前は「do~」が多いらしい。
ConcreteClass

AbstractClassを継承したサブクラス。AbstractClassで定義された抽象メソッドを実装する。
AbstractClassで枠組みを定義したメソッド(TemplateMethod())から呼び出される。

ConcreteClass.php
//親であるAbstractClassの抽象メソッドの具体的な実装。各サブクラス毎に異なる実装をおこなうことで、処理の詳細を変更することができる。
PrimitiveOperation1()
PrimitiveOperation2()

オブジェクト指向的要素

  • 継承
  • 親クラスでは具体的な処理内容をわざと抽象メソッドにし、サブクラスで実装するとことで、抽象メソッドの実装が保証される
  • サブクラス毎に実装内容を変更することができる
  • 親クラスがサブクラスのメソッドを呼び出す 制御構造の反転 

関連パターン

  • 4.Factory Method
  • 22.Strategy
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0