PHP面向对象深入研究之【组合模式与装饰模式】

简介:

组合模式

定义:组合模式定义了一个单根继承体系,使具有截然不同职责的集合可以并肩工作。

一个军队的案例,

<?php

abstract class Unit { // 个体
    abstract function bombardStrength();
}

class Archer extends Unit { // 弓箭手
    function bombardStrength() {
        return 4;
    }
}

class LaserCannonUnit extends Unit { // 火炮手
    function bombardStrength() {
        return 44;
    }
}
?>

军队整合成员,输出火力

<?php

abstract class Unit {
    abstract function bombardStrength();
}

class Archer extends Unit {
    function bombardStrength() {
        return 4;
    }
}

class LaserCannonUnit extends Unit {
    function bombardStrength() {
        return 44;
    }
}


class Army { // 军队
    private $units = array(); // 定义私有属性 个体集

    function addUnit( Unit $unit ) { // 添加成员
        array_push( $this->units, $unit );
    }

    function bombardStrength() { // 火力
        $ret = 0;
        foreach( $this->units as $unit ) {
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }
}

$unit1 = new Archer(); 
$unit2 = new LaserCannonUnit(); 
$army = new Army();
$army->addUnit( $unit1 ); 
$army->addUnit( $unit2 ); 
print $army->bombardStrength(); // 输出火力
?>
output:
48

军队进一步整合其他军队

<?php

abstract class Unit {
    abstract function bombardStrength();
}

class Archer extends Unit {
    function bombardStrength() {
        return 4;
    }
}

class LaserCannonUnit extends Unit {
    function bombardStrength() {
        return 44;
    }
}


class Army {
    private $units = array();
    private $armies= array();

    function addUnit( Unit $unit ) {
        array_push( $this->units, $unit );
    }

    function addArmy( Army $army ) {
        array_push( $this->armies, $army );
    }

    function bombardStrength() {
        $ret = 0;
        foreach( $this->units as $unit ) {
            $ret += $unit->bombardStrength();
        }

        foreach( $this->armies as $army ) {
            $ret += $army->bombardStrength();
        }

        return $ret;
    }
}

$unit1 = new Archer(); 
$unit2 = new LaserCannonUnit(); 
$army = new Army();
$army->addUnit( $unit1 ); 
$army->addUnit( $unit2 ); 
print $army->bombardStrength();
print "\n";
$army2 = clone $army; // 克隆军队
$army->addArmy( $army2 );
print $army->bombardStrength();
print "\n";
?>
output:
48
96

更好的方式,支持新增,移除等等其他功能。

<?php
abstract class Unit {
    abstract function addUnit( Unit $unit );
    abstract function removeUnit( Unit $unit );
    abstract function bombardStrength();
}
class Army extends Unit { // 军队
    private $units = array();

    function addUnit( Unit $unit ) {
        if ( in_array( $unit, $this->units, true ) ) { // $this用于调用正常的属性或方法,self调用静态的方法,属性或者常量
            return;
        }
        
        $this->units[] = $unit;
    }

    function removeUnit( Unit $unit ) {
        // >= php 5.3
        $this->units = array_udiff( $this->units, array( $unit ), 
                       function( $a, $b ) { return ($a === $b)?0:1; } );

        // < php 5.3
        // $this->units = array_udiff( $this->units, array( $unit ), 
        //                create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); 
        // 对象数组,create_function,创建函数
    }

    function bombardStrength() {
        $ret = 0;
        foreach( $this->units as $unit ) {
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }
}

// quick example classes
class Tank extends Unit {  // 坦克
    function addUnit( Unit $unit ) {}
    function removeUnit( Unit $unit ) {}

    function bombardStrength() {
        return 4;
    }
}

class Soldier extends Unit {  // 士兵
    function addUnit( Unit $unit ) {}
    function removeUnit( Unit $unit ) {}

    function bombardStrength() {
        return 8;
    }
}

$tank =  new Tank();
$tank2 = new Tank();
$soldier = new Soldier();

$army = new Army();
$army->addUnit( $soldier );
$army->addUnit( $tank );
$army->addUnit( $tank2 );

print_r( $army );
print $army->bombardStrength()."\n";

$army->removeUnit( $soldier );

print_r( $army );
print $army->bombardStrength()."\n";
?>
output:
Army Object
(
    [units:Army:private] => Array
        (
            [0] => Soldier Object
                (
                )

            [1] => Tank Object
                (
                )

            [2] => Tank Object
                (
                )

        )

)
16
Army Object
(
    [units:Army:private] => Array
        (
            [1] => Tank Object
                (
                )

            [2] => Tank Object
                (
                )

        )

)
8

添加异常处理

<?php
abstract class Unit {
    abstract function addUnit( Unit $unit );
    abstract function removeUnit( Unit $unit );
    abstract function bombardStrength();
}

class Army extends Unit {
    private $units = array();

