abstract class ApptEncoder{ abstract function encode(); } class BloggsApptEncoder extends ApptEncoder{ function encode(){ return 'this is bloggs object'; } } class MegaApptEncoder extends ApptEncoder{ function encode(){ return 'this is mega object'; } } abstract class CommsManager{ abstract function getHeaderText(); abstract function getApptEncoder(); abstract function getFooterText(); } class BloggsCommsManager extends CommsManager{ function getHeaderText(){ return 'this is bloggs header'; } function getApptEncoder(){ return new BloggsApptEncoder(); } function getFooterText(){ return 'this is bloggs footer'; } } class MegeCommsManger extends CommsManager{ function getHeaderText(){ return 'this is mega header'; } function getApptEncoder(){ return new MegaApptEncoder(); } function getFooterText(){ return 'this is mega footer'; } } class Settings{ static $COMMSTYPE = 'Bloggs'; } class AppConfig{ private static $instance; private $commsManager; //将构造方法设置为私有,可以防止继承 private function __construct(){ //只会运行一次 $this->init(); } private function init(){ switch (Settings::$COMMSTYPE){ case 'Mega': $this->commsManager = new MegaCommsManager(); break; default: $this->commsManager = new BloggsCommsManager(); } } public static function getInstance(){ if(empty(self::$instance)){ self::$instance = new self(); } return self::$instance; } public function getCommsManager(){ return $this->commsManager; } } $commsMgr = AppConfig::getInstance()->getCommsManager(); $commsMgr->getApptEncoder()->encode();