隐式实现购买火车票

import scala.util.Random

/**
  * Created by MC on 2018/5/17.
  * desc: 卖票系统
  * 普通人窗口、特殊人群窗口
  * 1.特殊人群窗口:小孩、老人、老师、学生
  * 2.普通人群窗口:年轻人
  */
//人群
class SpecialPerson(name:String,age:Int){
  def getName = name
  def getAge = age
}
class Child(name:String,age:Int){
  def getName = name
  def getAge = age
}
class Oldman(name:String,age:Int){
  def getName = name
  def getAge = age
}
class Man(name:String,age:Int){
  def getName = name
  def getAge = age
}
class Student(name:String,age:Int){
  def getName = name
  def getAge = age
}
//类型检查和转换
object ImplicitObj{
  implicit def person2SpecialPerson(obj:Any):SpecialPerson={
    if(obj.getClass==classOf[Child]) {
      val child = obj.asInstanceOf[Child]
      new SpecialPerson(child.getName, child.getAge)
    }else if(obj.getClass==classOf[Student]) {
      val tea = obj.asInstanceOf[Student]
      new SpecialPerson(tea.getName, tea.getAge)
    }else if(obj.getClass==classOf[Oldman]) {
      val om = obj.asInstanceOf[Oldman]
      new SpecialPerson(om.getName, om.getAge)
    }else{
      null
    }
  }
}
//主对象
object Demo04BuyTicket {
  def main(args: Array[String]): Unit = {
    val child = new Child("葫芦娃 ",7)
    val oldman = new Oldman("葫芦娃他爷爷",10)
    val man = new Man("葫芦娃他爸爸",28)

    val s = new SpecialPerson("山神",35)
    import ImplicitObj._
    buyTicket(child)
    buyTicket(man)
    buyTicket(s)

  }
//购票
  def buyTicket(sp:SpecialPerson) ={
//    var ticketNum = Random.nextInt(300)
var ticketNum =Random.nextInt(1000) + Random.nextInt(1000)+Random.nextInt(100)+Random.nextInt(10)
    if(sp!=null){
      println(s"${sp.getName},您的票号是:$ticketNum")
    }else{
      println("年轻人,请到普通窗口买票")
    }
  }
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