GoF定义:定义一系列算法,将每一个都封装起来,让它们可以互相替换。这个模式让算法在客户端之间保持独立性
我们可以在运行时(runtime)动态选择算法的行为
现实世界:在一场足球比赛中,如果A领先B 1:0,那么对于A来说,它们应该防守,而B应该全力进攻
代码世界:假设有两块有空余的内存,我们选择在第二块上面存储数据。那么在存储数据之前我们需要基于实际状况来判断是否能存数据
根据用户选择的不同,来决定Context
对象的具体行为
public class StrategyPatternEx
{
public static void main(String[] args)
{
System.out.println("***Strategy Pattern Demo***");
Scanner in= new Scanner(System.in);//To take input from user
IChoice ic = null;
Context cxt = new Context();
String input1,input2;;
//Looping twice to test two different choices
try
{
for (int i = 1; i <= 2; i++)
{
System.out.println("Enter an integer:");
input1 = in.nextLine();
System.out.println("Enter another integer:");
input2 = in.nextLine();
System.out.println("Enter ur choice(1 or 2)");
System.out.println("Press 1 for Addition, 2 for Concatenation");
String c = in.nextLine();
/*
For Java old versions-use these lines to collect input
from user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String c = br.readLine();
老版本没有Scanner啊
*/
if (c.equals("1"))
{
/*If user input is 1, create object of FirstChoice(Strategy 1)*/
ic = new FirstChoice();
}
else
{
/*If user input is 2, create object of SecondChoice(Strategy 2)*/
ic = new SecondChoice();
}
/*Associate the Strategy with Context*/
cxt.setChoice(ic);
cxt.showChoice(input1, input2);
}
}
finally {
in.close();
}
System.out.println("End of Strategy pattern");
}
}
interface IChoice
{
void myChoice(String s1, String s2);
}
class FirstChoice implements IChoice
{
@Override
public void myChoice(String s1, String s2)
{
System.out.println("You wanted to add the numbers.");
int int1, int2,sum;
int1=Integer.parseInt(s1);
int2=Integer.parseInt(s2);
sum=int1+int2;
System.out.println("The result of the addition is:"+sum);
System.out.println("***End of the strategy***");
}
}
class SecondChoice implements IChoice
{
@Override
public void myChoice(String s1, String s2)
{
System.out.println("You wanted to concatenate the numbers.");
System.out.println("The result of the addition is:"+s1+s2);
System.out.println("***End of the strategy***");
}
}
class Context {
private IChoice choice;
public void setChoice(IChoice choice)
{
this.choice = choice;
}
public void showChoice(String s1, String s2)
{
this.choice.myChoice(s1, s2);
}
}
策略模式的能力体现在哪里?
应用策略模式有哪些挑战?
策略模式重点在于将一个操作对应的所有后台逻辑区分开并且定义一个统一的接口来管理,再另外定义一个处理逻辑的类(Context
)来作为策略选择逻辑的操作对象
原文:https://www.cnblogs.com/mouseGo/p/14053444.html