日期:2014-05-20  浏览次数:20795 次

用接口回调的题目
景区 根据收费制度不同  


儿童 多少钱
学生  多少钱
军人  多少钱
成年人  多少钱

来写一个接口或者面向抽象类的程序

谢谢

------解决方案--------------------
import java.util.HashMap;


public class Test_9 {

/**
 * 人类。只是起到标识作用。
 */
interface Human{ }
/**
 * 儿童
 */
class Children implements Human{
}
/**
 * 学生
 */
static class Student implements Human{
}
/**
 * 军人
 */
class Soldier implements Human{
}
/**
 * 成年人
 */
class Adult implements Human{
}
/**
 * 收费策略
 */
interface Charging{
/**
 * 费用(单位:分)
 * @return 获得当前费用
 */
int getFeeValue();
}
/**
 * 儿童收费策略
 */
static class ChildrenCharging implements Charging{
public int getFeeValue() {
return 2000;
}
}
/**
 * 学生收费策略
 */
static class StudentCharging implements Charging{
public int getFeeValue() {
return 600;
}
}
/**
 * 军人收费策略
 */
static class SoldierCharging implements Charging{
public int getFeeValue() {
return 800;
}
}
/**
 * 成年人收费策略
 */
static class AdultCharging implements Charging{
public int getFeeValue() {
return 1000;
}

/**
 *  收费制度
 */
static class TheChargingSystem{
private HashMap<Class<? extends Human>, Charging> charging = new HashMap<Class<? extends Human>, Charging>();
public Charging getCharging(Human human){
return charging.get(human.getClass());
}
public Charging getCharging(Class<Human> type){
return charging.get(type);
}
public void setCharging(Class<? extends Human> humanType,Charging charging){
this.charging.put(humanType,charging);
}
}
/**
 * 用例
 */
public static void main(String[] args) {
//创建收费制度对象
TheChargingSystem tcs = new TheChargingSystem();
//配置相关的收费制度
tcs.setCharging(Children.class, new ChildrenCharging());
tcs.setCharging(Student.class, new StudentCharging());
tcs.setCharging(Soldier.class, new SoldierCharging());
tcs.setCharging(Adult.class, new AdultCharging());
//使用场景,使用收费制度对象,得到对应的收费值
Student stdu = new Student();
Charging charging = tcs.getCharging(stdu);
System.out.println(charging.getFeeValue());
}

}