工厂模式PHP

简单工厂模式
  • 自行车类
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('巴黎'); // 骑车到 巴黎

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