Created
July 14, 2014 06:24
-
-
Save kencoba/1294f7c3030a10346101 to your computer and use it in GitHub Desktop.
Third ieration : Stalls can have different charging algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package iteration.third | |
import java.util.Date | |
object Scenario3 { | |
def main(args: Array[String]) = { | |
def payMethodNormal(t: Ticket) = (t.outTime.getTime - t.inTime.getTime).toInt | |
def payMethodDouble(t: Ticket) = (t.outTime.getTime - t.inTime.getTime).toInt * 2 | |
val pa0 = new ParkingArea( | |
List( | |
new Stall(0, true, payMethodNormal), | |
new Stall(0, true, payMethodDouble))) | |
val (pa1, t1) = pa0.checkin(0) | |
println(s"t1 = ${t1}") | |
val (pa2, t2) = pa1.checkin(0) | |
println(s"t2 = ${t2}") | |
val (pa3, t3) = pa2.checkout(0, t1) | |
println(s"t3 = ${t3}") | |
println(s"amount = ${pa3.amount}") | |
val (pa4, t4) = pa3.checkin(1) | |
println(s"t4 = ${t4}") | |
val (pa5, t5) = pa4.checkout(1, t4) | |
println(s"t5 = ${t5}") | |
println(s"amount = ${pa5.amount}") | |
} | |
} | |
class Stall(val amount: Int, val isFree: Boolean, val payMethod: (Ticket) => Int) { | |
override def toString = s"amount=${amount} isFree=${isFree}" | |
} | |
class Ticket(val area: Stall, val inTime: Date, val outTime: Date) { | |
override def toString = { s"area = ${area} inTime=${inTime}, outTime=${outTime}" } | |
} | |
class ParkingArea(stalls: List[Stall]) { | |
def amount = stalls.map { s => s.amount }.sum | |
def checkin(no: Int): (ParkingArea, Ticket) = { | |
stalls(no).isFree match { | |
case true => { | |
val newStall = new Stall(stalls(no).amount, false, stalls(no).payMethod) | |
(new ParkingArea(stalls.updated(no, newStall)), new Ticket(newStall, new Date, null)) | |
} | |
case _ => (this, null) | |
} | |
} | |
def checkout(no: Int, t: Ticket): (ParkingArea, Ticket) = { | |
stalls(no) match { | |
case s if t.area == s && !s.isFree => { | |
val dummy = new Ticket(s, t.inTime, new Date) | |
val newAmount = s.amount + s.payMethod(dummy) | |
val newStall = new Stall(newAmount, true, s.payMethod) | |
val newTicket = new Ticket(newStall, dummy.inTime, dummy.outTime) | |
(new ParkingArea(stalls.updated(no, newStall)), newTicket) | |
} | |
case _ => (this, t) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment