Guest User

Untitled

a guest
May 28th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. //定義所有演算法的共用介面
  2. abstract class HotelPriceStrategy {
  3. //取得總價錢
  4. abstract fun getHotelPrice(price :Int, roomNight: Int) : Int
  5. }
  6.  
  7. //打折策略,建構子傳入折數
  8. class DiscountOffRateStrategy(private val discountRate:Double):HotelPriceStrategy() {
  9.  
  10. //計算售價
  11. override fun getHotelPrice(price :Int, roomNight: Int) : Int {
  12. return (price * roomNight * discountRate).toInt()
  13. }
  14. }
  15.  
  16. //折扣價錢,建構子傳入折扣金額
  17. class DiscountOffDollarStrategy(private val discountDollar:Int):HotelPriceStrategy() {
  18.  
  19. //計算售價
  20. override fun getHotelPrice(price :Int, roomNight: Int) : Int {
  21. return ( price * roomNight ) - discountDollar
  22. }
  23. }
  24.  
  25. fun main(args : Array<String>) {
  26.  
  27. val hotelPrice = 2000
  28. val roomNight = 3
  29.  
  30. //選擇使用打折
  31. val type = DiscountType.DISCOUNT_RATE
  32.  
  33. val price: Int
  34.  
  35. if ( type == DiscountType.DISCOUNT_RATE ) {
  36. //使用打折策略,打9折
  37. val strategy = DiscountOffRateStrategy(0.9)
  38. //計算售價
  39. price = strategy.getHotelPrice(hotelPrice, roomNight)
  40. println("totalPrice:$price") //5400
  41. }else{
  42. //使用折價策略,折200元
  43. val strategy2 = DiscountOffDollarStrategy(200)
  44. //計算售價
  45. price = strategy2.getHotelPrice(hotelPrice, roomNight)
  46. println("totalPrice:$price") //5800
  47. }
  48. }
  49.  
  50. //簡單工廠,依照折扣方式,回傳演算法策略
  51. internal class StrategyFactory{
  52. companion object {
  53. fun createStrategy(type: DiscountType): HotelPriceStrategy {
  54. return when (type) {
  55. //這裡不知道該怎麼傳入不同的參數
  56. DiscountType.DISCOUNT_RATE -> DiscountOffRateStrategy() //這裡要傳入折數
  57. DiscountType.DISCOUNT_DOLLAR -> DiscountOffDollarStrategy() //這裡要傳入折扣金額
  58. }
  59. }
  60. }
  61. }
  62.  
  63. enum class DiscountType {
  64. DISCOUNT_RATE, DISCOUNT_DOLLAR
  65. }
Add Comment
Please, Sign In to add comment