项目创建并实现基础UI
package org.appimport scala.io.StdInobject Main {def main(args: Array[String]): Unit = {var running = truewhile (running) {println("欢迎来到我的图书管理系统,请选择")println("1.查看所有图书")println("2.查询图书")println("3.登录")println("4.离开")// 获取用户的操作val choice = StdIn.readLine().trimchoice match {case "1" => println("查看所有图书")//TODO 查看所有图书case "2" => println("查询图书")case "3" => println("登录")//TODO 登录之后,应该要展示不同的UIcase "4" =>running = falseprintln("感谢您的使用,下次再见")case _ => println("无效的选择")}}}
}
经典的三层结构
改造代码实现UI层
LibrarayPresentation
package org.app
package uiimport org.app.service.BookServiceimport scala.io.StdInclass LibrarayPresentation {//显示游客的菜单private val BookService=new BookService()def showVisitorMenu(): Unit = {var running = truewhile (running) {println("欢迎来到我的图书管理系统,请选择")println("1.查看所有图书")println("2.查询图书")println("3.登录")println("4.离开")// 获取用户的操作val choice = StdIn.readLine().trimchoice match {case "1" => println("查看所有图书")//TODO 查看所有图书//调用业务逻辑层的方法val results=BookService.searchBook("")if(results.nonEmpty) {results.foreach(println)}else{println("没有找到图书")}case "2" => println("查询图书")case "3" => println("登录")//TODO 登录之后,应该要展示不同的UIcase "4" =>running = falseprintln("感谢您的使用,下次再见")case _ => println("无效的选择")}}}//显示管理员的菜单//显示登录用户的菜单def showMenu(): Unit = {showVisitorMenu()}
}
BookService
package org.app
package serviceimport models.BookModelimport 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
package org.app
package daoimport 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
package org.app
package models//图书类
// id 书名,作者,状态
case class BookModel (id: Int, name: String, author: String, available: Boolean) {}
Main
package org.appimport org.app.ui.LibrarayPresentationimport scala.io.StdInobject Main {def main(args: Array[String]): Unit = {val m = new LibrarayPresentation()m.showMenu()}
}