PHP设计模式

建造者模式

托比昂

建造者模式

用于将一个复杂的对象的创建、组装、表示进行分离。

使用场景

最常见的比如游戏人物自定义。

代码

<?php
/**
 * 建造者模式 实现
 * Created by PhpStorm.
 * User: retr
 * Date: 2018/11/3
 * Time: 2:09 PM
 */

/**
 * 头发
 * Class Hair
 */
class Hair
{
    public $color = "#000000";

    public function __construct($color = null)
    {
        if($color !== null)
        {
            $this->color = $color;
        }
    }
}

/**
 * 眼睛
 * Class Eye
 */
class Eye {

    public $eyelid = "double";

    public function __construct($eyelid = null)
    {
        if($eyelid !== null)
        {
            $this->eyelid = $eyelid;
        }
    }

}

/**
 * 翅膀
 * Class Wing
 */
class Wing {

    public $pair = 1;

    public function __construct($pair = 1)
    {
        $this->pair = $pair;
    }

}

/**
 * Interface Builder
 */
interface Builder {

    public function setHair();

    public function setEye();

    public function setWing();

}

abstract class Role {

    protected $hair;

    protected $eye;

    protected $wing;

}

/**
 * 创建人类
 * Class Human
 */
class Human extends Role implements Builder {

    public function setHair()
    {
        // TODO: Implement setHair() method.

        $this->hair = new Hair('#000000');
    }


    public function setEye()
    {
        // TODO: Implement setEye() method.

        $this->eye = new Eye('single');
    }

    public function setWing()
    {
        // TODO: Implement setWing() method.
        // 人族不需要翅膀。

        //$this->wing = new Wing();
    }

    public function getHuman()
    {
        return $this;
    }
}

/**
 * 创建天使
 * Class Angel
 */
class Angel extends Role implements Builder {

    public function setHair()
    {
        // TODO: Implement setHair() method.

        $this->hair = new Hair('#FFFFFF');
    }

    public function setEye()
    {
        // TODO: Implement setEye() method.

        $this->eye = new Eye('double');
    }

    public function setWing()
    {
        // TODO: Implement setWing() method.

        $this->wing = new Wing();
    }

}

/**
 * 玩家,这里充当导演角色。
 * Class Player
 */
class Player {

    public function __construct()
    {
        //此处可以初始化玩家的名字、性别等~
    }

    /**
     * @var $builder array
     */
    private $roles = [];

    /**
     * 创建并保存角色,生产环境中需要接受来自外部类的自定义配置。
     * @param Builder $builder
     */
    public function buildRole(Builder $builder)
    {
        $builder->setWing();

        $builder->setHair();

        $builder->setEye();

        array_push($this->roles, $builder);
    }

    /**
     * 获得所有角色
     * @return mixed
     */
    public function getRoles()
    {
        return $this->getRoles();
    }

    /**
     * 获得第一个角色
     * @return mixed
     */
    public function getRolesFirst()
    {
        return $this->roles[0];
    }
}


$player = new Player();

$player->buildRole(new Angel());

var_dump($player);

Github

建造者模式

发表评论