桥接模式
桥接模式(Bridge Pattern)也叫做桥梁模式,是一个比较简单的模式,其定义如下: Decouple an abstraction from its implementation so that the two can vary independently.(将抽象和实现解耦,使得两者可以独立地变化。)
例如我们需要发送消息给用户,可以选择短信,也可以选择邮件,并且邮件和短信都可以分为加急消息和普通消息,代码如下:
public interface MessageSender {
void send(String message, String toUser);
}
/**
* @Description: 邮件发送
*/
class EmailMessageSender implements MessageSender {
@Override
public void send(String message, String toUser) {
// TODO Auto-generated method stub
}
}
/**
* @Description: 短信发送
*/
class SmsMessageSender implements MessageSender {
@Override
public void send(String message, String toUser) {
// TODO Auto-generated method stub
}
}
创建一个桥接抽象角色类
public class AbstractMessageSender {
private MessageSender messageSender;
public AbstractMessageSender(MessageSender messageSender) {
this.messageSender = messageSender;
}
public void sendMessage(String message, String toUser) {
this.messageSender.send(message, toUser);
}
}
创建一个普通消息类
public class NomalMessage extends AbstractMessageSender {
public NomalMessage(MessageSender messageSender) {
super(messageSender);
}
@Override
public void sendMessage(String message, String toUser) {
super.sendMessage(message, toUser);
}
}
创建一个加急消息类
class UrgencyMessage extends AbstractMessageSender {
public UrgencyMessage(MessageSender messageSender) {
super(messageSender);
}
@Override
public void sendMessage(String message, String toUser) {
message = "加急:" + message;
super.sendMessage(message, toUser);
}
}
使用
public static void main(String[] args) {
MessageSender messageSender = new SmsMessageSender();
AbstractMessageSender abstractMessageSender = new NomalMessage(messageSender);
abstractMessageSender.sendMessage("普通消息", "张三");
messageSender = new EmailMessageSender();
abstractMessageSender = new UrgencyMessage(messageSender);
abstractMessageSender.sendMessage("加急消息", "李四");
}