展开全部
这个问题很简单啊,就是一个接口,N个具体类,然后创建一个抽象工厂根据62616964757a686964616fe4b893e5b19e31333330323937传入的类名生成不同的处理类。首先看看工程结构图:
Common接口:
package pkg1.pkg2;
/**
* Common计算接口
*
* @author
*
*/
public interface Common {
// 接口方法返回结算结果
public long calulate(int a, int b, int c);
}
package pkg1;
import pkg1.pkg2.Common;
/**
* Car007具体实现
*
* @author
*
*/
public class Car007 implements Common {
public long calulate(int a, int b, int c) {
return a * b / c;
}
}
package pkg1;
import pkg1.pkg2.Common;
/**
* Plane具体实现
*
* @author
*
*/
public class Plane implements Common {
public long calulate(int a, int b, int c) {
return a + b + c;
}
}
import pkg1.pkg2.Common;
/**
* 主程序应用方法
*
* @author
*
*/
public class ComputeTime {
/**
* 获得Common对象
*
* @param clazz
* @return
*/
public static Common getCommonObject(String clazz) {
Common common = null;
// 生成接口对象
try {
common = (Common) Class.forName("pkg1." + clazz).newInstance();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return common;
}
/**
* 计算运行distance所需要的时间
*
* @param distance
* 距离
* @param common
* 计算速度的接口对象
* @param a
* @param b
* @param c
* @return
*/
public static double calulate(long distance, Common common, int a, int b, int c) {
if ( common != null ) { return distance / common.calulate(a, b, c); }
return 0;
}
/**
* 主程序方法
*
* @param args
*/
public static void main(String[] args) {
if ( args == null || args.length
System.out.println("参数个数不正确!正确格式:java ComputeTime XX A B C");
return;
}
// 获得a
int a = Integer.parseInt(args[1]);
// 获得b
int b = Integer.parseInt(args[2]);
// 获得c
int c = Integer.parseInt(args[3]);
// 计算1000公里的时间
System.out.println(args[0]+"运行1000公里所需的时间为:"+calulate(1000, getCommonObject(args[0]), a, b, c)+"小时");
}
}
最后程序运行结果:
Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.
E:\>cd E:\workspace\test\bin
E:\workspace\test\bin>java ComputeTime Plane 20 30 40
Plane运行1000公里所需的时间为:11.0小时
E:\workspace\test\bin>java ComputeTime Car007 23 34 45
Car007运行1000公里所需的时间为:58.0小时
E:\workspace\test\bin>