工厂模式案例

class Power {

    protected $ability;

    protected $range;

    public function __construct($ability, $range)

    {

        $this->ability = $ability;

        $this->range = $range;

        echo $this->ability.'
'.$this->range.'


';

    }

}

class Flight

{

    protected $speed;

    protected $holdtime;

    public function __construct($speed, $holdtime) {

        $this->speed = $speed;

        $this->holdtime = $holdtime;

        echo $this->speed.'
'.$this->holdtime.'


';


    }

}

class Force

{

    protected $force;

    public function __construct($force) {

        $this->force = $force;

        echo $this->force.'


';

    }

}

class Shot

{

    protected $atk;

    protected $range;

    protected $limit;

    public function __construct($atk, $range, $limit) {

    }

}

class SuperModuleFactory

{

    public function makeModule($moduleName, $options)

    {

        switch ($moduleName) {

            case 'Power':

                return new Power($options[0], $options[1]);

            case 'Flight':

                return new Flight($options[0], $options[1]);

            case 'Force':

                return new Force($options[0]);

            case 'Shot':

                return new Shot($options[0], $options[1], $options[2]);

        }

    }

}

class Superman

{

    protected $power;

    public function __construct(array $modules)

    {

        // 初始化工厂

        $factory = new SuperModuleFactory;

        // 通过工厂提供的方法制造需要的模块

        foreach ($modules as $moduleName => $moduleOptions) {

            $this->power[] = $factory->makeModule($moduleName, $moduleOptions);

        }

    }

}

// 创建超人

$superman = new Superman([

    'Power' => [90, 100],

    'Flight' => [785, 900],

    'Force' => ['hjf'],

]);

你可能感兴趣的:(工厂模式案例)