JSRUN 用代码说话

桥接模式

编辑教程

Java设计模式 - 桥接模式

桥接模式将定义与其实现分离。它是一种结构模式。

此模式涉及充当桥接的接口。桥使得具体类与接口实现者类无关。

这两种类型的类可以改变而不影响对方。

例子

interface Printer {
   public void print(int radius, int x, int y);
}
class ColorPrinter implements Printer {
   @Override
   public void print(int radius, int x, int y) {
      System.out.println("Color: " + radius +", x: " +x+", "+ y +"]");
   }
}
class BlackPrinter implements Printer {
   @Override
   public void print(int radius, int x, int y) {
      System.out.println("Black: " + radius +", x: " +x+", "+ y +"]");
   }
}
abstract class Shape {
   protected Printer print;
   protected Shape(Printer p){
      this.print = p;
   }
   public abstract void draw();  
}
class Circle extends Shape {
   private int x, y, radius;

   public Circle(int x, int y, int radius, Printer draw) {
      super(draw);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }

   public void draw() {
      print.print(radius,x,y);
   }
}
public class Main {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new ColorPrinter());
      Shape blackCircle = new Circle(100,100, 10, new BlackPrinter());

      redCircle.draw();
      blackCircle.draw();
   }
}

上面的代码生成以下结果。

Color:10,x:100,100
Black:10,x:100,100
JSRUN闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
金额: 0
备注:
转账时请填写正确的金额和备注信息,到账由人工处理,可能需要较长时间
如有疑问请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