美文网首页
工厂模式案例

工厂模式案例

作者: 豆豆_06fa | 来源:发表于2019-02-14 20:51 被阅读0次

    <?php

    class Power {

        protected $ability;

        protected $range;

        public function __construct($ability, $range)

        {

            $this->ability = $ability;

            $this->range = $range;

            echo $this->ability.'<br>'.$this->range.'<hr>';

        }

    }

    class Flight

    {

        protected $speed;

        protected $holdtime;

        public function __construct($speed, $holdtime) {

            $this->speed = $speed;

            $this->holdtime = $holdtime;

            echo $this->speed.'<br>'.$this->holdtime.'<hr>';

        }

    }

    class Force

    {

        protected $force;

        public function __construct($force) {

            $this->force = $force;

            echo $this->force.'<hr>';

        }

    }

    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'],

    ]);

    相关文章

      网友评论

          本文标题:工厂模式案例

          本文链接:https://www.haomeiwen.com/subject/civyeqtx.html