发新话题
打印

[电脑编程] 设计模式的PHP5代码示例(转自PHPchina) 强烈推荐给每一个PHPer

设计模式的PHP5代码示例(转自PHPchina) 强烈推荐给每一个PHPer

我想设计模式这个名词对于每一个程序员一定不会陌生,自从GOP的23种设计模式被提出后,设计模式在C++,java,.net等开发平台语言上发展迅速,但是广大PHPer却很少涉足这方面,所以针对PHP设计模式的资料是少之又少。

今天在PHPchina上看到了一篇帖子,他给出了PHP实现各种设计模式的范例代码。在这里我转到这里,希望能起到抛砖引玉的作用,对咱学校的PHPer有所启发

TOP

1创建模式之Factory Method

1产品:
[复制PHP代码]
PHP代码如下:

<?php
interface Car
{
  function
run
();
}

class
BMWCar implements Car
{
  function
run(){echo "BMW running \n"
;}
}
class
FordCar implements Car
{
  function
run(){echo "Ford car running \n"
;}
}

?>



2简单工厂
[复制PHP代码]
PHP代码如下:

/**
* 简单工厂
*
*/
class SimpleCarFactory
{

  
/**
   * 工厂方法
   *
   * @param string $type
   * @return Car
   */
  
static function create($type
){
    if (
$type=='BMW'
) {
        return new
BMWCar
();
    }elseif (
$type=='Ford'
) {
        return new
FordCar
();
    }
    throw new
Exception("not such car type $type"
);
  }
}

$car=SimpleCarFactory::create('BMW'
);
$car->run();



3将工厂进行抽象
[复制PHP代码]
PHP代码如下:

interface Factory {
  
/**
   * @return Car
   */
  
function create
();
}

class
BMWFactory implements Factory
{

  function
create(){return new BMWCar
();}
}

class
FordFactory implements Factory
{

  function
create() {return new FordCar
();}
}

function
carTest(Factory $factory
){
  echo
'<pre>'
;
  
$car=$factory->create
();
  
$car->run
();
}

carTest(new BMWFactory
());
carTest(new FordFactory());


TOP

2创建模式之Abstract Factory


[复制PHP代码]
PHP代码如下:

<?php
interface Truck
{
  function
run
();
}

interface
SportCar
{
  function
compete
();
}

class
DongfengTruck implements Truck
{
  function
run
(){
    echo
"Dongfeng truck running\n"
;
  }
}

class
DongfengSportCar implements SportCar
{
  function
compete
(){
    echo
"Dongfeng sport car running\n"
;
  }
}

class
FordTruck implements Truck
{
  function
run
(){
    echo
"Ford truck running\n"
;
  }
}

class
FordCar implements SportCar
{
  function
compete
(){
    echo
"Ford car running\n"
;
  }
}

interface
Factory
{
  
/**
   * @return Truck
   */
  
function createTruck
();
  
/**
   * @return SportCar
   */
  
function createCar
();
}

class
FordFactory implements Factory
{
  function
createTruck
(){
    return new
FordTruck
();
  }
  function
createCar
(){
    return new
FordCar
();
  }
}

class
DongfengFactory implements Factory
{
  function
createTruck
(){
    return new
DongfengTruck
();
  }
  function
createCar
(){
    return new
DongfengSportCar
();
  }
}

function
factoryTest(Factory $factory
){
  
$truck=$factory->createTruck
();
  
$car=$factory->createCar
();
  echo
'<pre>'
;
  
$truck->run
();
  
$car->compete
();
}

factoryTest(new FordFactory
());
factoryTest(new DongfengFactory
());
?>


TOP

3创建模式之Prototype

复制已有的对象

由于php5使用引用传递对象,所以等号并不能复制对象.


1: 浅复制 clone关键字
[复制PHP代码]
PHP代码如下:

class Dog {
  private
$name
;
  
/**
   * 构造器
   *
   * @param string $name
   */
  
function __construct($name
){
   
$this->name=$name
;
  }
  
/**
   * 获取狗名,调试之用
   *
   * @return string
   */
  
function getName
(){
    return
$this->name
;
  }
}
  
$pet=new Dog('Spot'
);
  echo
'<pre>'
;
  echo
$pet,": class=".get_class($pet)," name=".$pet->getName(),"\n"
;
  
$clone=clone $pet
;
  echo
$clone,": class=".get_class($clone)," name=".$clone->getName(),"\n";



2: 魔术方法深复制
[复制PHP代码]
PHP代码如下:

class Phone {
  private
$id
;
  function
__construct($id
){
   
$this->id=$id
;
  }
  function
getId
(){
    return
$this->id
;
  }
}

