The Simple Factory Pattern is a creational design pattern that delegates object creation to a factory class instead of directly instantiating objects in the business logic. This separates the object creation process from business logic, enhancing system flexibility and scalability. In PHP development, the Simple Factory Pattern can be used to create different types of objects, achieving object decoupling and code refactoring.
The following example demonstrates how to implement object decoupling using the Simple Factory Pattern.
First, define an Animal interface to declare common behaviors for animals.
<?php interface Animal { public function eat(); public function speak(); } ?>
Create two classes that implement the Animal interface, representing a cat and a dog.
<?php class Cat implements Animal { public function eat() { echo "Cat is eating"; } public function speak() { echo "Cat is meowing"; } } class Dog implements Animal { public function eat() { echo "Dog is eating"; } public function speak() { echo "Dog is barking"; } } ?>
The factory class creates the corresponding animal object based on the input parameter.
<?php class AnimalFactory { public static function create($animalType) { switch ($animalType) { case "cat": return new Cat(); case "dog": return new Dog(); default: throw new Exception("Unsupported animal type: " . $animalType); } } } ?>
In the client code, objects are created through the factory class and methods are called:
<?php $cat = AnimalFactory::create("cat"); $cat->eat(); $cat->speak(); $dog = AnimalFactory::create("dog"); $dog->eat(); $dog->speak(); ?>
With the Simple Factory Pattern, the client code does not need to worry about the details of object creation and only calls the factory method. This achieves:
The PHP OOP Simple Factory Pattern is an efficient design approach. By encapsulating the object creation process in a factory class, it enables object decoupling and code refactoring. In practical development, mastering and applying the Simple Factory Pattern can significantly improve system flexibility and maintainability, making it an essential skill for PHP developers.