MVC模式简单实现
⭐️该文章展示了通过MVC模式实现——书籍添加,展示功能
⭐️纯面向小白,只是简单促进学习理解使用,不是大型项目——只有两个功能,大家拿到可以自己扩展,可以作为项目入门体验一把结构化项目到底是怎么样的——作者技术有限,敬请批评指正,也欢迎提问 ⭐️
⭐️不设计Web,不涉及界面化,只扩展了数据库持久化——要求配置Mysql数据库(如果有时间,后续在出一个纯JavaSE的版本)
目录跳转
一、目录结构分析
全部包在person.test.*中
controller包
- ——Dispatcher责任分发器
- ——xxxController功能控制器
- ——ControllerFactory控制器工厂
- dao包——持久化层
-
- ——DaoController负责数据库交互
- ——MySQLConnection负责数据库连接
modules包
- ——Book图书信息模型
- ——BookStore图书仓库模型(未用到,直接使用数据库保存了)
views包
- ——IOViews单例,负责输出到控制台
main包
- Application主程序
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y5X0oyZz-1641913775874)(C:\Users\86191\AppData\Roaming\Typora\typora-user-images\image-20220111222238986.png)]](https://i-blog.csdnimg.cn/blog_migrate/1a07f5177896de667dba8a4d8ebedbd7.png)
二、流程分析与演示
1.运行Application
2.输出提示,请输入操作
3.输入操作,转发操作,打印提示信息,控制器执行功能
4.持久化数据,控制器调用执行数据库操作
5.再次输入操作…
实际演示如下:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-69JMYEdY-1641913775875)(C:\Users\86191\AppData\Roaming\Typora\typora-user-images\image-20220111224720685.png)]](https://i-blog.csdnimg.cn/blog_migrate/33e17cad63ed2ba62280ecac32bd3849.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ts9z51iD-1641913775875)(C:\Users\86191\AppData\Roaming\Typora\typora-user-images\image-20220111224029437.png)]](https://i-blog.csdnimg.cn/blog_migrate/d00aaffee0ebd2aa1b75ae00d281db33.png)
三、代码实现
Application类
package person.test.main;
import person.test.controller.Dispatcher;
import person.test.modules.Book;
import person.test.modules.BookStore;
import person.test.views.IOViews;
import java.util.Scanner;
public class Application {
//转发器
private Dispatcher dispatcher=new Dispatcher();
//程序持有书库信息(未使用了)
private BookStore bookStore=BookStore.getBookStore();
//初始化,向书库中添加一些书籍
public void init(){
//改为通过数据库添加了
}
//构造函数
public Application() {
init();
}
public void run(){
String str_c="";
while (true){
IOViews.PrintOnScreen("\n请输入操作");
str_c=IOViews.getAline();
//如果输入OUT退出
if("OUT".equals(str_c))
System.exit(0);
else
dispatcher.runController(str_c);
}
}
public static void main(String[] args) {
Application application=new Application();
application.run();
}
}
Book类
- (定义数据模型)
package person.test.modules;
public class Book {
private String name;
private int ISB;
private String briefIntroduction;
public Book(){}
public Book(String name,int ISB,String briefIntroduction){
this.name=name;
this.ISB=ISB;
this.briefIntroduction=briefIntroduction;
}
public String getName() {
return name;
}
public String getBriefIntroduction() {
return briefIntroduction;
}
public int getISB() {
return ISB;
}
public void setName(String name) {
this.name = name;
}
public void setBriefIntroduction(String briefIntroduction) {
this.briefIntroduction = briefIntroduction;
}
public void setISB(int ISB) {
this.ISB = ISB;
}
}
IOView类
- (形式化的视图类)
package person.test.views;
import java.util.Scanner;
public class IOViews {
static private Scanner in=new Scanner(System.in);
static public String getAline(){
return in.nextLine();
}
static public void PrintOnScreen(String str){
System.out.println(str);
}
}
ControllerFactory类
- (通过操作命令查找输出控制器,如果没有该操作,输出提示)
package person.test.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ControllerFactory {
private static final Map<String,MyController> controllers=new HashMap<>();
//初始化添加操作命令-控制器的映射
static {
controllers.put("addBook",new AddBookController());
controllers.put("showBook",new ShowBookController());
}
//输入一个操作命令,输出对应的操作控制器,如果没有抛出异常信息
public MyController getController(String controllerName) throws NullPointerException {
if(controllers.containsKey(controllerName))
return controllers.get(controllerName);
else
throw new NullPointerException("没有这个操作");
}
}
Dispatcher类
- (转发操作)
package person.test.controller;
import person.test.views.IOViews;
public class Dispatcher {
private final ControllerFactory controllerFactory=new ControllerFactory();
public void runController(String controllerName){
try{
//尝试从工厂中获取该控制器
MyController controller = controllerFactory.getController(controllerName);
//执行控制器功能
controller.run();
}catch (NullPointerException e){
IOViews.PrintOnScreen(e.getMessage());
}
}
}
AddBookController类
- (添加书籍操作)
package person.test.controller;
import person.test.controller.dao.DaoController;
import person.test.modules.BookStore;
import person.test.views.IOViews;
import person.test.modules.Book;
public class AddBookController implements MyController{
// private BookStore bookStore=BookStore.getBookStore();
// private String name="addBook";
AddBookController(){}
@Override
public void run(){
Book book;
IOViews.PrintOnScreen("请输入书名");
String name=IOViews.getAline();
IOViews.PrintOnScreen("请输入编号");
String ISBstr=IOViews.getAline();
int ISB=Integer.parseInt(ISBstr);
IOViews.PrintOnScreen("请输入简介");
String briefIntroduction=IOViews.getAline();
book=new Book(name,ISB,briefIntroduction);
IOViews.PrintOnScreen("书名: "+book.getName()+"\nISB: "+book.getISB()+
"\n简介: "+book.getBriefIntroduction());
//通过数据库存入书籍
int res= DaoController.AddBook(book);
if(res==1){
IOViews.PrintOnScreen("添加成功");
}
// bookStore.addBook(book);
}
}
ShowBookController类
- (从数据库获取书籍,展示)
package person.test.controller;
import person.test.controller.dao.DaoController;
import person.test.modules.Book;
import person.test.modules.BookStore;
import person.test.views.IOViews;
import java.util.List;
public class ShowBookController implements MyController{
// BookStore bookStore=BookStore.getBookStore();
@Override
public void run() {
//通过数据库操作获取所有书籍
List<Book> list = DaoController.ShowAllBook();
for (Book book:list){
IOViews.PrintOnScreen("书名:"+book.getName()+"\n书号:"+book.getISB()+"\n简介:"+
book.getBriefIntroduction()+"\n");
}
}
}
Controller接口
- (控制器接口)
package person.test.controller;
public interface MyController {
void run();
}
DaoController类
- (数据库操作类)
package person.test.controller.dao;
import com.mysql.cj.jdbc.Driver;
import person.test.controller.MyController;
import java.sql.*;
public class MySQLConnection {
// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
// static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
// static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/BookStore?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "123";
private Connection conn = null;
private Statement stmt = null;
static MySQLConnection mySQLConnection=null;
private void Init(){
conn = null;
stmt = null;
try {
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
System.out.println("没有找到Driver类");
e.printStackTrace();
}catch (SQLException e){
System.out.println("SQL错误");
e.printStackTrace();
}
}
private MySQLConnection(){
Init();
}
static public ResultSet RunSQL(String sql){
ResultSet res=null;
if(mySQLConnection==null){
mySQLConnection=new MySQLConnection();
}
try {
mySQLConnection.stmt=mySQLConnection.conn.createStatement();
res=mySQLConnection.stmt.executeQuery(sql);
// mySQLConnection.stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return res;
}
static public void RunSQLUpdate(String sql){
if(mySQLConnection==null){
mySQLConnection=new MySQLConnection();
}
try {
mySQLConnection.stmt=mySQLConnection.conn.createStatement();
mySQLConnection.stmt.executeUpdate(sql);
mySQLConnection.stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
MySQLConnection数据库连接类
package person.test.controller.dao;
import com.mysql.cj.jdbc.Driver;
import person.test.controller.MyController;
import java.sql.*;
public class MySQLConnection {
// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
// static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
// static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/BookStore?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "123456";
private Connection conn = null;
private Statement stmt = null;
static MySQLConnection mySQLConnection=null;
private void Init(){
conn = null;
stmt = null;
try {
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
System.out.println("没有找到Driver类");
e.printStackTrace();
}catch (SQLException e){
System.out.println("SQL错误");
e.printStackTrace();
}
}
private MySQLConnection(){
Init();
}
static public ResultSet RunSQL(String sql){
ResultSet res=null;
if(mySQLConnection==null){
mySQLConnection=new MySQLConnection();
}
try {
mySQLConnection.stmt=mySQLConnection.conn.createStatement();
res=mySQLConnection.stmt.executeQuery(sql);
// mySQLConnection.stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return res;
}
static public void RunSQLUpdate(String sql){
if(mySQLConnection==null){
mySQLConnection=new MySQLConnection();
}
try {
mySQLConnection.stmt=mySQLConnection.conn.createStatement();
mySQLConnection.stmt.executeUpdate(sql);
mySQLConnection.stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据库表结构
CREATE TABLE `bookstore` (
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '无名',
`ISB` int NOT NULL,
`brief` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`ISB`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
结尾
作者长期更新,如果觉得本文还算不错的话,请给我一个大大的赞!!!
如果非常赞同这篇文章,请关注我,持续了解更多精彩博文!!!
作者主攻Java Web方向,平时长期更新Java Web基础概念文章,以及算法和数据结构——【一日双题—见微知著】系列。
同时设计模式系列共23种基础设计模式也已经完结——跳转连接
⭐️_设计模式系列文章汇总贴——全23种设计模式(后序再添加高级设计模式,设计原则等相关内容)

本文介绍了一个简单的MVC模式实现案例,主要功能包括书籍的添加与展示。通过纯面向初学者的方式,介绍了如何利用MVC模式进行项目的结构化设计。文中详细讲解了各组件的作用,并提供了完整的代码示例。

被折叠的 条评论
为什么被折叠?