class
Man
{
  private
$name
;
  
/**
   * @var Phone
   */
  
private $phone
;
  function
__construct($name
){
   
$this->name=$name
;
  }
  function
setPhone(Phone $phone
){
   
$this->phone=$phone
;
  }
  
/**
   * @return Phone
   */
  
function getPhone
(){
    return
$this->phone
;
  }
  function
getName
(){
    return
$this->name
;
  }
  
/**
   * 克隆时调用的魔术方法
   *
   */
  
function __clone
(){
   
//将手机一并复制,
    //如果注释掉,克隆人将和原来的人共用一部手机
   
$this->phone=clone $this->phone
;
  }
}

  
$phone=new Phone('2110'
);
  
$man=new Man('Nicholas'
);
  
$man->setPhone($phone
);

  echo
'<pre>'
;
  echo
"\n$man is ".get_class($man)." has name: ".$man->getName
();
  echo
"\nhas a:"
;
  
$manPhone=$man->getPhone
();
  echo
"\n$manPhone is ".get_class($manPhone)." has id: ".$manPhone->getId
();
  echo
"\n\n\n"
;
  
$cloneMan=clone $man
;
  echo
"\n$cloneMan is ".get_class($cloneMan)." has name: ".$cloneMan->getName
();
  echo
"\nhas a:"
;
  
$manPhone=$cloneMan->getPhone
();
  echo
"\n$manPhone is ".get_class($manPhone)." has id: ".$manPhone->getId
();
  echo
"\n\n\n";



TOP

3: 序列化深复制
[复制PHP代码]
PHP代码如下:

class Phone {
  private
$id
;
  function
__construct($id
){
   
$this->id=$id
;
  }
  function
getId
(){
    return
$this->id
;
  }
}

class
Man
{
  private
$name
;
  
/**
   * @var Phone
   */
  
private $phone
;
  function
__construct($name
){
   
$this->name=$name
;
  }
  function
setPhone(Phone $phone
){
   
$this->phone=$phone
;
  }
  
/**
   * @return Phone
   */
  
function getPhone
(){
    return
$this->phone
;
  }
  function
getName
(){
    return
$this->name
;
  }
}

  
$phone=new Phone('2110'
);
  
$man=new Man('Nicholas'
);
  
$man->setPhone($phone
);

  echo
'<pre>'
;
  echo
"\n$man is ".get_class($man)." has name: ".$man->getName
();
  echo
"\nhas a:"
;
  
$manPhone=$man->getPhone
();
  echo
"\n$manPhone is ".get_class($manPhone)." has id: ".$manPhone->getId
();
  echo
"\n\n\n"
;
  
/*在内存中序列化并反序列化*/
  
$cloneMan=unserialize(serialize($man
));
  echo
"\n$cloneMan is ".get_class($cloneMan)." has name: ".$cloneMan->getName
();
  echo
"\nhas a:"
;
  
$manPhone=$cloneMan->getPhone
();
  echo
"\n$manPhone is ".get_class($manPhone)." has id: ".$manPhone->getId
();
  echo
"\n\n\n";




TOP

4创建模式之Builder


[复制PHP代码]
PHP代码如下:

<?php

interface Part
{
  function
work
();
}

interface
PartFactory
{
  
/**
   * @return Part
   *
   */
  
function build
();
}

interface
Builder
{
  
/**
   * @return Cpu
   */
  
function buildCpu
();
  
/**
   * @return MainBoard
   */
  
function buildMainBoard
();
  
/**
   * @return Ram
   */
  
function buildRam
();
  
/**
   * @return VideoCard
   */
  
function buildVideoCard
();
  
/**
   * @return Power
   */
  
function buildPower
();
}

class
Computer
{

  private
$parts
=array();

  function
addPart(Part $part
){
   
$this->parts[]=$part
;
  }

  function
run
(){
   
/*@var $part Part*/
   
echo '<pre>'
;
    echo
$this," working \n"
;
    foreach (
$this->parts as $part
) {
        
$part->work
();
        echo
"\n"
;
    }
  }
}

class
Cpu implements Part
{
  function
work(){echo 'cpu: '. get_class($this).' running'
;}
}

class
MainBoard implements Part
{
  function
work(){echo 'main board: '.get_class($this).' running'
;}
}

class
Power implements Part
{
  function
work(){echo 'power: '.get_class($this).' running'
;}
}

class
Ram implements Part
{
  function
work(){echo 'ram: '.get_class($this).' running'
;}
}

class
VideoCard implements Part
{
  function
work(){echo 'video cark: '.get_class($this).' running'
;}
}

class
AmdCpu extends Cpu
{}
class
AsusMainBoard extends MainBoard
{}
class
GreatWallPower extends Power
{}
class
KingMaxRam extends Ram
{}
class
AtiVideoCard extends VideoCard
{}

class
Amd implements PartFactory
{
  function
build
(){
    return new
AmdCpu
();
  }
}

