项目创建并实现基础UI
Scala
package org.app
import scala.io.StdIn
object Main {
def main(args: Array[String]): Unit = {
var running = true
while (running) {
println("欢迎来到我的图书管理系统,请选择")
println("1.查看所有图书")
println("2.查询图书")
println("3.登录")
println("4.离开")
// 获取用户的操作
val choice = StdIn.readLine().trim
choice match {
case "1" => println("查看所有图书")
//TODO 查看所有图书
case "2" => println("查询图书")
case "3" => println("登录")
//TODO 登录之后,应该要展示不同的UI
case "4" =>
running = false
println("感谢您的使用,下次再见")
case _ => println("无效的选择")
}
}
}
}
经典的三层结构
改造代码实现UI层
LibrarayPresentation
Scala
package org.app
package ui
import org.app.service.BookService
import scala.io.StdIn
class LibrarayPresentation {
//显示游客的菜单
private val BookService=new BookService()
def showVisitorMenu(): Unit = {
var running = true
while (running) {
println("欢迎来到我的图书管理系统,请选择")
println("1.查看所有图书")
println("2.查询图书")
println("3.登录")
println("4.离开")
// 获取用户的操作
val choice = StdIn.readLine().trim
choice match {
case "1" => println("查看所有图书")
//TODO 查看所有图书
//调用业务逻辑层的方法
val results=BookService.searchBook("")
if(results.nonEmpty) {
results.foreach(println)
}else{
println("没有找到图书")
}
case "2" => println("查询图书")
case "3" => println("登录")
//TODO 登录之后,应该要展示不同的UI
case "4" =>
running = false
println("感谢您的使用,下次再见")
case _ => println("无效的选择")
}
}
}
//显示管理员的菜单
//显示登录用户的菜单
def showMenu(): Unit = {
showVisitorMenu()
}
}
BookService
Scala
package org.app
package service
import models.BookModel
import org.app.dao.BookDAO
import scala.collection.mutable.ListBuffer
class BookService {
private val bookDAO = new BookDAO()
//查询所有的图书
// def searchBook(query:String):图书列表List=(book对象)
def searchBook(query:String):ListBuffer[BookModel]={
//从文本文件中读取基本信息,并保存在列表
bookDAO.loadBooks()
}
}
BookDAO
Scala
package org.app
package dao
import models.BookModel
import scala.collection.mutable.ListBuffer
//图书,数据操作层
class BookDAO {
//加载图书,从文件中读入
def loadBooks(): ListBuffer[BookModel] = {
val books = new ListBuffer[BookModel]()
val source=scala.io.Source.fromFile("books.txt")
for (line<-source.getLines()) {
println(line)
val Array(id, name, author, available) = line.split(",")
books += BookModel(id.toInt, name, author, available.toBoolean)
}
//关闭连接
source.close()
books
}
}
BookModel
Scala
package org.app
package models
//图书类
// id 书名,作者,状态
case class BookModel (id: Int, name: String, author: String, available: Boolean) {
}
Main
Scala
package org.app
import org.app.ui.LibrarayPresentation
import scala.io.StdIn
object Main {
def main(args: Array[String]): Unit = {
val m = new LibrarayPresentation()
m.showMenu()
}
}