桥接模式
介绍
实现
步骤 1
|
1
2
3
|
public interface DrawAPI { public void drawCircle(int radius, int x, int y); } |
步骤 2
|
1
2
3
4
5
6
7
|
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 +"]"); } } |
|
1
2
3
4
5
6
7
|
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 +"]"); } } |
步骤 3
|
1
2
3
4
5
6
7
|
public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); } |
步骤 4
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
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); } } |
步骤 5
|
1
2
3
4
5
6
7
8
9
|
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(); } } |
步骤 6
|
1
2
|
Drawing Circle[ color: red, radius: 10, x: 100, 100] Drawing Circle[ color: green, radius: 10, x: 100, 100] |
原文:https://www.cnblogs.com/zhuxiaopijingjing/p/12340321.html