Junior — Middle
Which design pattern is best to apply when creating an object considering different implementation conditions?
sobes.tech AI
Answer from AI
To create an object with different dependency injection conditions, it is best to use the Factory pattern or Abstract Factory.
This pattern encapsulates the object creation logic and allows choosing a specific class for creation depending on runtime conditions.
Example of a simple factory method:
interface LoggerInterface {
public function log(string $message);
}
class FileLogger implements LoggerInterface {
public function log(string $message) {
// write to file
}
}
class DatabaseLogger implements LoggerInterface {
public function log(string $message) {
// write to database
}
}
class LoggerFactory {
public static function create(string $type): LoggerInterface {
if ($type === 'file') {
return new FileLogger();
} elseif ($type === 'db') {
return new DatabaseLogger();
}
throw new Exception('Unknown logger type');
}
}
$logger = LoggerFactory::create('file');
$logger->log('Message');
Thus, you can flexibly create objects depending on conditions.