最近在看相關的書籍,為了方便複習寫了這篇

目的:

將不同演算法(策略)處理包裝成一個類別

鐵人三項競賽

鐵人三項分別為:跑步,游泳, 騎車這三項

那對參加者來說只是不同的前進方式,他們的目標都為“終點”

所以我們把參賽者這class的動作行為讓外面傳入,當遇到不同的競賽項目時,在設定不同行為(策略)

Class 類別

運動員

Athlete

抽象動作 

Competition

動作 

RideCompetition,  RunCompetition,  SwimCompetition

 

程式碼

Competition

public abstract class Competition {
	
	public abstract void action();

}

RideCompetition

public class RideCompetition extends Competition{

	@Override
	public void action() {
		// TODO Auto-generated method stub
		System.out.println("riding a bike");
	}
}

RunCompetition

public class RunCompetition extends Competition{

	@Override
	public void action() {
		// TODO Auto-generated method stub
		System.out.println("Run Run Run");
	}
}

SwimCompetition

public class SwimCompetition extends Competition{

	@Override
	public void action() {
		// TODO Auto-generated method stub
		System.out.println("Swimming GO GO GO");
	}
}

Athlete

public class Athlete {
	
	private Competition mCompetition; 
	
	public void action(){
		if(mCompetition == null)
			mCompetition = new RunCompetition();
		
		mCompetition.action();
	}
	
	
	public void setCompetition(Competition competition){
		mCompetition = competition;
	}
}

 

Main 主程式

public class main {

	public static void main(String[] args) {
		
		//準備運動員
		Athlete athlete = new Athlete();
		//跑步比賽
		athlete.setCompetition(new RunCompetition());
		athlete.action();
		
		//騎車比賽
		athlete.setCompetition(new RideCompetition());
		athlete.action();
		
		//游泳比賽
		athlete.setCompetition(new SwimCompetition());
		athlete.action();
	}
}

 

其結果

 

這樣一來對Athlete來說,只需要執行動作action就好了

參加比賽項目的相關行為,再由外面傳進來.

 

範例

專案連結 這裡 

下載連結:https://jc7003@bitbucket.org/jc7003/strategy.git

參考連結

[Design Pattern] 策略模式 (Strategy Pattern) 把跑車行為裝箱吧

策略模式 Strategy Pattern

 

文章標籤
全站熱搜
創作者介紹
創作者 Owen Chen 的頭像
Owen Chen

歐文的BLOG

Owen Chen 發表在 痞客邦 留言(0) 人氣(6)