設計模式之Bridge——遊戲篇
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
今天從電子市場買來兩張遊戲碟,一張是三國遊戲(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這種模式了。
C:這裏行爲是指遊戲,抽象是指系統!