设计模式之Bridge——游戏篇
  
    今天从电子市场买来两张游戏碟,一张是三国游戏(SanGuoGame),一张是CS游戏(CSGame)。玩过游戏的人可能都知道,游戏对计算机系统(ComputerSystem)是有要求的,可能一个游戏在Windows98系统下能玩,到了Windows2000系统下就不能玩了,因此为了不走冤枉路,先看看游戏要求的计算机系统(ComputerSystem)可是一个好习惯呦! 
  
好了,闲话少叙开始我们的游戏旅程吧: 
1、  在这里,先定义计算机系统(ComputerSystem)接口类: 
public interface ComputerSystem { 
  public abstract void  playGame(); //玩游戏 
} 
2、  再定义对计算机系统(ComputerSystem)接口的具体实现类: 
A:Windows98系统 
public class Windows98 implements ComputerSystem{ 
  public void  playGame(){ 
    System.out.println("玩Windows98游戏!"); 
  } 
} 
B:Windows2000系统 
public class Windows2000 implements ComputerSystem{ 
  public void  playGame(){ 
    System.out.println("玩Windows2000游戏!"); 
  } 
} 
3、  定义游戏(Game)类: 
public abstract class  Game  { 
  public abstract void play(); //玩游戏 
  
  protected ComputerSystem getSetupSystem(String type) { //获得要安装的系统 
    if (type.equals("Windows98")) { //如果游戏要求必须安装在Windows98下 
      return new Windows98(); //使用Windows98系统 
    } 
    else if (type.equals("Windows2000")) { //如果游戏要求必须安装在Windows2000下 
      return new Windows2000(); //使用Windows2000系统 
    } 
    else { 
      return new Windows98(); //默认启动的是Windows98系统 
    } 
  } 
} 
4、  定义游戏(Game)类的子类: 
A:三国游戏(SanGuoGame) 
public class SanGuoGame extends Game { 
  private ComputerSystem computerSystem; 
  public SanGuoGame(String type) {//看游戏要求安装在那个系统上 
    computerSystem = getSetupSystem(type);//那么使用这个系统 
  } 
  
  public void play() {//玩游戏 
    computerSystem.playGame(); 
    System.out.println("我正在玩三国,不要烦我!"); 
  } 
} 
B:CS游戏(CSGame) 
public class CSGame extends Game { 
  private ComputerSystem computerSystem; 
  public CSGame(String type) { //看游戏要求安装在那个系统上 
    computerSystem = getSetupSystem(type); //那么使用这个系统 
  } 
  
  public void play() { //玩游戏 
    computerSystem.playGame(); 
    System.out.println("我正在玩CS,不要烦我!"); 
  } 
} 
5、编写测试类: 
public class Test  { 
  public static void main(String[] args) { 
    Game sanguo = new SanGuoGame("Windows98"); //游戏要求Windows98 
    sanguo.play(); 
  
    sanguo = new SanGuoGame("Windows2000");//游戏要求Windows2000 
    sanguo.play(); 
  
    Game cs = new CSGame("Windows98"); //游戏要求Windows98 
    cs.play(); 
  
    cs = new CSGame("Windows2000");//游戏要求Windows2000 
    cs.play(); 
  } 
} 
6、说明: 
A:Bridge定义:将抽象和行为划分开来,各自独立,但能动态的结合。 
B:从本例中我们可以看到,不同的游戏对系统的要求是不同的,三国和CS可能都需要Windows98系统,也可能需要Windows2000系统,甚至要求不相同的系统,因此处理这类问题,我们就可以用Bridge这种模式了。 
   
 
  |