2009年10月13日星期二

Bridge 设计模式

将抽象类和具体类分离开,让他们可以单独的机能扩张,并且将它们用桥的方式连接起来,就是Bridge设计模式。
比如有一个关于排序的抽象类Sorter,然后实现2个具体快速排序QuickSorter,冒泡排序BubbleSorter,代码如下:

abstract class Sorter{
public void sort(Object obj[]);
}
public class QuickSorter: Sorter{
public void sort(Object obj[]){
// 用快速排序排列 obj[]
・・・・
}
}

public class BubbleSorter : Sorter{
public void sort(Object obj[]){
// 用冒泡排序排列obj[]
・・・・
}
}

如果我们想扩张Sorter类,添加一个测量排序时间的方法:

abstract class TimerSorter:Sorter{
public void timerSorter(Object obj[]){
long start = System.currentTimeMillis();
sort(obj);
long end = System.currentTimeMillis();
System.out.println("time:"+(end - start));
}

这样,因为timerSorter这个方法在原来的Sorter抽象类中没有,所以要重写QuickSorter,BubbleSorter,实现QuickTimerSorter,BubbleTimerSoter。而原来写好的QuickSorter,和BubbleSorter类变的毫无帮助。
为了避免上面的问题,采用Bridge设计模式,在抽象类Sorter中,将会在具体类中重写的方法(sort),通过代理的方式转递给具体的类,如下:

abstract class Sorter{
private SortImple sortImple;
public Sorter(SortImple sortImple){
this.sortImple = sortImple;
}
public void sort(Object obj[]){
sortImple.sort(obj);
}
}

Abstract SortImple {
Public void sort(Object obj[]);
}
public class QuickSortImple: SortImple{
pubic void sort(Object obj[]){
// 用快速排序排列 obj[]
・・・・
}
}
public class BubbleSortImple: SortImple {
pubic void sort(Object obj[]){
// 用冒泡排序排列obj[]
・・・・
}
}
public class TimerSorter : Sorter{
public TimerSorter(SortImple sortImple){
super(sortImple);
}
public void timerSort(Object obj[]){
long start = System.currentTimeMillis();
sort(obj);
long end = System.currentTimeMillis();
System.out.println("time:"+(end - start));
}
}


像这样,机能定义层(Sorter)和机能实现层(SortImple)可以分别单独扩张,用桥的方式结合起来的方式就是Bridge设计模式。在本例中,抽象类Sorter和SotImple起到了桥的作用。

没有评论:

发表评论