桥接模式

定义:将抽象部分与实现部分分离,使它们都可以独立的变化。桥接模式的主要目的是将一个对象的变化因素抽象出来,不是通过类继承的方式来满足这个因素的变化,而是通过对象组合的方式来依赖因素的抽象,这样当依赖的因素的具体实现发生变化后,而我们的具体的引用却不用发生改变,因为我们的对象是依赖于抽象的,而不是具体的实现。

结构图:

1.创建桥接实现接口:

public interface DrawAPI 
{
   public void drawCircle(int radius, int x, int y);
}

2.创建实现了 DrawAPI 接口的实体桥接实现类:

public class GreenCircle implements DrawAPI 
{
    public Override  void drawCircle(int radius, int x, int y) 
    {
    }
}

3.使用 DrawAPI 接口创建抽象类 Shape:

public abstract class Shape 
{
   protected DrawAPI drawAPI;
   protected Shape(DrawAPI drawAPI)
   {
      this.drawAPI = drawAPI;
   }
   public abstract void draw();
}

4.创建实现了 Shape 接口的实体类:

public class Circle extends Shape 
{
   private int x, y, radius;

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

   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}
一直想把之前工作、学习时记录的文档整理到博客上,一方面温故而知新,一方面和大家一起学习 -程序小白
原文地址:https://www.cnblogs.com/wang-jin-fu/p/8318958.html