1. 程式人生 > >路一步步走>> 設計模式七:橋接-Bridge

路一步步走>> 設計模式七:橋接-Bridge

理解的不是很深 。用到在看。

package com.test.DPs.JieGou.Bridge;
/**
 * 結構型:Bridge-橋接		橋接:作用面為 物件
 * 
 * 用途:將抽象部分與它的實現部分分離,使它們都可以獨立的變化。
 */
interface DrawAPI{
	public 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:"+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:"+y+"]");
	}
}
abstract class Shape{
	protected DrawAPI drawAPI;
	protected Shape(DrawAPI drawAPI){
		this.drawAPI = drawAPI;
	}
	public abstract void draw();
}
/**
 * Circle類將DrawAPI和Shape類進行了橋接。
 *    Shepe類給出了引數,DrawAPI依據引數進行了實現。
 * 理解:橋接兩邊分別是:抽象和過載
 */
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);
	}
}

//客戶端使用程式碼
/*
	Shape redCircle = new Circle(100,100, 10, new RedCircle());
	Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
	redCircle.draw();
	greenCircle.draw()
*/