浅谈PHP设计模式的建造者模式
  yThMa20bw7iV 2023年11月02日 30 0
PHP

简介:

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

适用场景:

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

优点:

创建和表象分离

缺点:

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

代码:

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();
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  NT5NRjELxLp1   2024年04月29日   70   0   0 PHP
  iALoCqVB8AGc   2023年12月25日   36   0   0 PHP
  yThMa20bw7iV   2024年02月19日   71   0   0 PHP
  iyViKl6W0XQr   2024年05月17日   53   0   0 PHP
  NT5NRjELxLp1   2024年03月14日   83   0   0 PHP
yThMa20bw7iV