• 建造者模式(生成器模式)


    建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构造过程可以创建不同的表示。如果我们用了建造者模式,那么用户就只需指定需要建造的类型就可以得到它们,而具体建造的过程和细节就不需知道了.

    class Bird
    {

    public $head;
    public $wing;
    public $foot;

    public function show(){

    echo '头的颜色:'.$this->head.'<br>';
    echo '翅膀的颜色:'.$this->wing.'<br>';
    echo '脚的颜色:'.$this->foot.'<br>';
    }

    }


    abstract class BirdBuilder
    {
    protected $bird;

    public function __construct()
    {
    $this->bird = new Bird();
    }

    abstract function BuildHead();
    abstract function BuildWing();
    abstract function BuildFoot();
    abstract function GetBird();


    }

    class BlueBird extends BirdBuilder
    {

    public function BuildHead()
    {
    $this->bird->head = 'Blue';
    }

    public function BuildWing()
    {
    $this->bird->wing = 'gray';
    }

    public function BuildFoot()
    {
    $this->bird->foot = 'gray';

    }

    public function GetBird()
    {
    return $this->bird;
    }

    }
    class RoseBird extends BirdBuilder
    {



    public function BuildHead()
    {
    $this->bird->head = 'Red';
    }

    public function BuildWing()
    {
    $this->bird->wing = 'gray';
    }

    public function BuildFoot()
    {
    $this->bird->foot = 'gray';

    }

    public function GetBird()
    {
    return $this->bird;
    }

    }

    class Director
    {

    public function Construct($builder)
    {
    $builder->BuildHead();
    $builder->BuildWing();
    $builder->BuildFoot();

    return $builder->GetBird();
    }

    }

    $director = new Director();
    $blueBird=$director->Construct(new BlueBird());

    $blueBird->show();

    建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用的模式


  • 相关阅读:
    并发编程
    网络与WEB 编程
    包和模块
    元编程
    类和对象
    【算法题 14 LeetCode 147 链表的插入排序】
    剑指offer面试54题
    剑指offer 面试51题
    剑指offer 面试3题
    剑指offer 面试52题
  • 原文地址:https://www.cnblogs.com/paulversion/p/8430755.html
Copyright © 2020-2023  润新知