桥接模式
来源:互联网 发布:方舟生存进化优化好吗 编辑:程序博客网 时间:2024/06/05 19:36
桥接模式:将抽象部分与它的实现部分分离,使他们能够独立的变化。
合成/聚合复用原则:尽量使用合成/聚合,尽量不要使用类继承。
聚合表示的是一种弱的拥有关系,体现了A对象可以包含B对象,但B对象不是A对象的一部分;合成则是一种强的拥有关系,体现了严格的整体与部分的关系,部分与整体的生命周期是一样的。
抽象实例
Implementor.java
public abstract class Implementor { public abstract void operation();}class ConcreteImplementA extends Implementor{ @Override public void operation() { System.out.println("具体实现类A的实现"); }}class ConcreteImplementB extends Implementor{ @Override public void operation() { System.out.println("具体实现类B的实现"); }}
Abstraction.java
public class Abstraction { protected Implementor implementor; public void setImplementor(Implementor implementor){ this.implementor=implementor; } public void operation(){ implementor.operation(); }}
RefinedAbstraction.java
public class RefinedAbstraction extends Abstraction{ @Override public void operation() { implementor.operation(); }}
Test.java
public class Test { public static void main(String[] args) { RefinedAbstraction refinedAbstraction = new RefinedAbstraction(); refinedAbstraction.setImplementor(new ConcreteImplementA()); refinedAbstraction.operation(); refinedAbstraction.setImplementor(new ConcreteImplementB()); refinedAbstraction.operation(); }}
具体实例
手机与软件之间的聚合关系
HandSetSoft.java-手机软件
/** * 手机软件 * @author Carl_Hugo */public abstract class HandSetSoft { public abstract void run();}class HandSetGame extends HandSetSoft{ @Override public void run() { System.out.println("运行手机游戏"); }}class HandSetAddressList extends HandSetSoft{ @Override public void run() { System.out.println("运行手机通讯录"); }}
HandSetBrand.java-手机品牌
public abstract class HandSetBrand { protected HandSetSoft soft; //设置手机软件 public void setHandSetSoft(HandSetSoft soft){ this.soft=soft; } //运行 public abstract void run();}class HandSetBrandN extends HandSetBrand{ @Override public void run() { System.out.print("品牌N:"); soft.run(); }}class HandSetBrandM extends HandSetBrand{ @Override public void run() { System.out.print("品牌M:"); soft.run(); }}
测试
public class Test { public static void main(String[] args) { HandSetBrand ab; ab=new HandSetBrandN(); ab.setHandSetSoft(new HandSetGame()); ab.run(); ab.setHandSetSoft(new HandSetAddressList()); ab.run(); ab=new HandSetBrandM(); ab.setHandSetSoft(new HandSetGame()); ab.run(); ab.setHandSetSoft(new HandSetAddressList()); ab.run(); }}
输出:
0 0
- 设计模式:适配器模式,桥接模式
- 设计模式----桥接模式
- 设计模式---桥接模式
- 结构性模式-桥接模式
- 设计模式:桥接模式
- 设计模式 桥接模式
- 设计模式 - 桥接模式
- 设计模式--桥接模式
- 设计模式--桥接模式
- 设计模式 - 桥接模式
- 设计模式-桥接模式
- 设计模式 - 桥接模式
- 设计模式 - 桥接模式
- 【设计模式-桥接模式】
- 设计模式:桥接模式
- 【设计模式】----桥接模式
- 【设计模式】桥接模式
- 设计模式--桥接模式
- 定位的准确度与精度指标定义——RMS,CEP,Sigma
- Android spannableStringBuilder用法整理
- android LayoutInflater.inflate()的参数介绍
- JS的取经之路(三)
- 判别Class是否属于Interface
- 桥接模式
- VS2013 安装错误 Windows 程序兼容性模式已打开
- 第十二章 Spring组合注解
- swift 3.0 短信验证码倒计时实现
- DELPHI中MessageBox的用法 (转)
- 大龄码农的困惑
- 基于dragonboard 410c的kobuki机器人控制——远程控制
- struct usb_interface_descriptor
- 贝塞尔曲线