一、定义:
将抽象部分与它的实现部分分离,是他们可以独立地变化。。
二、体现原则:
开闭原则、组合/聚合复用原则(用组合/聚合代替 继承)、
三、例子实现:
实例1(PPT):不同发送消息的方式:
UML图:
代码实现:
//抽象消息类
public abstract class AbstractMessage {
private MessageInterface mi;
public AbstractMessage() {
}
public AbstractMessage(MessageInterface mi) {
this.mi=mi;
}
public void sendMessage() {
this.mi.send();
}
}
public class CommonMessage extends AbstractMessage {
public CommonMessage(MessageInterface messageSMS) {
super(messageSMS);
}
public void sendMessage() {
System.out.println("这是普通消息!");
super.sendMessage();
}
}
public class UrgencyMessage extends AbstractMessage {
public UrgencyMessage(MessageInterface mif) {
super(mif);
}
public void sendMessage() {
System.out.println("这是加急消息!");
super.sendMessage();
}
}
//发送方式接口
public interface MessageInterface {
public void send();
}
package 桥接模式消息发送;
public class MessageEmail implements MessageInterface {
@Override
public void send() {
System.out.println("Email消息发送!");
}
}
package 桥接模式消息发送;
public class MessageSMS implements MessageInterface {
@Override
public void send() {
System.out.println("站内消息发送!");
}
}
//场景类
public class Client {
public static void main(String args[]) {
AbstractMessage amss=new CommonMessage(new MessageEmail());
amss.sendMessage();
amss=new CommonMessage(new MessageSMS());
amss.sendMessage();
amss=new UrgencyMessage(new MessageEmail());
amss.sendMessage();
amss=new UrgencyMessage(new MessageSMS());
amss.sendMessage();
}
}
实例2(课本)手机型号和软件:
UML图:略
代码实现:
//软件接口
public interface ISoft {
public void run();
}
//游戏软件
public class GameSoft implements ISoft {
@Override
public void run() {
System.out.println("运行游戏!");
}
}
//通讯录软件
public class AddressSoft implements ISoft {
@Override
public void run() {
System.out.println("运行通讯录!");
}
}
//抽象手机品牌
package 手机型号与软件;
public abstract class Brand {
private ISoft s=null;
public Brand(ISoft is) {
this.s=is;
}
public void run() {
s.run();
}
}
//具体品牌
public class BrandA extends Brand {
public BrandA(ISoft is) {
super(is);
}
public void run() {
System.out.println("A品牌手机:");
super.run();
}
}
package 手机型号与软件;
public class BrandB extends Brand {
public BrandB(ISoft is) {
super(is);
}
public void run() {
System.out.println("B品牌手机");
super.run();
}
}
//场景类
public class Client {
public static void main(String[] args) {
Brand A=new BrandA(new GameSoft());
A.run();
Brand B=new BrandB(new AddressSoft());
B.run();
}
}
The end;