设计模式(策略模式)

本文从HeadFirst阅读后记录:


以下文件在同一目录下,采用策略模式:


策略模式:定义算法族,分别封装起来(接口的实现形式),接口之间可以相互调换,接口独立于 使用 接口的类。(针对接口编程,不针对实现编程原则)

character.java:

public abstract class character{
    weaponBehavior weapon_;
	
	public void fight(){
	   weapon_.useWeapon();
	}
	
	public void setWeapon(weaponBehavior w){
	   this.weapon_=w;
	}


}

weaponBehavior.java

public interface weaponBehavior{
    public void useWeapon();

}


knifeBehavior.java
public class knifeBehavior implements weaponBehavior{
    public void useWeapon(){
	   System.out.println("this is a knife");
	}


}


bowAndArrowBehavior.java
public class bowAndArrowBehavior implements weaponBehavior{
    public void useWeapon(){
	   System.out.println("this is a BowAndArrow");
	}

}


axeBehavior.java

public class axeBehavior implements weaponBehavior{
    public void useWeapon(){
	   System.out.println("this is a Axe");
	}
}


swordBehavior.java
public class swordBehavior implements weaponBehavior{
    public void useWeapon(){
	   System.out.println("this is a Sword");
	}

}


queen.java

   public class queen extends character{
	public queen(){
	     weapon_=new knifeBehavior();
	}
};

weapon.java

import java.io.*;

public class weapon {
   public static void main(String[] args){
       queen q=new queen();
	   q.setWeapon(new bowAndArrowBehavior());
	   q.fight();
   }

};


对应的类图:

设计模式(策略模式)_第1张图片


多用组合,少用继承;针对接口编程,不针对实现编程  这个两个原则  可能是 对策略模式最好的 阐述。


你可能感兴趣的:(设计模式)