工厂模式
约 136 字小于 1 分钟
2025-07-08
// 比如,我们有一些类,它们都继承自交通工具类:
interface Vehicle
{
public function drive();
}
class Car implements Vehicle
{
public function drive()
{
echo '汽车靠四个轮子滚动行走。' . PHP_EOL;
}
}
class Ship implements Vehicle
{
public function drive()
{
echo '轮船靠螺旋桨划水前进。'. PHP_EOL;
}
}
// 工厂
interface VehicleFactory
{
public static function run();
}
class CarVehicleFactory implements VehicleFactory
{
public static function run()
{
return new Car();
}
// other...
}
class ShipVehicleFactory implements VehicleFactory
{
public static function run()
{
return new Ship();
}
// other...
}
// 需要知道每个工厂的实现
CarVehicleFactory::run()->drive();
ShipVehicleFactory::run()->drive();
贡献者
更新日志
2025/7/8 02:36
查看所有更新日志
7d36c
-php于