java接口问题
的有关信息介绍如下:楼主你好!
按您的要求已经完成了初步设计,就等你接收了。
我所用的技术的“java 设计模式当中的策略模式”,它的核心点就是封装算法敏伍。你可以通过自己的编写新的交通工具在不修改原代码的情况下按要求对新类进行编码。
注意:一.你要编写的交通工具类必须实现Vehicel这个abstract
如:public class Ship extends Vehicel、、、、
二.因为不同的交通工具算法不同,所以这步我采用的接口对算法进行抽象定义,并在实际行为类实现的时候实现此借口单独编写自己的算法。
如:public class ShipWithComputeTime implements IComputeTime
三.记住我的包名:com.qs.strategy。
四.在最后我用了个简单工程模式用来实列化style参数,把你要填加的类,添加到if判断里面就OK了。
代码欣赏:
package com.qs.strategy;
public abstract class Vehicle {
private IComputeTime computeTime;
public Vehicle(){}
public abstract void prepareCompute();
public void computeTime(){
computeTime.computeTime();
}
public IComputeTime getComputeTime() {
return computeTime;
}
public void setComputeTime(IComputeTime computeTime) {
this.computeTime = computeTime;
}
}
package com.qs.strategy;
public class Car extends Vehicle{
@Override
public void prepareCompute() {
// TODO Auto-generated method stub
System.out.println("交通工具运行1000公里所需的时间:");
System.out.println("==========================");
}
}
package com.qs.strategy;
public class Plane 桥晌或extends Vehicle{
@Override
public void prepareCompute() {
// TODO Auto-generated method stub
System.out.println("交通工具运行谨辩1000公里所需的时间:");
System.out.println("==========================");
}
}
package com.qs.strategy;
public interface IComputeTime {
void computeTime();
}
package com.qs.strategy;
public class PlaneWithComputeTime implements IComputeTime {
private int a;
private int b;
private int c;
public PlaneWithComputeTime(){}
public PlaneWithComputeTime(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public void computeTime() {
// TODO Auto-generated method stub
System.out.println("java ComputeTime Plane " + " " + a + " " + b + " " + c);
System.out.println("compute result is " + (a + b) + c);
}
}
package com.qs.strategy;
public class CarWithComputeTime implements IComputeTime{
private int a;
private int b;
private int c;
public CarWithComputeTime(){}
public CarWithComputeTime(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public void computeTime() {
// TODO Auto-generated method stub
System.out.println("java ComputeTime Car " + " " + a + " " + b + " " + c);
System.out.println("compute result is " + (a * b) / c);
}
}
package com.qs.strategy;
public class SimpleVehicleFactory {
public SimpleVehicleFactory(){
}
public Vehicle instance(String style){
Vehicle vehicle = null;
if(style.toLowerCase().equals("car")){
vehicle = new Car();
}else if(style.toLowerCase().equals("plane")){
vehicle = new Plane();
}
if(vehicle == null)
System.out.println("请与管理员联系你输入的交通工具还未开通!!!");
return vehicle;
}
}
最后是测试类:
package com.qs.strategy;
public class TestVehicle {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleVehicleFactory factory = new SimpleVehicleFactory();
if(factory.instance("CaRs") != null){
Vehicle vehicle = factory.instance("CaRs");
vehicle.prepareCompute();
vehicle.setComputeTime(new CarWithComputeTime(40, 50, 60));
vehicle.computeTime();
}
}
}