Strategy
(史帝芬, idealist@gcn.net.tw, 2003/11/07)
第一次想到要使用Strategy Pattern,是在寫電腦象棋時,希望能讓電腦擁有不同棋風,使用Strategy確實可以
透過多型的方式,很巧妙的讓電腦展現出不同棋風,Strategy的中文可以譯為"策略",真的還蠻貼切的。
底下就舉個簡單的例子,希望各位能夠明白。需要特別注意的是,因為C++提供Template的功能,所以可以
不用透過多型也能實作這個pattern。

- Java
Chess.java
package tw.idv.idealist.patterns.strategy;
public class Chess {
private Strategy strategy;
private String name;
public Chess(String name, Strategy strategy) {
this.name = name;
this.strategy = strategy;
}
public int nextHand() {
return strategy.nextHand();
}
}
Strategy.java
package tw.idv.idealist.patterns.strategy;
public interface Strategy {
public int nextHand();
}
StrategyA.java
package tw.idv.idealist.patterns.strategy;
public class StrategyA implements Strategy {
public int nextHand() {
System.out.println("Strategy A");
return 1;
}
}
StragegyB.java
package tw.idv.idealist.patterns.strategy;
public class StrategyB implements Strategy {
public int nextHand() {
System.out.println("Strategy B");
return 2;
}
}
StrategyC.java
package tw.idv.idealist.patterns.strategy;
public class StrategyC implements Strategy {
public int nextHand() {
System.out.println("Strategy C");
return 3;
}
}
Main.java
package tw.idv.idealist.patterns.strategy;
import java.util.*;
public class Main {
public static void main(String[] args) {
Chess man = null;
Random rand = new Random();
switch (rand.nextInt(3)) {
case 0:
man = new Chess("Steven", new StrategyA());
break;
case 1:
man = new Chess("Michael", new StrategyB());
break;
case 2:
man = new Chess("Kevin", new StrategyC());
break;
}
man.nextHand();
}
}
- C++
Chess.h
#ifndef __CHESS_H
#define __CHESS_H
#include <stdio.h>
template <class S>
class Chess {
private:
S* ss;
public:
Chess(S* s) { ss = s; };
void nextHand() { ss->nextHand(); };
};
#endif
Strategy.h
#ifndef __STRATEGY_H
#define __STRATEGY_H
#include <stdio.h>
class Strategy {
public:
virtual void nextHand() { printf("super Strategy\n"); };
};
#endif
StrategyA.h
#ifndef __STRATEGY_A_H
#define __STRATEGY_A_H
#include <stdio.h>
#include "Strategy.h"
class StrategyA: public Strategy {
public:
void nextHand() { printf("Strategy A\n"); };
};
#endif
StrategyB.h
#ifndef __STRATEGY_B_H
#define __STRATEGY_B_H
#include "Strategy.h"
#include
class StrategyB: public Strategy {
public:
void nextHand() { printf("Strategy B\n"); };
};
#endif
StrategyC.h
#ifndef __STRATEGY_C_H
#define __STRATEGY_C_H
#include "Strategy.h"
#include
class StrategyC: public Strategy {
public:
void nextHand() { printf("Strategy C\n"); };
};
#endif
MAIN.CPP
#include <time.h>
void main()
{
Strategy* s;
srand( (unsigned)time( NULL ) );
switch (rand() % 3) {
case 0:
s = new StrategyA();
break;
case 1:
s = new StrategyB();
break;
case 2:
s = new StrategyC();
break;
}
Chess man(s);
man.nextHand();
}
說明
上面的範例程式雖然還是有Strategy class,其實這個class可以拿掉,因為已經有template,透過template就可以達到多型了。