电子说
桥接模式的目标是使对象的抽象部分与实现部分分离,使之可以分别独立变化,以尽量避免产生耦合。
下图以绘制圆形为例:圆形的颜色通过接口类DrawAPI及其2个实现类RedCircle以及GreenCircle实现;圆形的坐标以及半径通过抽象类及其扩展类实现,在实现draw()方法时,直接使用DrawAPI类中的相关对象的drawCircle方法。
DrawAPI接口类:
package bridge;
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
RedCircle实现类:
package bridge;
public class RedCircle implements DrawAPI{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("画红色圆,半径"+radius+",坐标:x="+x+",y="+y);
}
}
GreenCircle实现类:
package bridge;
public class GreenCircle implements DrawAPI{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("画绿色圆,半径"+radius+",坐标:x="+x+",y="+y);
}
}
Shape抽象类:
package bridge;
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI=drawAPI;
}
public abstract void draw();
}
Circle扩展类:
package bridge;
public class Circle extends Shape{
int x, y, radius;
public Circle(DrawAPI drawAPI,int x,int y,int radius) {
super(drawAPI);
this.x=x;
this.y=y;
this.radius=radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
主函数调用方式:
package main;
import bridge.*;
public class BridgePattern {
public static void main(String[] args) {
Shape redCircle =new Circle(new RedCircle(),10,10,5);
Shape greenCircle = new Circle(new GreenCircle(),20,20,6);
redCircle.draw();
greenCircle.draw();
}
}
全部0条评论
快来发表一下你的评论吧 !