class
Asus implements PartFactory
{
  function
build
(){
    return new
AsusMainBoard
();
  }
}
class
GreatWall implements PartFactory
{
  function
build
(){
    return new
GreatWallPower
();
  }
}
class
KingMax implements PartFactory
{
  function
build
(){
    return new
KingMaxRam
();
  }
}
class
Ati implements PartFactory
{
  function
build
(){
    return new
AtiVideoCard
();
  }
}


TOP

/**
* 负责生产各个零件
*
*/
class MixedBuilder implements Builder
{
  
/**
   * @var PartFactory
   */
  
private $cpuFactory,$powerFactory,$mainBoardFactory,$videoCardFactory,$ramFactory
;
  function
__construct
(){
   
$this->cpuFactory=new Amd
();
   
$this->mainBoardFactory=new Asus
();
   
$this->powerFactory=new GreatWall
();
   
$this->ramFactory=new KingMax
();
   
$this->videoCardFactory=new Ati
();
  }
  function
buildCpu
(){
    return
$this->cpuFactory->build
();
  }
  function
buildPower
(){
    return
$this->powerFactory->build
();
  }
  function
buildMainBoard
(){
    return
$this->mainBoardFactory->build
();
  }
  function
buildVideoCard
(){
    return
$this->videoCardFactory->build
();
  }
  function
buildRam
(){
    return
$this->ramFactory->build
();
  }
}

/**
* 负责组装各个零件
*
*/
class Director
{
  
/**
   * @var Builder
   */
  
private $builder
;
  function
__construct(Builder $builder
){
   
$this->builder=$builder
;
  }
  
/**
   * @return Computer
   *
   */
  
function buildComputer
(){
   
$computer=new Computer
();
   
$computer->addPart($this->builder->buildPower
());
   
$computer->addPart($this->builder->buildMainBoard
());
   
$computer->addPart($this->builder->buildCpu
());
   
$computer->addPart($this->builder->buildRam
());
   
$computer->addPart($this->builder->buildVideoCard
());
    return
$computer
;
  }
}

//builder目的,使部件的生产与组装解耦
//部件零售者,处理构置零件
$builder=new MixedBuilder
();
//装机人,处理装配顺序
$director=new Director($builder
);

$computer=$director->buildComputer
();

$computer->run
();
?>

TOP

5创建模式之Singleton


[复制PHP代码]
PHP代码如下:

final class SuperMan {

  private static
$self
;

  private
$name
;

  
/**
   * 私有构造函数,防止随便创建
   *
   * @param string $name
   */
  
private function __construct
(){
  }
  
/**
   * 召唤超人的唯一方法
   *
   * @return SuperMan
   */
  
static function call
(){
    if (!
self::$self
) {
        
self::$self=new SuperMan
();
    }
    return
self::$self
;
  }
  
/**
   * 调试用方法
   * @return string
   */
  
function getName
(){
    return
$this->name
;
  }
  
/**
   * 调试用方法
   *
   * @param string $name
   */
  
function setName($name
){
   
$this->name=$name
;
  }

  
/**
   * 关闭复制
   *
   */
  
function __clone
(){
    throw new
Exception("超人不能克隆"
);
  }

  
/**
   * 关闭序列化
   *
   */
  
function __sleep
(){
    throw new
Exception("超人不能保存"
);
  }

  
/**
   * 关闭反序列化
   *
   */
  
function __wakeup
(){
    throw new
Exception("超人不能恢复"
);
  }
}

echo
'<pre>'
;
  
$superA=SuperMan::call
();
  
$superA->setName('Super Man'
);
  
$superB=SuperMan::call
();
  echo
$superA,'      ',$superA->getName(),"\n"
;
  echo
$superB,'      ',$superB->getName(),"\n\n\n"
;
  
SuperMan::call()->setName("Bat Man"
);
  
$superA=SuperMan::call
();
  
$superB=SuperMan::call
();
  echo
$superA,'      ',$superA->getName(),"\n"
;
  echo
$superB,'      ',$superB->getName(),"\n\n\n";



TOP

6结构模式之Proxy


[复制PHP代码]
PHP代码如下:

interface Fighter {

  function
fight
();

  function
killSelf
();
}

class
JapaneseFilter implements Fighter
{

  function
fight
(){
    echo
__CLASS__.' fighting',"\n"
;
  }

  function
killSelf
(){
    echo
__CLASS__.' dying',"\n"
;
  }
}

class
NoKillSelfProxy implements Fighter
{
  
/**
   * @var Fighter
   */
  
private $fighter
;

  function
__construct(Fighter $fighter
){
   
$this->fighter=$fighter
;
  }

  function
fight
(){
   
$this->fighter->fight
();
  }

  function
killSelf
(){
    echo
'self kill not allow',"\n"
;
  }
}


