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();
        }
    }
    

    在这里插入图片描述

    这些类的依赖关系。

    在这里插入图片描述

  • 相关阅读:
    如何利用c++读取.doc文档
    C++经典面试题(验证你的C++水准)
    与你初识
    VS2005发布项目
    请教一:OpenGL旋转
    数据备份和故障修复文件历史记录
    数据备份和故障修复备份与还原
    使用Windows 8 的“任务计划”令HydraVision更加精彩
    Windows 恢复环境(Windows RE模式)
    Unsupported major.minor version 49.0错误处理
  • 原文地址:https://www.cnblogs.com/itjiangpo/p/14181316.html
Copyright © 2011-2022 走看看