单一职责原则

登录模块在实际项目开发中很常见,请按照教材28页(PPT49页)利用单一职责原则重构后的类图实现这一模块。

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
// MainClass is responsible for starting the system.public class MainClass {    

public static void main(String[] args) {        

JFrame frame = new JFrame("Login Form");
        LoginForm loginForm = new LoginForm(frame);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);
        frame.setVisible(true);
    }

}

// LoginForm is responsible for displaying the login form and handling events.

public class LoginForm extends JFrame {    

private UserDAO userDAO;
    public LoginForm(JFrame frame) {        

super("Login Form");
        userDAO = new UserDAO();
        // Add UI components and event handlers here

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setVisible(true);
    }

    // Event handler methods go here}

// UserDAO encapsulates all operations related to the users table.

public class UserDAO {    

private DBUtil dbUtil;
    public UserDAO() {        

dbUtil = new DBUtil();
    }

    public boolean findUser(String userName, String userPassword) throws Exception {        Connection connection = dbUtil.getConnection();

        PreparedStatement statement = connection.prepareStatement(            "SELECT * FROM Users WHERE username = ? AND password = ?");
        statement.setString(1, userName);
        statement.setString(2, userPassword);

        ResultSet resultSet = statement.executeQuery();
        return resultSet.next();
    }

}

// DBUtil provides a connection to the database.

public class DBUtil {    

private final String URL = "jdbc:mysql://localhost:3306/mydatabase";
    private final String USER = "root";
    private final String PASSWORD = "20223959";
    public Connection getConnection() throws Exception {        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

}

posted @   平安喜乐×  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示