设计模式之 策略模式
策略模式为同一个行为定义了不同的策略,并为每种策略都实现了不同的方法。在用户使用时,系统根据不同的策略自动切换不同的方法来实现策略的改变。同一个策略下的不同方法是对同一功能的不同实现,因此在使用时可以相互替换而不影响用户的使用。
(1)定义策略模式接口
public interface TravelStrategy{ void travelMode(); }
(2)定义策略实现
public class TravelByAirStrategy implements TravelStrategy{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void travelMode(){ logger.info("travel by air"); } } public class TravelByCarStrategy implements TravelStrategy{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void travelMode(){ logger.info("travel by car"); } }
(3)定义上下文实现策略模式
public class Context{ private TravelStrategy travelStrategy; public TravelStrategy getTravelStrategy(){ return travelStrategy; } public void setTravelStrategy(TravelStrategy travelStrategy){ this.travelStrategy = travelStrategy; } public void travelMode(){ this.travelStrategy.travelMode(); } }
(4)使用策略模式
public static void main(String[] args){ Context context = new Context(); // travel by air TravelStrategy travelByAir = new TravelByAirStrategy(); context.setTravelStrategy(travelByAir); context.travelMode(); // travel by car TravelStrategy travelByCar = new TravelByCarStrategy(); context.setTravelStrategy(travelByCar); context.travelMode(); }