zoukankan      html  css  js  c++  java
  • 桥梁模式

    桥梁模式也属于结构性模式中的一种。
    中间的接口在类与类之间充当“桥梁”的角色。
    主要作用还是对代码之间进行抽象和解耦。
    首先创建一个接口,作为及各类之间的“桥梁”。

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

    这时候两根不同颜色的笔实现了DrawAPI接口,画出不同的颜色和形状。

    RedPen

    public class RedPen implements DrawAPI {
        @Override
        public void draw(int radius, int x, int y) {
            System.out.println("红笔 radius="+redius+" 从 x="+x+"  到y="+y);
        }
    }
    

    GreenPen

    public class GreedPen implements DrawAPI {
        @Override
        public void draw(int radius, int x, int y) {
            System.out.println("绿笔 radius="+radius+" 从 x="+x+" 到 y="+y);
        }
    }
    
    

    这时候有个图形的抽象类BaseShape,需要画出不同的形状。因此构造方法中需要传入DrawAPI接口,并且两者之间是组合关系。

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

    然后Circle和Rectangle继承BaseShape抽象类。

    Rectangle

    public class Rectangle extends BaseShape {
        private int radius,x,y;
        protected Rectangle(int radius, int x,int y,DrawAPI drawAPI) {
            super(drawAPI);
            this.radius = radius;
            this.x = x;
            this.y = y;
        }
    
        @Override
        public void draw() {
            drawAPI.draw(radius,x,y);
        }
    }
    
    

    Circle

    public class Circle extends BaseShape {
        int radius;
        protected Circle(int radius,DrawAPI drawAPI) {
            super(drawAPI);
            this.radius = radius;
        }
    
        @Override
        public void draw() {
            drawAPI.draw(radius,0,0);
        }
    }
    
    

    来吧,测试一下这药怎么玩?

    public class BridgeTest {
        public static void main(String[] args) {
        	// 画一个绿色的圆
            BaseShape greenCircle = new Circle(10, new GreedPen());
            // 画一个红色的矩形
            BaseShape redRectangle = new Rectangle(4, 8,9, new RedPen());
            greenCircle.draw();
            redRectangle.draw();
        }
    }
    

    在这里插入图片描述

    这些类的依赖关系。

    在这里插入图片描述

  • 相关阅读:
    二叉树线索化。。。
    如何通过指针访问虚函数表,并且调用里面的方法
    进程间通信IPC
    什么时候该用assert
    高并发服务端分布式系统设计概要(上)
    C语言读写文件
    Linux 与 BSD 有什么不同?
    extern "C" 使用
    C语言字符数组的定义与初始化
    Linux守护进程
  • 原文地址:https://www.cnblogs.com/itjiangpo/p/14181316.html
Copyright © 2011-2022 走看看