W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
橋接模式將定義與其實(shí)現(xiàn)分離。它是一種結(jié)構(gòu)模式。
此模式涉及充當(dāng)橋接的接口。橋使得具體類與接口實(shí)現(xiàn)者類無關(guān)。
這兩種類型的類可以改變而不影響對(duì)方。
interface Printer { public void print(int radius, int x, int y); } class ColorPrinter implements Printer { @Override public void print(int radius, int x, int y) { System.out.println("Color: " + radius +", x: " +x+", "+ y +"]"); } } class BlackPrinter implements Printer { @Override public void print(int radius, int x, int y) { System.out.println("Black: " + radius +", x: " +x+", "+ y +"]"); } } abstract class Shape { protected Printer print; protected Shape(Printer p){ this.print = p; } public abstract void draw(); } class Circle extends Shape { private int x, y, radius; public Circle(int x, int y, int radius, Printer draw) { super(draw); this.x = x; this.y = y; this.radius = radius; } public void draw() { print.print(radius,x,y); } } public class Main { public static void main(String[] args) { Shape redCircle = new Circle(100,100, 10, new ColorPrinter()); Shape blackCircle = new Circle(100,100, 10, new BlackPrinter()); redCircle.draw(); blackCircle.draw(); } }
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: