zoukankan      html  css  js  c++  java
  • 1.8(设计模式)桥接模式

    桥接模式可以将抽象和实现分离开来,两者可以单独变化互不干扰。

    两者之间通过一个桥梁连接,所以称为桥接模式。

    下面举一个具体的例子,假设这里有一个抽象类Shape,还有一些实现类RedCircle,GreenCircle.

    它们之间通过桥梁DrawAPI接口连接起来。

    桥梁接口(桥接模式中的桥梁)

    public interface DrawAPI {
        public void drawCircle(float r,float x, float y);
    }

    具体的实现类要实现桥梁接口(桥接模式中的实现部分)

    GreenCircle

    public class GreenCircle implements DrawAPI{
    
        @Override
        public void drawCircle(float r, float x, float y) {
            System.out.println("draw greenCircle" + "r:" + r +" x:" + x + " y:" + y);
        }
    
    }

    RedCircle

    public class RedCircle implements DrawAPI{
    
        @Override
        public void drawCircle(float r, float x, float y) {
            System.out.println("draw redCircle" + "r:" + r +" x:" + x + " y:" + y);
        }
    }

    Shape(桥接模式中的抽象部分) Shape使用了DrawAPI(桥梁)

    public abstract class Shape {
        protected DrawAPI drawAPI;
        
        public Shape(DrawAPI drawAPI) {  // 抽象类也是类,只是不能由自身实例化,
            this.drawAPI = drawAPI;      //一般通过子类实例化(默认调用无参构造方法),如果添加了构造方法,需要在子类中引用。
        }
        
        public abstract void draw();
    }

    Circle :Shape的具体类

    public class Circle extends Shape{
        private float r;
        private float x;
        private float y;
        
        
        public Circle(float r, float x, float y,DrawAPI drawAPI) {
            super(drawAPI);
            // TODO Auto-generated constructor stub
            this.r = r;
            this.x = x;
            this.y = y;
        }
    
        @Override
        public void draw() {
            // TODO Auto-generated method stub
            drawAPI.drawCircle(r, x, y);
        }
    }

    测试:

    public class Main {
        public static void main(String[] args) {
            Shape greenCircle = new Circle(2, 0, 0, new GreenCircle());
            greenCircle.draw();
            Shape redCircle = new Circle(2, 0, 0, new RedCircle());
            redCircle.draw();
        }
    }
    draw greenCircler:2.0 x:0.0 y:0.0
    draw redCircler:2.0 x:0.0 y:0.0

    上述抽象和实现之间通过桥梁连接,抽象和实现之间可以独立的变换,改变具体的实现类不会对抽象类造成影响。

    改变抽象类也不会对实现类造成影响,只要两者连接的桥梁没有发生改变,两者都可以独立的变换而且易于扩展。

  • 相关阅读:
    20191024-6 Alpha发布用户使用报告
    【第三章】MySQL数据库的字段约束:数据完整性、主键、外键、非空、默认值、自增、唯一性
    【第六章】MySQL日志文件管理
    【第四章】MySQL数据库的基本操作:数据库、表的创建插入查看
    【第一章】MySQL数据概述
    【Linux运维】LNMP环境配置
    【Linux 运维】linux系统修改主机名
    【Linux 运维】linux系统查看版本信息
    【Linux 运维】Centos7初始化网络配置
    50、树中两个节点的公共祖先
  • 原文地址:https://www.cnblogs.com/huang-changfan/p/10950133.html
Copyright © 2011-2022 走看看