php面向对象的开发过程中,不仅仅是把共同的方法抽象成类,还要对生成对象的策略有所了解
工厂方法模式:一层层继承类,达到最终实现所有方法的目的
抽象工厂模式:最大化的把客类实现抽象化
原型模式:通过克隆的方法获取对象
说的很抽象,用代码说明吧,大家细细品味,欢迎大家指正
工厂方法模式:
//工厂方法模式
abstract class appEncoder{
abstract function encode();
}
class BlogAppEncoder extends appEncoder{
function encode(){
return "encode in Blog format\n";
}
}
class MegaAppEncoder extends appEncoder{
function encode(){
return "encode in Blog format\n";
}
}
abstract class CommsManager{
abstract function getHeader();
abstract function getAppEncoder();
abstract function getFooter();
}
class BlogCommsManager extends CommsManager{
function getHeader(){
return "BloggsCal header\n";
}
function getAppEncoder()
{
return new BlogAppEncoder();
}
function getFooter(){
return "Bloggscal footer\n";
}
}
class MegaCommsManager extends CommsManager{
function getHeader(){
return "MegaCal header\n";
}
function getAppEncoder()
{
return new MegaAppEncoder();
}
function getFooter(){
return "Megacal footer\n";
}
}
抽象工厂模式
abstract class CommsManager{
const APP = 1;
const TTD = 2;
const CONTRACT = 3;
abstract function getHeader();
abstract function make($flag_in);
abstract function getFooter();
}
class BlogCommsManager extends CommsManager{
function getHeader(){
return "blog header\n";
}
function make($flag_in){
switch($flag_in)
{
case self::APP:
return new BlogAppEncoder();
case self::TTD:
return new BlogTtdEncoder();
case self::CONTRACT:
return new BlogConEncoder();
}
return new BlogAppEncoder();
}
function getFooter(){
return "blog footer\n";
}
}
原型模式
//原型模式
class Sea{};
class EarthSea extends Sea{};
class MarSea extends Sea{};
class Plains{};
class EarthPlains extends Plains{};
class MarPlains extends Plains{};
class Foreast{};
class EarthForeast extends Foreast{};
class MarForeast extends Foreast{};
class TerrainFactory{
Private $sea;
Private $plains;
Private $Foreast;
function __construct(Sea $sea,Plains $plains, Foreast $foreast){
$this->sea = $sea;
$this->plains = $plains;
$this->foreast = $foreast;
}
function getSea()
{
return clone $this->sea;
}
function getPlains(){
return clone $this->plains;
}
function getForeast(){
return clone $this->foreast;
}
}
$factory = new TerrainFactory(new EarthSea(), new EarthPlains(), new EarthForeast());
print_r($factory->getSea());
print_r($factory->getPlains());
print_r($factory->getForeast());