package Stragery;
public abstract class Operation {
public abstract int oper(int a);
}
各自的算法实现:
package Stragery;
public class OperationImpl extends Operation {
public int oper(int a)
{
System.out.println("使用算法1");
return a;
}
}
class OperationImplB extends Operation {
public int oper(int a)
{
System.out.println("使用算法2");
return a+2;
}
}
class OperationImplC extends Operation {
public int oper(int a)
{
System.out.println("使用算法3");
return a+3;
}
}
策略类:
public class StrageryContext {
Operation oper=null;
public StrageryContext(int no)
{
switch (no)
{
case 1:
OperationImpl os=new OperationImpl();
oper=os;
break;
case 2:
OperationImplB os1=new OperationImplB();
oper=os1;
break;
case 3:
OperationImplC os2=new OperationImplC();
oper=os2;
break;
}
}
public int getResult(int a)
{
return oper.oper(a);
}
}
Client使用类:
public class Client {
public static void main(String args[]){
StrageryContext context;
int a;
System.out.println("演示调用算法1");
context=new StrageryContext(new Integer(1));
a=12;
context.getResult(a);
System.out.println("演示调用算法2");
context=new StrageryContext(new Integer(2));
context.getResult(a);
System.out.println("演示调用算法3");
context=new StrageryContext(new Integer(3));
a=12;
context.getResult(a);
}
}