File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package designpattern .bridge ;
2+
3+ /**
4+ *
5+ * @author liu yuning
6+ *
7+ */
8+ public abstract class Abstraction {
9+ protected Implementor implementor ;// 桥接模式的关键,使得Abstraction聚合Implementor
10+ private String name ;
11+
12+ public Abstraction (String name ) {
13+ this .setName (name );
14+ }
15+
16+ public void setImplementor (Implementor implementor ) {
17+ this .implementor = implementor ;
18+ }
19+
20+ public void operation () {
21+ System .out .print ("Abstraction-" + this .getName () + ": " );
22+ implementor .operation ();
23+ }
24+
25+ public String getName () {
26+ return name ;
27+ }
28+
29+ public void setName (String name ) {
30+ this .name = name ;
31+ }
32+ }
33+
34+ class AbstractionA extends Abstraction {
35+
36+ public AbstractionA (String name ) {
37+ super (name );
38+ }
39+
40+ @ Override
41+ public void operation () {
42+ super .operation ();
43+ }
44+
45+ }
46+
47+ class AbstractionB extends Abstraction {
48+
49+ public AbstractionB (String name ) {
50+ super (name );
51+ }
52+
53+ @ Override
54+ public void operation () {
55+ super .operation ();
56+ }
57+
58+ }
Original file line number Diff line number Diff line change 1+ package designpattern .bridge ;
2+
3+ /**
4+ * 客户端
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class BridgeClient {
10+ public static void main (String [] args ) {
11+
12+ Abstraction a = new AbstractionA ("A" );
13+ a .setImplementor (new ConcreteImplemtorA ());
14+ a .operation ();
15+ a .setImplementor (new ConcreteImplemtorB ());
16+ a .operation ();
17+
18+ Abstraction b = new AbstractionB ("B" );
19+ b .setImplementor (new ConcreteImplemtorA ());
20+ b .operation ();
21+ b .setImplementor (new ConcreteImplemtorB ());
22+ b .operation ();
23+
24+ // 这样通过使用“组合/聚合复用原则”
25+ // 如果继续有AbstractionC ... 或者ConcreteImplemtorC ...
26+ // 只需要扩展类即可,不需要修改现有类,符合“开放-封闭”原则
27+ }
28+
29+ }
Original file line number Diff line number Diff line change 1+ package designpattern .bridge ;
2+
3+ /**
4+ *
5+ * @author liu yuning
6+ *
7+ */
8+ public abstract class Implementor {
9+
10+ public abstract void operation ();
11+
12+ }
13+
14+ class ConcreteImplemtorA extends Implementor {
15+
16+ @ Override
17+ public void operation () {
18+ System .out .println ("ConcreteImplemtorA的方法执行" );
19+
20+ }
21+
22+ }
23+
24+ class ConcreteImplemtorB extends Implementor {
25+
26+ @ Override
27+ public void operation () {
28+ System .out .println ("ConcreteImplemtorB的方法执行" );
29+
30+ }
31+
32+ }
You can’t perform that action at this time.
0 commit comments