Шаблон проектирования "Внедрение зависимости"
5 марта 2020Относится к структурным шаблонам.
Используется для реализации слабосвязанной архитектуры.
Пример на PHP
class DatabaseConfiguration
{
private string $host;
private int $port;
private string $username;
private string $password;
public function __construct(string $host, int $port, string $username, string $password)
{
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
}
public function getHost(): string
{
return $this->host;
}
public function getPort(): int
{
return $this->port;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
}
class DatabaseConnection
{
private DatabaseConfiguration $configuration;
public function __construct(DatabaseConfiguration $config)
{
$this->configuration = $config;
}
public function getDsn()
{
return sprintf(
'%s:%s@%s:%d',
$this->configuration->getUsername(),
$this->configuration->getPassword(),
$this->configuration->getHost(),
$this->configuration->getPort()
);
}
}
Использование:
$config = new DatabaseConfiguration('localhost', 3306, 'user', '1234');
$connection = new DatabaseConnection($config);
$dsn = $connection->getDsn();
Пример на Go
package main
import "fmt"
type DatabaseConfiguration struct {
host string
port int
username string
password string
}
type DatabaseConnection struct {
config *DatabaseConfiguration
}
func (c *DatabaseConfiguration) GetHost() string {
return c.host
}
func (c *DatabaseConfiguration) GetPort() int {
return c.port
}
func (c *DatabaseConfiguration) GetPassword() string {
return c.password
}
func (c *DatabaseConfiguration) GetUsername() string {
return c.username
}
func (c DatabaseConnection) GetDSN() string {
return fmt.Sprintf(
"%s:%s@%s:%d",
c.config.GetUsername(),
c.config.GetPassword(),
c.config.GetHost(),
c.config.GetPort(),
)
}
func main() {
dbConf :=DatabaseConfiguration{
host: "localhost",
port: 3306,
password: "test",
username: "test",
}
dbConn := DatabaseConnection{config: &dbConf}
dbConn.GetDSN()
}
Источники:
http://designpatternsphp.readthedocs.io/ru/latest/Structural/DependencyInjection/README.html