桥接适用于把抽象化和实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构性模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦
这种模式设计到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可以被结构化改变而不互相影响。
设计模式意图: 将抽象部分和实现部分分离,使得它们可以独立变化。
优点:
缺点: 桥接模式的引入会增加系统的理解和设计难度,由于聚合挂链关系建立在抽象层,要求开发者针对抽象设计与编程。
使用场景:
总结:
即我们可以通过使用接口类型的变量来调用实现类的引用。
我们有一个作为桥接实现的 drawapi 接口和实现了 drawapi 接口的实体类 redcircle、greencircle。shape 是一个抽象类,将使用 drawapi 的对象。bridgepatterndemo,我们的演示类使用 shape 类来画出不同颜色的圆。
public interface drawapi { public void drawcircle(int radius, int x, int y); }
类redcircle
public 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 +"]"); } }
类greencircle
public 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 +"]"); } }
public abstract class shape { protected drawapi drawapi; protected shape(drawapi drawapi){ this.drawapi = drawapi; } public abstract void draw(); }
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); } }
public class bridgepatterndemo { public static void main(string[] args) { shape redcircle = new circle(100,100, 10, new redcircle()); shape greencircle = new circle(100,100, 10, new greencircle()); redcircle.draw(); greencircle.draw(); } }
drawing circle[ color: red, radius: 10, x: 100, 100] drawing circle[ color: green, radius: 10, x: 100, 100]
如对本文有疑问, 点击进行留言回复!!
设计模式之解释器模式(附:SpelExpressionParser中解释器模式应用分析)
网友评论