- /*學生抽象類*/
- abstract class Student{
- public abstract void doMethod(Method method);
- }
- /*本科生*/
- class Granduate extends Student{
- public Granduate(){}
- public void doMethod(Method method){
- System.out.println("本科生");
- method.method();
- }
- }
- /*碩士生*/
- class Master extends Student{
- public Master(){}
- public void doMethod(Method method){
- System.out.println("碩士生");
- method.method();
- }
- }
- /*發放辦法接口*/
- interface Method{
- public void method();
- }
- /*方法實現1(Method1)*/
- class Method1 implements Method{
- public void method(){
- System.out.println("助學金髮放辦法1");
- }
- }
- /*方法實現2(Method2)*/
- class Method2 implements Method{
- public void method(){
- System.out.println("助學金髮放辦法2");
- }
- }
- /*Test*/
- public class Test{
- public static void main(String[] args){
- Student s=new Master();
- s.doMethod(new Method2());
- /*使用方法2爲碩士生髮助學金*/
- }
- }
個人認爲,Bridge模式的核心就是組合,把描述一個事物的各個維度用組合的方式放在一個基礎的維裏面,這樣就不必生成M*N*L... 這麼多個子類,另外就是需要保證當某一個維度的長度變長的時候不能更改其它類。總結起來就是兩點:
1.把描述一個事物的所有維度放在一個類裏面;
2.在某個或者某些維度的長度增加或者減少或者改變時,不能更改原有的類。
滿足了上面兩個條件,也就實現了Bridge模式。