鍦ㄩ傞厤鍣ㄦā寮忎腑鎴戜滑鎻愬埌錛孏arin鏂頒氦浜嗕釜濂蟲湅鍙嬶紝浠栨瘡澶╅兘浼氭敹鍒板涓嬪懡浠わ細
1 public interface Command {
2 public void execute();
3 }
鍏朵腑涓閮ㄥ垎鏄仛楗紝涓閮ㄥ垎鏄礂琛f湇錛汫arin蹇呴』浜茶嚜瀹屾垚鍚楋紝涓嶄竴瀹氾細
1 public class CookCommand implements GirlFriendCommand {
2
3 private String mealName = null;
4
5 public CookCommand(String mealName) {
6 super();
7 this.mealName = mealName;
8 }
9
10 private MealSupplier mealSupplier = null;
11
12 public void setMealSupplier(MealSupplier mealSupplier) {
13 this.mealSupplier = mealSupplier;
14 }
15
16 @Override
17 public void execute() {
18 mealSupplier.cook(mealName);
19 }
20
21 }
鐪熸瀹屾垚鍋氶キ鐨勬槸涓涓娊璞$殑MealSupplier.
1 public interface MealSupplier {
2 public void cook(String name);
3 }
瀹冨彲鑳戒唬琛ㄧ殑鏄竴涓キ搴楋細
1 public class Restaurant implements MealSupplier{
2
3 public Restaurant() {
4 super();
5 }
6
7 @Override
8 public void cook(String name) {
9 System.out.println("楗簵鐑уソ浜?/span>"+name);
10 }
11
12 }
鍚屾牱鐨勶紝鐪熸媧楄。鏈嶇殑鏄娊璞$殑CanWash.
1 public class WashCommand implements GirlFriendCommand {
2
3 private CanWash wash = null;
4
5 public void setWash(CanWash wash) {
6 this.wash = wash;
7 }
8
9 @Override
10 public void execute() {
11 if(wash != null){
12 wash.washClothes();
13 }
14 }
15
16 }
瀹冧唬琛ㄧ殑鍙兘鏄礂琛f満錛?br />
1 public interface CanWash {
2 public void washClothes();
3 }
1 public class WashingMachine implements CanWash {
2
3 @Override
4 public void washClothes() {
5 System.out.println("媧楄。鏈烘礂濂戒簡琛f湇");
6 }
7
8 }
Garin瑕佸仛鐨勫氨鏄潗絳夊懡浠わ紝濡備綍鎵ц瀹屽叏涓嶇錛?br /> 1 public class GirlFriendCommandTest {
2
3 /**
4 * @param args
5 */
6 public static void main(String[] args) {
7 BoyFriend bf = new BoyFriend("Garin");
8
9 bf.addCommand(new CookCommand("楸奸鑲変笣"));
10 bf.addCommand(new WashCommand());
11 bf.action();
12 }
13
14 }
鎵ц瀹屽懡浠ゅ悗鏁堟灉濡備笅錛?br />Garin寮濮嬫墽琛屽懡浠?br />楗簵鐑уソ浜嗛奔棣欒倝涓?br />媧楄。鏈烘礂濂戒簡琛f湇
]]>