Junior — Middle
To which group does the 'Factory' pattern belong in the context of software design?
sobes.tech AI
Answer from AI
The "Factory" pattern belongs to the group of creational design patterns. Its main task is to create objects, hiding the logic of their creation and allowing client code to work with abstractions rather than specific classes.
For example, in PHP, you can use a factory to create different types of objects depending on parameters:
interface Logger {
public function log(string $message);
}
class FileLogger implements Logger {
public function log(string $message) {
// Write to file
}
}
class DatabaseLogger implements Logger {
public function log(string $message) {
// Write to database
}
}
class LoggerFactory {
public static function create(string $type): Logger {
if ($type === 'file') {
return new FileLogger();
} elseif ($type === 'database') {
return new DatabaseLogger();
}
throw new Exception("Unknown logger type");
}
}
$logger = LoggerFactory::create('file');
$logger->log('Message');
Thus, the factory encapsulates object creation and simplifies code extensibility and maintenance.