喜迎
春节

设计模式——桥接模式


说明

桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化。桥接的用意是:将抽象化与实现化解耦,使得二者可以独立变化,像我们常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时候,在各个数据库之间进行切换,基本不需要动太多的代码,甚至丝毫不用动,原因就是JDBC提供统一接口,每个数据库提供各自的实现,用一个叫做数据库驱动的程序来桥接就行了。

示例

下面看下桥接模式的代码实现

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
// 定义接口
interface Sourceable{
public function method();
}

// 定义两个实现类
class SourceSub1 implements Sourceable{
public function method(){
echo "this is first sub!" . PHP_EOL;
}
}

class SourceSub2 implements Sourceable{
public function method(){
echo "this is the second sub!" . PHP_EOL;
}
}

// 定义一个桥,持有Sourceable的一个实例
abstract class Bridge{
private Sourceable $source;

public function method(){
$this->source->method();
}

public function getMSource(): Sourceable{
return $this->source;
}

public function setSource(Sourceable $source){
$this->source = $source;
}
}

class MyBridge extends Bridge{
public function method(){
$this->getMSource()->method();
}
}

// 调用
$bridge = new MyBridge();

$source1 = new SourceSub1();
$bridge->setSource($source1);
$bridge->method();

$source2 = new SourceSub2();
$bridge->setSource($source2);
$bridge->method();
// 这样,就通过对Bridge类的调用,实现了对接口Sourceable的实现类SourceSub1和SourceSub2的调用。

/**
* output:
this is first sub!
this is the second sub!

// 定义接口
interface Sourceable{
public function method();
}

// 定义两个实现类
class SourceSub1 implements Sourceable{
public function method(){
echo "this is first sub!" . PHP_EOL;
}
}

class SourceSub2 implements Sourceable{
public function method(){
echo "this is the second sub!" . PHP_EOL;
}
}

// 定义一个桥,持有Sourceable的一个实例
abstract class Bridge{
private Sourceable $source;

public function method(){
$this->source->method();
}

public function getMSource(): Sourceable{
return $this->source;
}

public function setSource(Sourceable $source){
$this->source = $source;
}
}

class MyBridge extends Bridge{
public function method(){
$this->getMSource()->method();
}
}

// 调用
$bridge = new MyBridge();

$source1 = new SourceSub1();
$bridge->setSource($source1);
$bridge->method();

$source2 = new SourceSub2();
$bridge->setSource($source2);
$bridge->method();
// 这样,就通过对Bridge类的调用,实现了对接口Sourceable的实现类SourceSub1和SourceSub2的调用。

/**
* output:
this is first sub!
this is the second sub!

*/

总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
评 论
 上一篇
设计模式——工厂方法模式
设计模式——工厂方法模式
说明 创建一个工厂接口和创建多个工厂实现类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了,不需要修改之前的代码。 示例下面看下工厂方法模式的代码实现 1234567891011121314151617181920212223242
2022-05-19
下一篇 
设计模式——模板方法模式
设计模式——模板方法模式
说明示例下面看下模板方法模式的代码实现 12345678910111213141516171819202122232425262728abstract class AbstractCalculator{ public final fu
2022-05-19
  目录