PHP面向对象程序设计之对象生成方法详解(2)

<?php // 根据类图,规划类的代码。从大局入手。 abstract class ApptEncoder { abstract function encode(); } class BloggsApptEncoder extends ApptEncoder { function encode() { return "Appointment data encoded in BloggsCal format\n"; } } class MegaApptEncoder extends ApptEncoder { function encode() { return "Appointment data encoded in MegaCal format\n"; } } abstract class CommsManager { const APPT = 1; const TTD = 2; const CONTACT = 3; abstract function getHeaderText(); abstract function make( $flag_int ); // int标记 abstract function getFooterText(); } class BloggsCommsManager extends CommsManager { function getHeaderText() { return "BloggsCal header\n"; } function make( $flag_int ) { switch ( $flag_int ) { case self::APPT: // self直接控制常量 return new BloggsApptEncoder(); case self::CONTACT: return new BloggsContactEncoder(); case self::TTD: return new BloggsTtdEncoder(); } } function getFooterText() { return "BloggsCal footer\n"; } } $mgr = new BloggsCommsManager(); print $mgr->getHeaderText(); print $mgr->make( CommsManager::APPT )->encode(); print $mgr->getFooterText(); ?>

output:

BloggsCal header
Appointment data encoded in BloggsCal format
BloggsCal footer

原型模式

改造成一个保存具体产品的工厂类。

<?php class Sea {} // 大海 class EarthSea extends Sea {} class MarsSea extends Sea {} class Plains {} // 平原 class EarthPlains extends Plains {} class MarsPlains extends Plains {} class Forest {} // 森林 class EarthForest extends Forest {} class MarsForest extends Forest {} class TerrainFactory { // 地域工厂 private $sea; private $forest; private $plains; function __construct( Sea $sea, Plains $plains, Forest $forest ) { // 定义变量为类对象 $this->sea = $sea; $this->plains = $plains; $this->forest = $forest; } function getSea( ) { return clone $this->sea; // 克隆 } function getPlains( ) { return clone $this->plains; } function getForest( ) { return clone $this->forest; } } $factory = new TerrainFactory( new EarthSea(), new EarthPlains(), new EarthForest() ); print_r( $factory->getSea() ); print_r( $factory->getPlains() ); print_r( $factory->getForest() ); ?>

output:

EarthSea Object ( ) EarthPlains Object ( ) EarthForest Object ( )

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/d89c4feb0fae90157057f796f8c324d0.html