The factory pattern is the class or method responsible for generating other objects.
Type 1 implementation
For example, we have some classes, all of which inherit from the vehicle class:
interface Vehicle
{
public function drive();
}
class Car implements Vehicle
{
public function drive()
{
echo '汽车靠四个轮子滚动行走。';
}
}
class Ship implements Vehicle
{
public function drive()
{
echo '轮船靠螺旋桨划水前进。';
}
}
class Aircraft implements Vehicle
{
public function drive()
{
echo '飞机靠螺旋桨和机翼的升力飞行。';
}
}
Create another factory class, dedicated to the creation of the class:
class VehicleFactory
{
public static function build($className = null)
{
$className = ucfirst($className);
if ($className && class_exists($className)) {
return new $className();
}
return null;
}
}
The factory class uses a static method to create other classes, which can be used in the client as follows:
VehicleFactory::build('Car')->drive();
VehicleFactory::build('Ship')->drive();
VehicleFactory::build('Aircraft')->drive();
Eliminates the need to new
work every time .
2 Solve
Reference materials: