设计模式面试题

控制反转(IoC)与依赖注入(DI)

  1. 控制反转是一种在软件工程中解耦合的思想,调用类只依赖接口,而不依赖具体的实现类,减少了耦合。控制权交给了容器,在运行的时候才由容器决定将具体的实现动态的“注入”到调用类的对象中。
  2. 依赖注入是一种设计模式,可以作为控制反转的一种实现方式。依赖注入就是将实例变量传入到一个对象中去(Dependency injection means giving an object its instance variables)。
  3. 通过IoC框架,类A依赖类B的强耦合关系可以在运行时通过容器建立,也就是说把创建B实例的工作移交给容器,类A只管使用就可以。

参考:控制反转(IoC)与依赖注入(DI)

理解PHP依赖注入和Laravel的IOC容器

依赖注入:把一个类中可变换的部分提取出来抽象为单独的类,然后在将实例变量注入到原来的类中,供原始类进行使用
IOC容器:控制反转是工程中解耦合的思想,本来需要自己new的类现在完全交给了容器去实例化,比如类A依赖B类,容器创建B的实例,类A只管使用即可。Laravel中Phalcon\DI就是这个容器的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

class SomeComponent
{

protected $_di;

public function __construct($di)
{
$this->_di = $di;
}

public function someDbTask()
{

// Get the connection service
// Always returns a new connection
$connection = $this->_di->get('db');

}

public function someOtherDbTask()
{

// Get a shared connection service,
// this will return the same connection everytime
$connection = $this->_di->getShared('db');

//This method also requires a input filtering service
$filter = $this->_db->get('filter');

}

}

$di = new Phalcon\DI();

//Register a "db" service in the container
$di->set('db', function(){
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});

//Register a "filter" service in the container
$di->set('filter', function(){
return new Filter();
});

//Register a "session" service in the container
$di->set('session', function(){
return new Session();
});

//Pass the service container as unique parameter
$some = new SomeComponent($di);

$some->someTask();

参考:理解PHP 依赖注入|Laravel IoC容器