package org.kangta.straty;
/**
* 具体策略角色
* @author Administrator
*
*/
public class Add implements Operation {
public void op(double a, double b) {
// TODO Auto-generated method stub
double result = a + b;
System.out.println(result);
}
}
Sub.java
package org.kangta.straty;
/**
* 具体策略角色
* @author Administrator
*
*/
public class Sub implements Operation {
public void op(double a, double b) {
// TODO Auto-generated method stub
double result = a - b;
System.out.println(result);
}
}
Div.java
package org.kangta.straty;
/**
* 具体策略角色
* @author Administrator
*
*/
public class Div implements Operation {
public void op(double a, double b) {
// TODO Auto-generated method stub
if(b != 0)
{
double result = a / b;
System.out.println(result);
}
else
{
System.out.println("除0了!");
}
}
}
Multi.java
package org.kangta.straty;
/**
* 具体策略角色
* @author Administrator
*
*/
public class Multi implements Operation {
public void op(double a, double b) {
// TODO Auto-generated method stub
double result = a * b;
System.out.println(result);
}
}
OK!抽象策略角色和具体策略角色都已经建立成功了,现在来建立环境角色
Calc.java
package org.kangta.straty;
/**
* 环境角色
* @author Administrator
*
*/
public class Calc {
public final static Add add = new Add();
public final static Sub sub = new Sub();
public final static Div div = new Div();
public final static Multi multi = new Multi();
}
都建立好了测试一下
Test.java
package org.kangta.straty.test;
import org.kangta.straty.Calc;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Calc c = new Calc();
c.add.op(11,22);
c.sub.op(22,11);
c.div.op(33, 11);
c.multi.op(33, 33);
}