Rumah > pembangunan bahagian belakang > tutorial php > PHP面向对象进阶设计模式:外观模式使用实例

PHP面向对象进阶设计模式:外观模式使用实例

巴扎黑
Lepaskan: 2023-03-07 20:22:01
asal
1909 orang telah melayarinya

什么是外观模式?

通过在必须的逻辑和方法的集合前创建的外观接口,外观设计模式隐藏了来自调用对象的复杂性。

为何使用外观设计模式:

使用基于外观设计模式的对象的原因是接口第三方解决方案。需要记住的是,我们不断强调面向对象的项目应当知识关联对象的一个集合。鉴于这种体系结构,首席编程人员可能觉得使用第三方对象更为明智。

假设要为某个应用程序提供搜索Web页面。该页面首先自己查找符合搜索项的所有数据。如果结果数小于10,那么就会调用第三方服务检索其他结果,这些结果会被添加至应用程序在内部发现的结果末尾。Search外观对象将结果返回至调用视图对象。在内部,Search外观对象会调用查询内部数据库的方法。随后,它会判断是否需要通过Web服务来调用Google。如果需要,那么还会分析所有结果,以便返回一个同类结果集。

为了隐藏复杂的、执行业务进程某个步骤所需的方法和逻辑组,就应当使用基于外观设计模式的类。

UML

该UML图详细说明了一个使用外观设计模式的类设计。

2.png

下面是对上图的说明:

1.MyObject类包含一个名为doSomethingRequiresAandB()的公共方法,该方法只是MyObject类执行中的一个步骤。doSomethingRequiresAandB()方法创建对象LogicFacade的一个新实例,该实例调用对于MyObject来说足够抽象的、名称为callRequiredLogic()的公共方法。

2.LogicFacade类内部的callRequiredLogic()方法随后负责创建LogicObjectA的一个实例以及调用doSomethingA()方法,此外还负责创建LogicObjectB的一个实例以及调用doSomethingB()方法。

3.上述所有动作都通过LogicFacade类向回传递,从而使他们能够被MyObject使用。


使用实例代码展示:

header("Content-type:text/html;Charset=utf-8");

//子系统角色
class SubSystemOne{
   function mothedOne(){
       echo "方法一<br>";
   }
}
class SubSystemTwo{
   function mothedTwo(){
       echo "方法二<br>";
   }
}
class SubSystemThree{
   function mothedThree(){
       echo "方法三<br>";
   }
}

//外观角色
class Facade{
    private $subSystemOne = null;
    private $subSystemTwo = null;
    private $subSystemThree =null;

    function __construct(){
        $this->subSystemOne =new SubSystemOne();
        $this->subSystemTwo =new SubSystemTwo();
        $this->subSystemThree =new SubSystemThree();
    }

    function mothedA(){
        $this->subSystemOne->mothedOne();
    }
    function mothedB(){
        $this->subSystemTwo->mothedTwo();
    }
    function mothedC(){
        $this->subSystemThree->mothedThree();
    }
    function mothedD(){
        $this->subSystemOne->mothedOne();
        $this->subSystemTwo->mothedTwo();
        $this->subSystemThree->mothedThree();
    }
}

//测试
$facade = new Facade();
$facade->mothedA();
$facade->mothedB();
$facade->mothedC();
$facade->mothedD();
Salin selepas log masuk


Atas ialah kandungan terperinci PHP面向对象进阶设计模式:外观模式使用实例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan