您的位置:首页 > 编程语言 > Java开发

JAVA设计模式之桥接模式

2017-11-13 12:27 609 查看

标签: java设计模式

2017-04-25 18:06 408人阅读 评论(0) 收藏 举报


分类:

java设计模式(24)


将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者可以独立地变化。这句话有三个关键词,也就是抽象化、实现化和脱耦。
抽象化
存在于多个实体中的共同的概念性联系,就是抽象化。作为一个过程,抽象化就是忽略一些信息,从而把不同的实体当做同样的实体对待。
实现化
抽象化给出的具体实现,就是实现化。
脱耦
所谓耦合,就是两个实体的行为的某种强关联。而将它们的强关联去掉,就是耦合的解脱,或称脱耦。在这里,脱耦是指将抽象化和实现化之间的耦合解脱开,或者说是将它们之间的强关联改换成弱关联。

将两个角色之间的继承关系改为聚合关系,就是将它们之间的强关联改换成为弱关联。因此,桥梁模式中的所谓脱耦,就是指在一个软件系统的抽象化和实现化之间使用组合/聚合关系而不是继承关系,从而使两者可以相对独立地变化

参与者

1.Abstraction : 定义抽象类的接口。 维护一个指向Implementor类型对象的指针。

2.RefinedAbstraction:扩充由Abstraction定义的接口。

3.Implementor:定义实现类的接口,该接口不一定要与Abstraction的接口完全一致。 事实上这两个接口可以完全不同。 一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些基本操作的较高层次的操作。

4.ConcreteImplementor:实现Implementor接口并定义它的具体实现。

类图



示例

Abstraction

/**
* 定义Abstraction Person类
*/
public abstract class Person {

private Clothing clothing;
private String type;

public Clothing getClothing() {
return clothing;
}

public void setClothing(Clothing clothing) {
this.clothing = clothing;
}

public void setType(String type) {
this.type = type;
}

public String getType() {
return this.type;
}

public abstract void dress();
}


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

RefinedAbstraction

/**
* 定义RefinedAbstraction类Man
*/
public class Man extends Person {
public Man() {
setType("男人");
}

public void dress() {
Clothing clothing = getClothing();
clothing.personDressCloth(this);
}
}

/**
* 定义RefinedAbstraction类Lady
*/
public class Lady extends Person {
public Lady() {
setType("女人");
}

public void dress() {
Clothing clothing = getClothing();
clothing.personDressCloth(this);
}
}


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

Implementor

/**
* 定义Implementor 类Clothing
*
*/
public abstract class Clothing {
public abstract void personDressCloth(Person person);
}


1

2

3

4

5

6

7

ConcreteImplementor

/**
* 定义ConcreteImplementor类Jacket
*/
public class Jacket extends Clothing {
public void personDressCloth(Person person) {
System.out.println(person.getType() + "穿马甲");
}
}
/**
* 定义ConcreteImplementor类 Trouser
*/
public class Trouser extends Clothing {
public void personDressCloth(Person person) {
System.out.println(person.getType() + "穿裤子");
}
}


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Test

/**
* 测试类
*/
public class Test {

public static void main(String[] args) {

Person man = new Man();

Person lady = new Lady();

Clothing jacket = new Jacket();

Clothing trouser = new Trouser();

jacket.personDressCloth(man);
trouser.personDressCloth(man);

jacket.personDressCloth(lady);
trouser.personDressCloth(lady);
}
}


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

result

男人穿马甲
男人穿裤子
女人穿马甲
女人穿裤子


1

2

3

4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: