java简单工厂_Java,设计模式,简单工厂。

展开全部

这个问题很简单啊,就是一个接口,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>

076ed68fdd952f0c2ca498f259b635fa.bmp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值