<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
表弟馬上就要大學畢業,找工作要寫簡歷(Resume),因此他就來問我關於這方面的問題。我告訴他最好寫兩種類型的簡歷,一種是用中文寫的,一種是用英文寫的,如果是國企的話,就投中文簡歷(ChineseResume),如果是外企的話,就投英文簡歷(EnglishResume),嘿嘿,原因在這裏就沒必要多說了吧。
下面讓我們看看這個過程該如何實現呢?
1、我們先定義簡歷(Resume)接口類:
public interface Resume {
public void writeText();
}
2、再定義對簡歷(Resume)接口的具體實現:
A:中文簡歷(ChineseResume)
public class ChineseResume implements Resume{
public void writeText(){
System.out.println("用中文寫簡歷!");
}
}
B:英文簡歷(EnglishResume)
public class EnglishResume implements Resume{
public void writeText(){
System.out.println("用英文寫的簡歷!");
}
}
3、定義投遞策略(Strategy)類:
public class Strategy {
private Resume resume;
public Strategy(Resume resume) { //使用簡歷的策略
this.resume=resume;
}
public void postResume() { //投遞簡歷
System.out.println("投遞");
resume.writeText();
}
}
4、編寫測試類:
public class Test {
public static void main(String args[]) {
//如果是國企
Resume brotherResume = new ChineseResume(); //表弟用中文寫的簡歷
Strategy strategy = new Strategy(brotherResume); //使用用中文寫的簡歷
strategy.postResume(); //給國企投遞該簡歷
//如果是私企
brotherResume = new EnglishResume(); //表弟用英文寫的簡歷
strategy = new Strategy(brotherResume); //使用用英文寫的簡歷
strategy.postResume(); //給私企投遞該簡歷
}
}
5、說明:
A:Strategy模式主要是定義一系列的算法,把這些算法一個個封裝成單獨的類。
B:在本例中,中文簡歷(ChineseResume)和英文簡歷(EnglishResume)就相當於兩種算法,同時我們把它定義成兩個單獨的類。
C:在找工作時,我們可以根據企業類型選擇投遞那種簡歷,Strategy模式和Factory模式的不同之處是:Strategy模式主要是用來選擇不同的算法,而Factory模式的重點是用來創建對象。