Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //定義所有演算法的共用介面
- abstract class HotelPriceStrategy {
- //取得總價錢
- abstract fun getHotelPrice(price :Int, roomNight: Int) : Int
- }
- //打折策略,建構子傳入折數
- class DiscountOffRateStrategy(private val discountRate:Double):HotelPriceStrategy() {
- //計算售價
- override fun getHotelPrice(price :Int, roomNight: Int) : Int {
- return (price * roomNight * discountRate).toInt()
- }
- }
- //折扣價錢,建構子傳入折扣金額
- class DiscountOffDollarStrategy(private val discountDollar:Int):HotelPriceStrategy() {
- //計算售價
- override fun getHotelPrice(price :Int, roomNight: Int) : Int {
- return ( price * roomNight ) - discountDollar
- }
- }
- fun main(args : Array<String>) {
- val hotelPrice = 2000
- val roomNight = 3
- //選擇使用打折
- val type = DiscountType.DISCOUNT_RATE
- val price: Int
- if ( type == DiscountType.DISCOUNT_RATE ) {
- //使用打折策略,打9折
- val strategy = DiscountOffRateStrategy(0.9)
- //計算售價
- price = strategy.getHotelPrice(hotelPrice, roomNight)
- println("totalPrice:$price") //5400
- }else{
- //使用折價策略,折200元
- val strategy2 = DiscountOffDollarStrategy(200)
- //計算售價
- price = strategy2.getHotelPrice(hotelPrice, roomNight)
- println("totalPrice:$price") //5800
- }
- }
- //簡單工廠,依照折扣方式,回傳演算法策略
- internal class StrategyFactory{
- companion object {
- fun createStrategy(type: DiscountType): HotelPriceStrategy {
- return when (type) {
- //這裡不知道該怎麼傳入不同的參數
- DiscountType.DISCOUNT_RATE -> DiscountOffRateStrategy() //這裡要傳入折數
- DiscountType.DISCOUNT_DOLLAR -> DiscountOffDollarStrategy() //這裡要傳入折扣金額
- }
- }
- }
- }
- enum class DiscountType {
- DISCOUNT_RATE, DISCOUNT_DOLLAR
- }
Add Comment
Please, Sign In to add comment