    function addUnit( Unit $unit ) {
        if ( in_array( $unit, $this->units, true ) ) {
            return;
        }
        
        $this->units[] = $unit;
    }

    function removeUnit( Unit $unit ) {
        // >= php 5.3
        //$this->units = array_udiff( $this->units, array( $unit ), 
        //                function( $a, $b ) { return ($a === $b)?0:1; } );

        // < php 5.3
        $this->units = array_udiff( $this->units, array( $unit ), 
                        create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
    }

    function bombardStrength() {
        $ret = 0;
        foreach( $this->units as $unit ) {
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }
}

class UnitException extends Exception {}

class Archer extends Unit {
    function addUnit( Unit $unit ) {
        throw new UnitException( get_class($this)." is a leaf" );
    }

    function removeUnit( Unit $unit ) {
        throw new UnitException( get_class($this)." is a leaf" );
    }

    function bombardStrength() {
        return 4;
    }
}

$archer = new Archer();
$archer2 = new Archer();
$archer->addUnit( $archer2 );

?>

output:
Fatal error: Uncaught exception 'UnitException' with message 'Archer is a leaf'

点评:组合模式中的一切类都共享同一个父类型,可以轻松地在设计中添加新的组合对象或局部对象,而无需大范围地修改代码。

最终的效果,逐步优化(完美):

<?php

class UnitException extends Exception {}

abstract class Unit {
    abstract function bombardStrength();

    function addUnit( Unit $unit ) {
        throw new UnitException( get_class($this)." is a leaf" );
    }

    function removeUnit( Unit $unit ) {
        throw new UnitException( get_class($this)." is a leaf" );
    }
}

class Archer extends Unit {
    function bombardStrength() {
        return 4;
    }
}

class LaserCannonUnit extends Unit {
    function bombardStrength() {
        return 44;
    }
}

class Army extends Unit {
    private $units = array();

    function addUnit( Unit $unit ) {
        if ( in_array( $unit, $this->units, true ) ) {
            return;
        }
        
        $this->units[] = $unit;
    }

    function removeUnit( Unit $unit ) {
        // >= php 5.3
        //$this->units = array_udiff( $this->units, array( $unit ), 
        //                function( $a, $b ) { return ($a === $b)?0:1; } );

        // < php 5.3
        $this->units = array_udiff( $this->units, array( $unit ), 
                        create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
    }

    function bombardStrength() {
        $ret = 0;
        foreach( $this->units as $unit ) {
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }
}

// create an army
$main_army = new Army();

// add some units
$main_army->addUnit( new Archer() );
$main_army->addUnit( new LaserCannonUnit() );

// create a new army
$sub_army = new Army();

// add some units
$sub_army->addUnit( new Archer() );
$sub_army->addUnit( new Archer() );
$sub_army->addUnit( new Archer() );

// add the second army to the first
$main_army->addUnit( $sub_army );

// all the calculations handled behind the scenes
print "attacking with strength: {$main_army->bombardStrength()}\n";
?>
output:
attacking with strength: 60

更牛逼的组合处理,

<?php

abstract class Unit {
    function getComposite() {
        return null;
    }

    abstract function bombardStrength();
}


abstract class CompositeUnit extends Unit { // 抽象类继承抽象类
    private $units = array();

    function getComposite() {
        return $this;
    }

    protected function units() {
        return $this->units;
    }

    function removeUnit( Unit $unit ) {
        // >= php 5.3
        //$this->units = array_udiff( $this->units, array( $unit ), 
        //                function( $a, $b ) { return ($a === $b)?0:1; } );

        // < php 5.3
        $this->units = array_udiff( $this->units, array( $unit ), 
                        create_function( '$a,$b', 'return ($a === $b)?0:1;' ) );
    }

    function addUnit( Unit $unit ) {
        if ( in_array( $unit, $this->units, true ) ) {
            return;
        }
        $this->units[] = $unit;
    }
}
class Army extends CompositeUnit {

    function bombardStrength() {
        $ret = 0;
        foreach( $this->units as $unit ) {
            $ret += $unit->bombardStrength();
        }
        return $ret;
    }

}

class Archer extends Unit {
    function bombardStrength() {
        return 4;
    }
}

class LaserCannonUnit extends Unit {
    function bombardStrength() {
        return 44;
    }
}

class UnitScript {
    static function joinExisting( Unit $newUnit,
                                  Unit $occupyingUnit ) { // 静态方法,直接通过类名来使用
        $comp;

        if ( ! is_null( $comp = $occupyingUnit->getComposite() ) ) { // 军队合并处理
            $comp->addUnit( $newUnit ); 
        } else { // 士兵合并处理
            $comp = new Army(); 
            $comp->addUnit( $occupyingUnit );
            $comp->addUnit( $newUnit );
        }
        return $comp;
    }
}

$army1 = new Army();
$army1->addUnit( new Archer() );
$army1->addUnit( new Archer() );

$army2 = new Army();
$army2->addUnit( new Archer() );
$army2->addUnit( new Archer() );
$army2->addUnit( new LaserCannonUnit() );

$composite = UnitScript::joinExisting( $army2, $army1 );
print_r( $composite );

?>

output:
Army Object
(
    [units:CompositeUnit:private] => Array
        (
            [0] => Archer Object
                (
                )

            [1] => Archer Object
                (
                )

            [2] => Army Object
                (
                    [units:CompositeUnit:private] => Array
                        (
                            [0] => Archer Object
                                (
                                )

                            [1] => Archer Object
                                (
                                )

                            [2] => LaserCannonUnit Object
                                (
                                )

                        )

                )

        )

)

点评:Unit 基础,CompositeUnit复合中实现add与remove。军队继承Composite,射手继承Archer。这样射手中就不会有多余的add与remove方法了。

装饰模式

装饰模式帮助我们改变具体组件的功能。

看例子

<?php
abstract class Tile { // 砖瓦
    abstract function getWealthFactor(); // 获取财富
}

class Plains extends Tile { // 平原
    private $wealthfactor = 2;
    function getWealthFactor() {
        return $this->wealthfactor;
    }
}

class DiamondPlains extends Plains { // 钻石地段
    function getWealthFactor() {
        return parent::getWealthFactor() + 2;
    }
}

class PollutedPlains extends Plains { // 污染地段
    function getWealthFactor() {
        return parent::getWealthFactor() - 4;
    }
}
$tile = new PollutedPlains();
print $tile->getWealthFactor();
?>
output:
-2

点评:不具有灵活性,我们不能同时获得钻石与被污染的土地的资金情况。

装饰模式使用组合和委托而不是只使用继承来解决功能变化的问题。
看例子:

<?php

abstract class Tile {
    abstract function getWealthFactor();
}

class Plains extends Tile {
    private $wealthfactor = 2;
    function getWealthFactor() {
        return $this->wealthfactor;
    }
}

abstract class TileDecorator extends Tile { // 装饰
    protected $tile;
    function __construct( Tile $tile ) {
        $this->tile = $tile;
    }
}

class DiamondDecorator extends TileDecorator { // 钻石装饰
    function getWealthFactor() {
        return $this->tile->getWealthFactor()+2;
    }
}

class PollutionDecorator extends TileDecorator { // 污染装饰
    function getWealthFactor() {
        return $this->tile->getWealthFactor()-4;
    }
}

$tile = new Plains();
print $tile->getWealthFactor(); // 2

$tile = new DiamondDecorator( new Plains() );
print $tile->getWealthFactor(); // 4

$tile = new PollutionDecorator(
             new DiamondDecorator( new Plains() ));
print $tile->getWealthFactor(); // 0
?>
output:
2
4
0

点评:这个模型具有扩展性。我们不需要创建DiamondPollutionPlains对象就可以构建一个钻石被污染的对象。

一个更逼真的例子

<?php

class RequestHelper{} // 请求助手

abstract class ProcessRequest { // 进程请求
    abstract function process( RequestHelper $req );
}

class MainProcess extends ProcessRequest { // 主进程
    function process( RequestHelper $req ) {
        print __CLASS__.": doing something useful with request\n";
    }
}

abstract class DecorateProcess extends ProcessRequest { // 装饰进程
    protected $processrequest;
    function __construct( ProcessRequest $pr ) { // 引用对象,委托
        $this->processrequest = $pr;
    }
}

class LogRequest extends DecorateProcess { // 日志请求
    function process( RequestHelper $req ) {
        print __CLASS__.": logging request\n"; // 当前类,有点递归的感觉
        $this->processrequest->process( $req );
    }
}

class AuthenticateRequest extends DecorateProcess { // 认证请求
    function process( RequestHelper $req ) {
        print __CLASS__.": authenticating request\n";
        $this->processrequest->process( $req );
    }
}

class StructureRequest extends DecorateProcess { // 组织结构请求
    function process( RequestHelper $req ) {
        print __CLASS__.": structuring request\n";
        $this->processrequest->process( $req );
    }
}

$process = new AuthenticateRequest( new StructureRequest(
                                    new LogRequest (
                                    new MainProcess()
                                    ))); // 这样可以很灵活的组合进程的关系,省去很多重复的继承

$process->process( new RequestHelper() );
print_r($process);
?>

output:
AuthenticateRequest: authenticating request
StructureRequest: structuring request
LogRequest: logging request
MainProcess: doing something useful with request
AuthenticateRequest Object
(
    [processrequest:protected] => StructureRequest Object
        (
            [processrequest:protected] => LogRequest Object
                (
                    [processrequest:protected] => MainProcess Object
                        (
                        )

                )

        )

)

点评:这里有一种递归的感觉,一层调用一层。模式是牛人总结出来用于灵活的解决一些现实问题的。牛!给开发多一点思路。



本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5183162.html,如需转载请自行联系原作者


相关文章
|
7月前
|
PHP
PHP编程中的面向对象和面向过程
【8月更文挑战第28天】在PHP编程中,我们可以选择面向对象或面向过程的编程方式。面向对象的编程方式更符合人类习惯,易于理解,提高程序的重用性,减少代码出错率;而面向过程的编程方式则强调的是功能行为,以具体的功能实现为主。
|
2天前
|
监控 算法 安全
基于 PHP 语言深度优先搜索算法的局域网网络监控软件研究
在当下数字化时代,局域网作为企业与机构内部信息交互的核心载体,其稳定性与安全性备受关注。局域网网络监控软件随之兴起,成为保障网络正常运转的关键工具。此类软件的高效运行依托于多种数据结构与算法,本文将聚焦深度优先搜索(DFS)算法,探究其在局域网网络监控软件中的应用,并借助 PHP 语言代码示例予以详细阐释。
15 1
|
7月前
|
设计模式 数据库连接 PHP
PHP编程中的面向对象与设计模式
在PHP编程世界中,掌握面向对象编程(OOP)和设计模式是提升代码质量和开发效率的关键。本文将深入浅出地介绍如何在PHP中应用OOP原则和设计模式,以及这些实践如何影响项目架构和维护性。通过实际案例,我们将探索如何利用这些概念来构建更健壮、可扩展的应用程序。
|
7月前
|
设计模式 测试技术 PHP
使用PHP进行面向对象网站开发的最佳实践
【8月更文第10天】PHP 是一种广泛使用的开源服务器端脚本语言,特别适合于 Web 开发并可嵌入 HTML 中。随着 PHP 5.x 和 7.x 版本的发展,它已经完全支持面向对象编程(OOP)。面向对象的设计模式和原则可以帮助开发者构建更加模块化、可扩展且易于维护的应用程序。
65 6
|
4月前
|
存储 PHP
09 PHP高级面向对象,大多数人不了解的东西!
路老师分享了PHP语言的高级应用,包括final关键字、抽象类、接口使用、对象类型检测及魔术方法等。通过实例详细讲解了PHP面向对象编程的核心概念和技术要点,帮助读者深入理解和掌握PHP。
48 3
|
4月前
|
Java PHP 开发者
08 PHP面向对象的高级操作
路老师分享PHP语言知识,帮助大家入门并深入了解PHP。内容涵盖构造方法、析构方法、继承、多态、`$this-&gt;`与`::`操作符的使用,以及数据隐藏等核心概念。通过详细示例,讲解如何在实际开发中运用这些技术。适合初学者和进阶开发者学习。
46 2
|
4月前
|
PHP
07 PHP的面向对象你真的了解吗?
路老师分享PHP语言知识,帮助大家入门并深入了解PHP。本文介绍了面向对象编程的基础概念,包括类、对象、封装性、继承性和多态性,以及类的定义、方法、实例化和成员变量等内容。下篇将讲解构造函数、析构函数及PHP对象的高级应用。
59 2
|
6月前
|
Java PHP 数据安全/隐私保护
PHP 面向对象,构造函数,析构函数,继承,方法的重写,接口抽象类,static,final,this,parent,self的异同和作用
本文详细介绍了PHP面向对象编程的一系列核心概念和用法,包括构造函数、析构函数、继承、方法重写、访问控制、接口、抽象类、静态成员、final关键字、以及this、self、parent这三个关键字的异同和作用。通过具体示例代码,展示了如何在PHP中使用这些面向对象的特性,以及它们在实际开发中的应用。
PHP 面向对象,构造函数,析构函数,继承,方法的重写,接口抽象类,static,final,this,parent,self的异同和作用
|
5月前
|
PHP 开发者
PHP编程中的面向对象基础
【9月更文挑战第36天】在PHP的世界中,面向对象编程(OOP)是一块基石。它不仅为代码带来了结构、可维护性与重用性,还让复杂的问题变得简单化。通过掌握类与对象、继承与多态等核心概念,开发者可以构建出更加强大和灵活的应用。本文将引导你理解这些概念,并通过实例展示如何在PHP中应用它们,让你轻松驾驭OOP的力量。
|
6月前
|
PHP 开发者
PHP编程中的面向对象基础与实践
【9月更文挑战第27天】在PHP的海洋里,面向对象编程(OOP)是一艘强大的船,它不仅能让代码组织得更加优雅,还能提高开发效率。本文将带你领略OOP的魅力,从基础概念到实际应用,让你轻松驾驭这艘船,开启高效编程之旅。

热门文章

最新文章