码迷,mamicode.com
首页 > 其他好文 > 详细

Bridge Design Pattern (桥模式)

时间:2015-08-03 01:20:10      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

桥模式的核心思想在于:抽象和行为分离。

在JDON里面,板桥里人举的例子是咖啡(抽象)与加奶(行为)的关系。原文(http://www.jdon.com/designpatterns/bridge.htm)

意思比较清晰,比如说,按照排列组合关系,大杯咖啡,小杯咖啡,和是否加奶,能够组成四种组合:大杯加奶,小杯加奶,大杯不加奶,小杯不加奶,如果再加一种行为进去,比如加巧克力,或者加方糖什么的,势必会出现更多的组合。如果为每一种组合创造一种对象,会造成对象过多代码混乱的状况。

还有很多例子阐述类似的问题,比如两类人(抽象)与行为的关系,男人穿衣服,女人穿衣服,男人戴帽子,女人戴帽子,诸多的例子,都是在说明桥模式的应用场景。

巧模式的核心思想正是在这里:将抽象与行为分离开,以排列组合的方式降低类型的个数,也让代码更为清晰,具备更好的维护性。

代码如下:

package dp.birdge;

/*
 * 抽象:笔
 */
public abstract class Pen {

	protected Color color;

	public void draw() {
		color.draw();
	}

}

package dp.birdge;

public class LongPen extends Pen {

	public LongPen(Color color) {
		this.color = color;
	}

	public void draw() {
		System.out.print("Use long pen >> ");
		super.draw();
	}
}



package dp.birdge;

public class ShortPen extends Pen {

	public ShortPen(Color color) {
		this.color = color;
	}

	public void draw() {
		System.out.print("Use short pen >> ");
		super.draw();
	}
}



package dp.birdge;

public abstract class Color {
	protected String color;

	/*
	 * 行为
	 */
	public void draw() {
		System.out.println("Draw " + this.color);
	}
}



package dp.birdge;

public class DrawGreen extends Color {
	public DrawGreen() {
		this.color = "green";
	}
}



package dp.birdge;

public class DrawRed extends Color {
	public DrawRed() {
		this.color = "red";
	}
}



package dp.birdge;

public class Main {
	public static void main(String ares[]) {
		Color green = new DrawGreen();
		Color red = new DrawRed();

		Pen longGreenPen = new LongPen(green);
		Pen longRedPen = new LongPen(red);

		Pen shortGreenPen = new ShortPen(green);
		Pen shortRedPen = new ShortPen(red);

		longGreenPen.draw();
		longRedPen.draw();
		shortGreenPen.draw();
		shortRedPen.draw();
	}
}




运行结果如下:

Use long pen >> Draw green
Use long pen >> Draw red
Use short pen >> Draw green
Use short pen >> Draw red



Bridge Design Pattern (桥模式)

标签:

原文地址:http://my.oschina.net/nox/blog/486767

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!