疯狂编程网

  • 首页
  • 后端
    • GOLANG
    • PHP
  • 前端
  • 客户端
  • 服务器
  • AIGC
  • 开发工具
  • 代码人生
  • 关于本站
    • 联系我们
    • 免责声明
  1. 首页
  2. 后端
  3. PHP
  4. 正文

浅谈PHP设计模式的建造者模式

2023年5月10日 614点热度 0人点赞 0条评论

简介:

建造者模式,又称之为生成器模式,属于创建型的设计模式。将一个复杂对象的构建,与它的表示分离,使得同样的构建过程可以创建不同的表示。

适用场景:

用于创建一些复杂的对象,这些对象内部构建间的建造顺序通常是稳定的(这就表名可以抽离),但对象的外在面临着复杂的变化。

优点:

创建和表象分离

缺点:

如果核心类内部发生变化,建造者也要相应修改
与工厂模式:
比工厂模式多了一道自行处理的工序

代码:

abstract class TestPaper {
    abstract public function BuildPaper();
    abstract public function BuildQuestion();
}

class ChineseExaminationPaper extends TestPaper {
    public function BuildPaper() {
        echo "使用A4纸";
    }

    public function BuildQuestion() {
        echo "语文题";
    }
}

class EnglishExaminationPaper extends TestPaper {
    public function BuildPaper() {
        echo "使用A6纸";
    }

    public function BuildQuestion() {
        echo "英文题";
    }
}



class ExaminationPaper {
    private $examination_paper;
    function __construct($examination_paper) {
        $this->examination_paper = $examination_paper;
    }

    public function create() {
        $this->examination_paper->BuildPaper();
        $this->examination_paper->BuildQuestion();
    }
}


//客户端代码

$thinDirector = new ExaminationPaper(new ChineseExaminationPaper());
$thinDirector->create();

$fatDirector = new ExaminationPaper(new EnglishExaminationPaper());
$fatDirector->create();
标签: php
最后更新:2023年5月10日

大明

靠写代码养家的开发者。

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 疯狂编程网. ALL RIGHTS RESERVED.

京ICP备2022013580号-1