学习地址:http://www.runoob.com/design-pattern/bridge-pattern.html

桥接模式(Bridge Pattern)


桥接模式(Bridge pattern)属于结构型模式,它提供一个桥接结构,来实现二者的解耦

这种模式使用一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响

博主餐好了几个博客,于是顺手也采取了颜色与形状的简单例子。

主要解决:个人理解,对类的多维切分,从某种角度上方便了扩展。

何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。

如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。

代码:

1、形状以及桥梁抽象类:

package com.pat.bridge;

/**
* 这是桥接模式中的桥梁(形状抽象类)
* @author ZX
*
*/
public abstract class ShapeBridge {
Color color;
public abstract void draw();
} /**
* 具体形状
* @author ZX
*
*/
class Circle extends ShapeBridge{
String shape="圆形"; public void draw() {
color.paint(shape);
} public Circle(Color color) {
this.color=color;
}
}
class Squre extends ShapeBridge{
String shape="正方形"; public void draw() {
color.paint(shape);
}
public Squre(Color color) {
this.color=color;
}
}

2、颜色类,被桥接对象

package com.pat.bridge;
/**
* 颜色接口
* @author ZX
*
*/
public interface Color {
void paint(String shape); }
/**
* 具体颜色
* @author ZX
*
*/
class Red implements Color{ @Override
public void paint(String shape) {
if(shape==null||"".equals(shape)) {
System.out.println("红色色块");
}else {
System.out.println("红色"+shape);
}
}
}
class Blue implements Color{ @Override
public void paint(String shape) {
if(shape==null||"".equals(shape)) {
System.out.println("蓝色色块");
}else {
System.out.println("蓝色"+shape);
}
}
}

3、测试类:

package com.pat.bridge;

public class Test {
public static void main(String[] args) {
Red red = new Red();
Squre sq = new Squre(red);
sq.draw();
}
}

4、结果:

红色正方形

最新文章

  1. 懒加载lazyload
  2. 编译原理-词法分析03-DFA
  3. C++ 读取txt文本内容,并将结果保存到新文本
  4. JavaScript HTML CSS外部链接
  5. Linux 中强大且常用命令:find、grep
  6. CSS子元素居中(父元素宽高已知,子元素未知)
  7. Winform知识
  8. jQuery之选择器
  9. ajax详解,以及异步JSOP的实现
  10. win7系统64位plsql的设置
  11. redis+tomcat共享session问题(转)
  12. jquery扩展方法
  13. struts 中的创建Action的三种方法
  14. acm 2015北京网络赛 F Couple Trees 主席树+树链剖分
  15. 同步锁Lock(互斥锁)
  16. 基于Otsu算法的图像自适应阈值切割
  17. linux2.6.30.4内核移植(6)——移植应用程序hello world常见的错误:-bin/sh ./hello not found
  18. 原子性、可见性、synchronized 有好理解
  19. 修改spfile位置
  20. Art & Material

热门文章

  1. DDD实战6 单元测试
  2. 我所理解的设计模式(C++实现)——观察者模式(Observer Pattern)
  3. 网络编程Socket它TCP它TIME_WAIT国家具体解释
  4. boost库交叉编译(Linux生成ARM的库)
  5. Golang写https服务端
  6. jquery 标签页
  7. 所有语言的Awesome(2)
  8. C++的中英文字符串表示(string,wstring),使用wcout.imbue(std::locale("chs"));本地化解析编码
  9. IDisposeable 最佳实现
  10. JVM的几个介绍