桥接模式
Posted forthedream1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了桥接模式相关的知识,希望对你有一定的参考价值。
1.基本概念
- 将抽象化与实现化解耦
- UML
2.代码实现
package com.chengjie; interface DrawAPI { void drawCircle(int radius, int x, int y); } class RedCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: red, radius: " + radius +", x: " +x+", "+ y +"]"); } } class GreenCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: green, radius: " + radius +", x: " +x+", "+ y +"]"); } } abstract class Shape1 { public Shape1(DrawAPI drawAPI) { this.drawAPI = drawAPI; } protected DrawAPI drawAPI; public abstract void draw(); } class Circle1 extends Shape1 { private int radius, x, y; public Circle1(DrawAPI drawAPI, int radius, int x, int y) { super(drawAPI); this.radius = radius; this.x = x; this.y = y; } @Override public void draw() { this.drawAPI.drawCircle(radius, x, y); } } public class TestBridge { public static void main(String[] args) { Circle1 redCircle = new Circle1(new RedCircle(),100, 10, 10); Circle1 greenCircle = new Circle1(new GreenCircle(),100, 10, 10); redCircle.draw(); greenCircle.draw(); } }
3.优点
- 抽象与实现分离
- 当有新API时,容易扩展
4.缺点
- 会增加系统的理解与设计难度
5.应用场景
- 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展
- JDBC
6.参考
https://www.cnblogs.com/java-my-life/archive/2012/05/07/2480938.html
http://www.runoob.com/design-pattern/bridge-pattern.html
以上是关于桥接模式的主要内容,如果未能解决你的问题,请参考以下文章