Strategy -- 策略模式
来源:互联网 发布:vector java 用法 编辑:程序博客网 时间:2024/06/02 23:07
- public interface Strategy {
-
- public void operation();
- }
-
-
-
-
- class BackDoor implements Strategy {
-
- @Override
- public void operation() {
- System.out.println("找乔国老帮忙");
- }
-
- }
-
- class GivenGreenLight implements Strategy {
-
- @Override
- public void operation() {
- System.out.println("求吴国太开个绿灯");
- }
-
- }
-
- class BlockEnemy implements Strategy {
-
- @Override
- public void operation() {
- System.out.println("孙夫人断后");
- }
-
- }
-
-
-
-
-
- class Context implements Strategy{
- private Strategy mStrategy;
-
- public Context(Strategy s){
- mStrategy = s;
- }
-
- @Override
- public void operation() {
- mStrategy.operation();
- }
-
-
- }
public interface Strategy {public void operation();}/** * 三条妙计 */class BackDoor implements Strategy {@Overridepublic void operation() {System.out.println("找乔国老帮忙");}}class GivenGreenLight implements Strategy {@Overridepublic void operation() {System.out.println("求吴国太开个绿灯");}}class BlockEnemy implements Strategy {@Overridepublic void operation() {System.out.println("孙夫人断后");}}/** * 锦囊盛放妙计 */class Context implements Strategy{private Strategy mStrategy;public Context(Strategy s){mStrategy = s;}@Overridepublic void operation() {mStrategy.operation();}}
-
-
-
- System.out.println("***********1.策略模式***********");
-
- Context context = new Context(new BackDoor());
- System.out.println("使用第 1 条妙计:");
- context.operation();
-
- context = new Context(new GivenGreenLight());
- System.out.println("使用第 2 条妙计:");
- context.operation();
-
- context = new Context(new BlockEnemy());
- System.out.println("使用第 3 条妙计:");
- context.operation();
- System.out.println("");