Junior — Middle
Can you list the main design patterns for classes?
sobes.tech AI
Answer from AI
Design patterns for classes in PHP (and in OOP in general) include:
- Singleton — ensures a class has only one instance and provides a global point of access.
- Factory Method — defines an interface for creating an object, allowing subclasses to alter the type of objects created.
- Abstract Factory — provides an interface for creating families of related or dependent objects without specifying their concrete classes.
- Strategy — enables selecting an algorithm's behavior at runtime by encapsulating algorithms in separate classes.
- Decorator — dynamically adds responsibilities to objects by wrapping them.
- Observer — defines a dependency between objects so that when one changes, others are notified.
- Adapter — converts the interface of a class into another interface clients expect.
- Facade — provides a simplified interface to a complex system.
Example of Singleton in PHP:
class Singleton {
private static $instance = null;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
These patterns help write flexible, extendable, and maintainable code.