Java學習筆記12——資料型別思考題
阿新 • • 發佈:2021-11-30
類圖
原始碼
TravelStrategy.java package com.strategy; public abstract class TravelStrategy { public abstract int costTime(int km); } AirPlaneTravelStrategy.java package com.strategy; public class AirPlaneTravelStrategy extends TravelStrategy{ @Override public int costTime(int km) {return km * 1; } } CarTravelStrategy.java package com.strategy; public class CarTravelStrategy extends TravelStrategy{ @Override public int costTime(int km) { return km * 1; } } TravelHappy.java package com.strategy; public class TravelHappy { private TravelStrategy strategy;public TravelHappy(TravelStrategy strategy){ this.strategy = strategy; } public int travelCostTime(int km){ return strategy.costTime(km); } } Client.java package com.strategy; public class Client { public static void main(String args[]){ TravelStrategy strategy; TravelHappy th;//這裡的策略可以使用配置檔案進行讀取 strategy = new AirPlaneTravelStrategy(); th = new TravelHappy(strategy); System.out.println("從北京到上海 1000公里"); int costTime; costTime = th.travelCostTime(1000); System.out.println("-------costTime-------------" + costTime +" 分鐘"); System.out.println("--------------------"); //這裡的策略可以使用配置檔案進行讀取 strategy = new CarTravelStrategy(); th = new TravelHappy(strategy); costTime = th.travelCostTime(1000); System.out.println("-------costTime-------------" + costTime +" 分鐘"); } }