Strategy策略设计模式

1.策略模式定义

Strategy模式也叫作行为模式;他对一系列算法进行封装,提供接口,使用哪一种算法,它把选择权交给客户端的用户,使用哪种算法让用户决定。


2.策略模式的特点

(1)提供了可以替换继承关系的方法

(2)也避免了使用多重条件转移语句


3.策略模式的缺点

(1)客户端要知道所有的策略类,客户端的用户必须要了解这些算法的区别,从而选择合适自己的算法

(2)策略模式会造成很多的策略类,是项目变得复杂


策略模式的Demo:

1.方法接口:

package strategypattern2;

public interface MethodInterface {
	//方法
	public void method();
}

2.方法的实现部分一:

扫描二维码关注公众号,回复: 2667463 查看本文章
package strategypattern2;

public class WalkMethod implements MethodInterface{	
	@Override
	public void method() {
		// TODO Auto-generated method stub
		System.out.println("走路!!!");
	}
}

3.方法的实现部分二:

package strategypattern2;

public class RunMethod implements MethodInterface{
	@Override
	public void method() {
		// TODO Auto-generated method stub
		System.out.println("跑步....");
	}	
}

4.策略模式调用方法:

package strategypattern2;
/**
*类描述:选择需要的算法
*@author: 张宇
*@date: 日期: 2018年7月30日 时间: 下午7:13:01
*@version 1.0
 */
public class ContextMethod {

	private MethodInterface methodInterface;
	public ContextMethod(MethodInterface methodInterface){
		this.methodInterface=methodInterface;
	}
	public void run(){
		this.methodInterface.method();
	}
}

5.客户端模式的测试类:

package strategypattern2;
/**
*类描述:简单的策略设计模式
*@author: 张宇
*@date: 日期: 2018年7月30日 时间: 下午7:10:04
*@version 1.0
 */
public class Cilent {
    public static void main(String[]args){
    	ContextMethod context=new ContextMethod(new RunMethod());
    	context.run();
    	System.out.println("--------------------------------");
    	ContextMethod context1=new ContextMethod(new WalkMethod());
    	context1.run();
    }
}

运行结果:

跑步....
--------------------------------
走路!!!

策略模式在选择算法的时候用到,比如:打折活动,对于初级会员打折多少,中级会员打折多少,高级会员打折多少用到策略模式。

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/81290896