PHP面向对象程序设计之对象生成方法详解
本文实例讲述了PHP面向对象程序设计之对象生成方法。分享给大家供大家参考,具体如下:
对象
看个例子
<?php abstractclassEmployee{//雇员 protected$name; function__construct($name){ $this->name=$name; } abstractfunctionfire(); } classMinionextendsEmployee{//奴隶继承雇员 functionfire(){ print"{$this->name}:I'llclearmydesk\n"; } } classNastyBoss{//坏老板 private$employees=array(); functionaddEmployee($employeeName){//添加员工 $this->employees[]=newMinion($employeeName);//代码灵活性受到限制 } functionprojectFails(){ if(count($this->employees)>0){ $emp=array_pop($this->employees); $emp->fire();//炒鱿鱼 } } } $boss=newNastyBoss(); $boss->addEmployee("harry"); $boss->addEmployee("bob"); $boss->addEmployee("mary"); $boss->projectFails(); //output: //mary:I'llclearmydesk ?>
再看一个更具有灵活性的案例
<?php abstractclassEmployee{ protected$name; function__construct($name){ $this->name=$name; } abstractfunctionfire(); } classMinionextendsEmployee{ functionfire(){ print"{$this->name}:I'llclearmydesk\n"; } } classNastyBoss{ private$employees=array(); functionaddEmployee(Employee$employee){//传入对象 $this->employees[]=$employee; } functionprojectFails(){ if(count($this->employees)){ $emp=array_pop($this->employees); $emp->fire(); } } } //newEmployeeclass... classCluedUpextendsEmployee{ functionfire(){ print"{$this->name}:I'llcallmylawyer\n"; } } $boss=newNastyBoss(); $boss->addEmployee(newMinion("harry"));//直接以对象作为参数,更具有灵活性 $boss->addEmployee(newCluedUp("bob")); $boss->addEmployee(newMinion("mary")); $boss->projectFails(); $boss->projectFails(); $boss->projectFails(); //output: //mary:I'llclearmydesk //bob:I'llcallmylawyer //harry:I'llclearmydesk ?>
单例
<?php classPreferences{ private$props=array(); privatestatic$instance;//私有的,静态属性 privatefunction__construct(){}//无法实例化,私有的构造函数 publicstaticfunctiongetInstance(){//返回对象静态方法才可以被类访问,静态方法中要有静态属性 if(empty(self::$instance)){ self::$instance=newPreferences(); } returnself::$instance; } publicfunctionsetProperty($key,$val){ $this->props[$key]=$val; } publicfunctiongetProperty($key){ return$this->props[$key]; } } $pref=Preferences::getInstance(); $pref->setProperty("name","matt"); unset($pref);//removethereference $pref2=Preferences::getInstance(); print$pref2->getProperty("name")."\n";//demonstratevalueisnotlost ?>
点评:不能随意创建对象,只能通过Preferences::getInstance()来创建对象。
工厂模式
<?php abstractclassApptEncoder{ abstractfunctionencode(); } classBloggsApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinBloggsCalformat\n"; } } classMegaApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinMegaCalformat\n"; } } classCommsManager{//负责生产Bloggs对象 functiongetApptEncoder(){ returnnewBloggsApptEncoder(); } } $obj=newCommsManager(); $bloggs=$obj->getApptEncoder();//获取对象 print$bloggs->encode(); ?>
output:
AppointmentdataencodedinBloggsCalformat
进一步增加灵活性设置
<?php abstractclassApptEncoder{ abstractfunctionencode(); } classBloggsApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinBloggsCalformat\n"; } } classMegaApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinMegaCalformat\n"; } } classCommsManager{ constBLOGGS=1; constMEGA=2; private$mode; function__construct($mode){ $this->mode=$mode; } functiongetHeaderText(){ switch($this->mode){ case(self::MEGA): return"MegaCalheader\n"; default: return"BloggsCalheader\n"; } } functiongetApptEncoder(){ switch($this->mode){ case(self::MEGA): returnnewMegaApptEncoder(); default: returnnewBloggsApptEncoder(); } } } $man=newCommsManager(CommsManager::MEGA); print(get_class($man->getApptEncoder()))."\n"; $man=newCommsManager(CommsManager::BLOGGS); print(get_class($man->getApptEncoder()))."\n"; ?>
output:
MegaApptEncoder
BloggsApptEncoder
工厂方法模式要把创建者类与要生产的产品类分离开来。
抽象工厂
通过抽象来来约束,成为一定的规矩。
<?php abstractclassApptEncoder{ abstractfunctionencode(); } classBloggsApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinBloggsCalformat\n"; } } classMegaApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinMegaCalformat\n"; } } abstractclassCommsManager{//预约 abstractfunctiongetHeaderText(); abstractfunctiongetApptEncoder(); abstractfunctiongetTtdEncoder(); abstractfunctiongetContactEncoder(); abstractfunctiongetFooterText(); } classBloggsCommsManagerextendsCommsManager{ functiongetHeaderText(){ return"BloggsCalheader\n"; } functiongetApptEncoder(){ returnnewBloggsApptEncoder(); } functiongetTtdEncoder(){ returnnewBloggsTtdEncoder(); } functiongetContactEncoder(){ returnnewBloggsContactEncoder(); } functiongetFooterText(){ return"BloggsCalfooter\n"; } } classMegaCommsManagerextendsCommsManager{ functiongetHeaderText(){ return"MegaCalheader\n"; } functiongetApptEncoder(){ returnnewMegaApptEncoder(); } functiongetTtdEncoder(){ returnnewMegaTtdEncoder(); } functiongetContactEncoder(){ returnnewMegaContactEncoder(); } functiongetFooterText(){ return"MegaCalfooter\n"; } } $mgr=newMegaCommsManager(); print$mgr->getHeaderText(); print$mgr->getApptEncoder()->encode();//对象调用方法,返回对象,继续调用方法。 print$mgr->getFooterText(); ?>
output:
MegaCalheader
AppointmentdataencodedinMegaCalformat
MegaCalfooter
更加牛逼的实现
<?php //根据类图,规划类的代码。从大局入手。 abstractclassApptEncoder{ abstractfunctionencode(); } classBloggsApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinBloggsCalformat\n"; } } classMegaApptEncoderextendsApptEncoder{ functionencode(){ return"AppointmentdataencodedinMegaCalformat\n"; } } abstractclassCommsManager{ constAPPT=1; constTTD=2; constCONTACT=3; abstractfunctiongetHeaderText(); abstractfunctionmake($flag_int);//int标记 abstractfunctiongetFooterText(); } classBloggsCommsManagerextendsCommsManager{ functiongetHeaderText(){ return"BloggsCalheader\n"; } functionmake($flag_int){ switch($flag_int){ caseself::APPT://self直接控制常量 returnnewBloggsApptEncoder(); caseself::CONTACT: returnnewBloggsContactEncoder(); caseself::TTD: returnnewBloggsTtdEncoder(); } } functiongetFooterText(){ return"BloggsCalfooter\n"; } } $mgr=newBloggsCommsManager(); print$mgr->getHeaderText(); print$mgr->make(CommsManager::APPT)->encode(); print$mgr->getFooterText(); ?>
output:
BloggsCalheader
AppointmentdataencodedinBloggsCalformat
BloggsCalfooter
原型模式
改造成一个保存具体产品的工厂类。
<?php classSea{}//大海 classEarthSeaextendsSea{} classMarsSeaextendsSea{} classPlains{}//平原 classEarthPlainsextendsPlains{} classMarsPlainsextendsPlains{} classForest{}//森林 classEarthForestextendsForest{} classMarsForestextendsForest{} classTerrainFactory{//地域工厂 private$sea; private$forest; private$plains; function__construct(Sea$sea,Plains$plains,Forest$forest){//定义变量为类对象 $this->sea=$sea; $this->plains=$plains; $this->forest=$forest; } functiongetSea(){ returnclone$this->sea;//克隆 } functiongetPlains(){ returnclone$this->plains; } functiongetForest(){ returnclone$this->forest; } } $factory=newTerrainFactory(newEarthSea(), newEarthPlains(), newEarthForest()); print_r($factory->getSea()); print_r($factory->getPlains()); print_r($factory->getForest()); ?>
output:
EarthSeaObject ( ) EarthPlainsObject ( ) EarthForestObject ( )
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。