CommManager 類中的 getApptEncoder() 方法 專門用來負責生成相應的對象。
如下代碼來自《深刻PHP 面向對象、模式與實踐》(第三版)第9章
<?php/** * Created by PhpStorm. * User: Eilen * Date: 2018/9/2 * Time: 8:40 */abstract class ApptEncoder{ abstract function encode();}class BloggsApptEncoder extends ApptEncoder{ public function encode() { return 'Appointment data encoded in BloggsCal format\n'; }}class MegaApptEncoder extends ApptEncoder{ public function encode() { return 'Appointment data encoded in MegaCal format\n'; }}class CommManager{ const BLOGGS = 1; const MEGA =2; private $mode; function __construct($mode) { $this->mode = $mode; } function getHeaderText() { switch ($this->mode){ case (self::MEGA): return 'MegaCal header\n'; default: return 'BloggsCal header\n'; } } function getApptEncoder() { switch ($this->mode){ case (self::MEGA): return new MegaApptEncoder(); default: return new BloggsApptEncoder(); } }}//引用工廠模式$comm = new CommManager(CommManager::MEGA);$mega = $comm->getApptEncoder();echo $mega->encode();