目录
一、实现方式
策略模式
模板模式
二、使用场景
三、优点
四、举例
一、实现方式
策略模式
- 定义策略接口 Strategy
- 创建具体策略类 OperationAdd、OperationSubtract、OperationMultiply
- 创建一个上下文类 Context,包含一个策略对象的引用,并通过该引用调用策略
模板模式
- 定义抽象父类 Game:包含模板方法和一些抽象方法或具体方法
- 实现子类 Cricket、Football:继承抽象父类并实现抽象方法,不改变算法结构
//1、定义策略接口
public interface Strategy {public int doOperation(int num1, int num2);
}//2、创建具体策略类
public class OperationAdd implements Strategy{@Overridepublic int doOperation(int num1, int num2) {return num1 + num2;}
}
public class OperationSubtract implements Strategy{@Overridepublic int doOperation(int num1, int num2) {return num1 - num2;}
}
public class OperationMultiply implements Strategy{@Overridepublic int doOperation(int num1, int num2) {return num1 * num2;}
}//3、创建一个上下文类
public class Context {private Strategy strategy;public Context(Strategy strategy){this.strategy = strategy;}public int executeStrategy(int num1, int num2){return strategy.doOperation(num1, num2);}
}public class StrategyPatternDemo {public static void main(String[] args) {Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5));context = new Context(new OperationSubtract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5));context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5));}
}
//1、定义抽象父类 Game
public abstract class Game {abstract void initialize();abstract void startPlay();abstract void endPlay(); //模板public final void play(){ initialize();//初始化游戏 startPlay();//开始游戏 endPlay();//结束游戏}
}//2、实现子类
public class Cricket extends Game { @Overridevoid endPlay() {System.out.println("Cricket Game Finished!");} @Overridevoid initialize() {System.out.println("Cricket Game Initialized! Start playing.");} @Overridevoid startPlay() {System.out.println("Cricket Game Started. Enjoy the game!");}
}public class Football extends Game {@Overridevoid endPlay() {System.out.println("Football Game Finished!");}@Overridevoid initialize() {System.out.println("Football Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Football Game Started. Enjoy the game!");}
}public class TemplatePatternDemo {public static void main(String[] args) {Game game = new Cricket();game.play();System.out.println();game = new Football();game.play(); }
}
二、使用场景
策:当一个系统中有许多类,它们之间的区别仅在于它们的行为时
模:当存在一些通用的方法,可以在多个子类中共用时
三、优点
策:算法自由切换,避免多重条件判断,扩展性好
模:封装不变部分,扩展可变部分,提取公共代码
四、举例
策:
- 旅行方式的选择:骑自行车、坐汽车.....每种方式都是一个可替换的策略
- Java AWT中的LayoutManager:不同的布局管理器实现了相同的接口,但提供了不同的布局算法
模:
- 建筑流程:地基、走线、水管等步骤相同,但每一步里面具体的实现方法又有不同