美文网首页
工厂模式

工厂模式

作者: CaptainRoy | 来源:发表于2018-06-29 23:21 被阅读1次
    简单工厂模式
    • 自行车类
    class Bicycle
    {
        public function driveTo($destionation)
        {
            echo '骑车到 '.$destionation.PHP_EOL;
        }
    }
    
    • 工厂类
    class SimpleFactory
    {
        public function createBicycle()
        {
            $bicycle = new Bicycle();
            return $bicycle;
        }
    }
    
    $factory = new SimpleFactory();
    $bicycle = $factory->createBicycle();
    $bicycle->driveTo('北京'); // 骑车到 北京
    
    抽象工厂模式
    • 自行车类
    class Bicycle
    {
        public function driveTo($destionation)
        {
            echo '骑车到 '.$destionation.PHP_EOL;
        }
    }
    
    • 抽象工厂类
    abstract class Factory
    {
        abstract public function createVehicle();
    }
    
    • 自行车工厂类
    class BicycleFactory extends Factory
    {
        public function createVehicle()
        {
            $bicycle = new Bicycle();
            return $bicycle;
        }
    }
    
    $factory = new BicycleFactory();
    $bicycle = $factory->createVehicle();
    $bicycle->driveTo('巴黎'); // 骑车到 巴黎
    

    相关文章

      网友评论

          本文标题:工厂模式

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