function
fighterAction(Fighter $fighter
){
  echo
'<pre>'
;
  
$fighter->fight
();
  
$fighter->killSelf
();
  echo
'</pre>'
;
}


$jf=new JapaneseFilter
();
$pf=new NoKillSelfProxy($jf
);

fighterAction($jf
);
fighterAction($pf);


TOP

7结构模式之Adapter



[复制PHP代码]
PHP代码如下:

<?php

interface WhatIHave
{

  function
haveOp
();
}

interface
WhatIWant
{

  function
wantOp
();
}

class
Adapter implements WhatIWant
{
  
/**
   * @var WhatIHave
   */
  
private $have
;
  function
__construct(WhatIHave $have
){
   
$this->have=$have
;
  }

  function
wantOp
(){
   
$this->have->haveOp
();
  }
}

class
ClassHad implements WhatIHave
{
  function
haveOp
(){
    echo
'have op'
;
  }
}

function
functionHad (WhatIWant $want
){
  
$want->wantOp
();
}

$have=new ClassHad
();
$want=new Adapter($have
);

//迁就原有的接口,只能采用适配器类来处理.
functionHad($want
);
?>


TOP

8结构模式式之Composite


[复制PHP代码]
PHP代码如下:

<?php

class Tree
{
  private
$branch
;
  function
setBranch(Branch $branch
){
   
$this->branch=$branch
;
  }
  function
__toString
(){
    return
"Tree: has ".$this->branch->__toString
();
  }
}

class
Branch
{
  private static
$count=0
;

  private
$id
;
  private
$branches
;
  private
$leaves
;

  function
__construct
(){
   
$this->id= ++self::$count
;
  }
  function
getId
(){
    return
$this->id
;
  }
  function
addChild(Branch $branch
){
   
$this->branches[]=$branch
;
  }
  function
addLeaf(Leaf $leaf
){
   
$this->leaves[]=$leaf
;
  }

  function
__toString
(){
   
$str= 'Branch '.$this->id
;
    if (
count($this->branches)>0
) {
        
$str.=' Has branches: '
;
        foreach (
$this->branches as $branch
) {
            
$str.=$branch->__toString()."\n"
;
        }
    }
    if (
count($this->leaves)>0
) {
        
$str.=' Has leaves'
;
        foreach (
$this->leaves as $leaf
) {
            
$str.=$leaf->__toString()."\n"
;
        }
    }
    return
$str
;
  }
}

class
Leaf
{

  private static
$count=0
;
  private
$id
;

  function
__construct
(){
   
$this->id= ++self::$count
;
  }
  function
__toString
(){
    return
' Leaf '.$this->id
;
  }
}

$branch=new Branch();
//树枝
$branch->addChild(new Branch());
//树枝上的树枝
$branch->addLeaf(new Leaf());
//树枝上的叶子
$tree=new Tree();
//树
$tree->setBranch($branch);
//树的树枝
echo '<pre>',$tree
;
?>


TOP

9结构模式之Decorator


[复制PHP代码]
PHP代码如下:

<?php

interface Tea
{
  function
getDesc
();
  function
getPrice
();
}

class
BlackTea implements Tea
{

  function
getDesc
(){
    return
" BlackTea "
;
  }
  function
getPrice
(){
    return
6
;
  }
}

class
GreanTea implements Tea
{

  function
getDesc
(){
    return
" GreanTea "
;
  }
  function
getPrice
(){
    return
8
;
  }
}

class
SugarTea implements Tea
{
  
/**
   * @var Tea
   */
  
private $tea
;
  function
__construct(Tea $tea
){
   
$this->tea=$tea
;
  }
  function
getDesc
(){
    return
' sugar '.$this->tea->getDesc
();
  }
  function
getPrice
(){
    return
1+$this->tea->getPrice
();
  }
}

class
MilkTea implements Tea
{
  
/**
   * @var Tea
   */
  
private $tea
;
  function
__construct(Tea $tea
){
   
$this->tea=$tea
;
  }
  function
getDesc
(){
    return
' milk '.$this->tea->getDesc
();
  }
  function
getPrice
(){
    return
2+$this->tea->getPrice
();
  }
}
echo
'<pre>'
;

//绿茶,加糖,加牛奶
$tea=new MilkTea(new SugarTea(new GreanTea
()));
echo
$tea->getDesc(),'   $',$tea->getPrice
();
echo
"\n\n\n\n"
;
//红茶,加牛奶
$tea=new MilkTea(new BlackTea
());
echo
$tea->getDesc(),'   $',$tea->getPrice
();
echo
"\n\n\n\n"
;
//绿茶加糖
$tea=new SugarTea(new GreanTea
());
echo
$tea->getDesc(),'   $',$tea->getPrice
();
echo
"\n\n\n\n"
;
?>


TOP