上个周末开始看head first,这本书通俗易懂,非常适合学习设计模式。
感觉看了后而不去用很难深刻的理解设计模式,所以就把其中的例子实现了一下,加深理解。底下为strategy模式的一个小例子。
我就不在此介绍什么是strategy模式了,大家可以而查阅该书,讲解特别精辟。
我的理解是,strategy模式其实就是把具有共同行为的事物的特性抽象出来,然后面向接口编程,而忽略各个事物的细节。
对上例而言,其把各个角色总结抽象为character类,而把所有武器抽象为IweaponBehavior接口,这样我们在实现的时候,只要知道某个character使用某个IweaponBehavior而已,然后在运行时动态的调用他们各自的方法。
感觉看了后而不去用很难深刻的理解设计模式,所以就把其中的例子实现了一下,加深理解。底下为strategy模式的一个小例子。
- package strategyPattern;
- /**
- * strategy Pattern
- * @author Zheng Haitao
- *
- */
- public class Character {
- private IweaponBehavior weaponBehavior;
- public Character(IweaponBehavior weaponBehavior){
- this.weaponBehavior = weaponBehavior;
- }
- public void setWeaponBehavior(IweaponBehavior weaponBehavior){
- this.weaponBehavior = weaponBehavior;
- }
- public void fight(){
- weaponBehavior.useWeapon();
- }
- public static void main(String[] args){
- //use relevant behavior to construct character.
- Character king = new King(new KnifeBehavior());
- Character queen = new Queen(new GunBehavior());
- //call the wrapper method.
- king.fight();
- queen.fight();
- //use set method to change the behavior dynamically.
- king.setWeaponBehavior(new GunBehavior());
- king.fight();
- }
- }
- class King extends Character{
- public King(IweaponBehavior weaponBehavior){
- super(weaponBehavior);
- }
- }
- class Queen extends Character{
- public Queen(IweaponBehavior weaponBehavior){
- super(weaponBehavior);
- }
- }
- //weapon behavior interface.
- interface IweaponBehavior{
- public void useWeapon();
- }
- class KnifeBehavior implements IweaponBehavior{
- @Override
- public void useWeapon() {
- System.out.println("this is knife behavior");
- }
- }
- class GunBehavior implements IweaponBehavior{
- @Override
- public void useWeapon() {
- System.out.println("this is gun behavior");
- }
- }
我的理解是,strategy模式其实就是把具有共同行为的事物的特性抽象出来,然后面向接口编程,而忽略各个事物的细节。
对上例而言,其把各个角色总结抽象为character类,而把所有武器抽象为IweaponBehavior接口,这样我们在实现的时候,只要知道某个character使用某个IweaponBehavior而已,然后在运行时动态的调用他们各自的方法。