原文:http://www.linkedkeeper.com/detail/blog.action?bid=26
Frank 2015/08/18 阅读: 350 评论: 0 收藏: 0
定义将抽象部分与实现部分分离,使它们都可以独立的变化。结构示例Implementor:定义实现接口interface Implementor { // 实现抽象部分需要的某些具体功能 public void operationImpl();}Abstraction:定义抽象接口abstract class Abstraction { // 持有一个 Implementor 对象,... |
定义
将抽象部分与实现部分分离,使它们都可以独立的变化。
结构
示例
Implementor:定义实现接口
1
2
3
4
|
interface Implementor {
public void operationImpl();
}
|
Abstraction:定义抽象接口
1
2
3
4
5
6
7
8
9
10
11
12
13
|
abstract class Abstraction {
protected Implementor impl;
public Abstraction(Implementor impl) {
this .impl = impl;
}
public void operation() {
impl.operationImpl();
}
}
|
ConcreteImplementor:实现 Implementor 中定义的接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class ConcreteImplementorA implements Implementor {
@Override
public void operationImpl() {
System.out.println( "具体的实现A" );
}
}
class ConcreteImplementorB implements Implementor {
@Override
public void operationImpl() {
System.out.println( "具体的实现B" );
}
}
|
RefinedAbstraction:扩展 Abstraction 类
1
2
3
4
5
6
7
8
9
10
11
12
|
class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor impl) {
super (impl);
}
public void otherOperation() {
}
}
|
测试代码
1
2
3
4
5
6
7
8
|
public class BridgePattern {
public static void main(String[] args) {
Implementor impl = new ConcreteImplementorA();
RefinedAbstraction abs = new RefinedAbstraction(impl);
abs.operation();
abs.otherOpertaion();
}
}
|
样例
实现部分定义接口
1
2
3
4
|
interface MessageImplementor {
public void send(String message);
}
|
抽象部分定义接口
1
2
3
4
5
6
7
8
9
10
11
12
|
public abstract class AbstractMessage {
protected MessageImplementor impl;
public AbstractMessage(MessageImplementor impl) {
this .impl = impl;
}
public void sendMessage(String message) {
this .impl.send(message);
}
}
|
具体的实现发送消息
1
2
3
4
5
6
7
8
9
10
11
|
public class MessageSMS implements MessageImplementor {
public void send(String message) {
System.out.prinlt( "使用短信方式发送消息:" + message);
}
}
public class MessageEmail implements MessageImplementor {
public void send(String message) {
System.out.println( "使用Email方法发送消息:" + message);
}
}
|
抽象的消息消息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class CommonMessage extends AbstractMessage {
public CommonMessage(MessageImplementor impl) {
super (impl);
}
public void sendMessage(Stirng message) {
super .sendMessage(message);
}
}
public class UrgencyMessage extends AbstractMessage {
public UrgencyMessage (MessageImplementor impl) {
super (impl);
}
public void sendMessage(Stirng message) {
super .sendMessage(message);
}
}
|
转载请并标注:
“本文转载自 http://www.linkedkeeper.com/detail/blog.action?bid=26 (文/Frank)”
|