【设计模式】结构型04桥接模式(Bridge Pattern)

时间:2023-03-09 22:58:00
【设计模式】结构型04桥接模式(Bridge Pattern)

学习地址: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、结果:

红色正方形