zoukankan      html  css  js  c++  java
  • 每日日报3——软件设计①|单一职责原则(登录)

    登录模块在实际项目开发中很常见,利用单一职责原则重构后的类图实现这一模块。

    一、单一职责原则

    https://baike.baidu.com/item/%E5%8D%95%E4%B8%80%E8%81%8C%E8%B4%A3%E5%8E%9F%E5%88%99/9456515?fr=aladdin

    二、类图

    三、版本

    (一)C++版

    ① 效果:

    ② 代码:

    login.cpp

     1 #include<iostream>
     2 using namespace std;
     3 
     4 class LoginForm
     5 {
     6 public:
     7     void init() {
     8         cout << "初始化成功!" << endl;
     9     }
    10     void display() {
    11         cout << "显示界面成功!" << endl;
    12     }
    13     void validate() {
    14         cout << "方法调用成功!" << endl;
    15     }
    16 };
    17 
    18 class UserDao
    19 {
    20 public:
    21     void findUser(int userName, int userPassword) {
    22         int name = 1;
    23         int password = 1;
    24         if (userName == name && userPassword == password) {
    25             cout << "用户名及密码正确,登录成功!" << endl;
    26         }
    27         else {
    28             cout << "用户名或密码错误,请重新输入!!" << endl;
    29         }
    30     }
    31 };
    32 
    33 class DBUtil
    34 {
    35 public:
    36     void getConnection() {
    37         cout << "连接成功!!!" << endl;
    38     }
    39 };
    40 
    41 int main() {
    42     LoginForm login;
    43     UserDao userdao;
    44     DBUtil db;
    45     db.getConnection();
    46     login.init();
    47     login.display();
    48     int m, n;
    49     cout << "请输入学号:";
    50     cin >> m;
    51     cout << "请输入密码:";
    52     cin >> n;
    53     userdao.findUser(m,n);
    54     login.validate();
    55 
    56 }

    (二)JAVA版

    ① 效果:

     

    ② 目录结构:

    ③ 数据库建表语句:

     1 SET FOREIGN_KEY_CHECKS=0;
     2 
     3 -- ----------------------------
     4 -- Table structure for `login`
     5 -- ----------------------------
     6 DROP TABLE IF EXISTS `login`;
     7 CREATE TABLE `login` (
     8   `id` int(11) NOT NULL AUTO_INCREMENT,
     9   `userName` varchar(255) NOT NULL,
    10   `userPassword` varchar(255) NOT NULL,
    11   PRIMARY KEY (`id`)
    12 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    13 
    14 -- ----------------------------
    15 -- Records of login
    16 -- ----------------------------
    17 INSERT INTO `login` VALUES ('1', 'admin', '123456');

    ④ 代码:

    MainClass.java

    1 package login;
    2 
    3 public class MainClass {//负责启动系统
    4     public static void main(String[] args) {
    5         //在主函数中,实例化Login类的对象,调用初始化界面的方法
    6         LoginForm login = new LoginForm();
    7         login.init();
    8     }
    9 }

    DBUtil.java

     1 package login;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.PreparedStatement;
     6 import java.sql.ResultSet;
     7 import java.sql.SQLException;
     8 
     9 public class DBUtil {
    10     
    11     public static final String url="jdbc:mysql://localhost:3306/login";//URL
    12     public static final String user="root";//用户名
    13     public static final String password="123";//密码
    14     
    15     /**
    16      * 连接数据库
    17      * @return
    18      */
    19     public static Connection getConnection(){
    20         Connection conn=null;
    21         try {
    22             Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动
    23             conn=DriverManager.getConnection(url, user, password);
    24             System.out.println("数据库连接成功!");
    25         }catch(Exception e) {
    26             e.printStackTrace();
    27         }
    28         return conn;
    29     }
    30 
    31     /**
    32      * 关闭数据库
    33      */
    34     public static void close(Connection conn,PreparedStatement pstm) {
    35 
    36         System.out.println("关闭SQL(conn,pstm)");
    37         if(pstm!=null) {
    38             try {
    39                 pstm.close();
    40             }catch(SQLException e) {
    41                 e.printStackTrace();
    42             }
    43         }
    44 
    45         if(conn!=null) {
    46             try {
    47                 conn.close();
    48             }catch(SQLException e) {
    49                 e.printStackTrace();
    50             }
    51         }
    52 
    53     }
    54 
    55     public static void close(Connection conn,PreparedStatement pstm,ResultSet rs) {
    56 
    57         System.out.println("关闭SQL(conn,pstm,rs)");
    58         if(pstm!=null) {
    59             try {
    60                 pstm.close();
    61             }catch(SQLException e) {
    62                 e.printStackTrace();
    63             }
    64         }
    65 
    66         if(conn!=null) {
    67             try {
    68                 conn.close();
    69             }catch(SQLException e) {
    70                 e.printStackTrace();
    71             }
    72         }
    73 
    74         if(rs!=null) {
    75             try {
    76                 rs.close();
    77             }catch(SQLException e) {
    78                 e.printStackTrace();
    79             }
    80         }
    81 
    82     }
    83 
    84 //    public static void main(String[] args) {
    85 //        getConnection();
    86 //    }
    87 }

    LoginForm.java

      1 package login;
      2 
      3 import java.awt.BorderLayout;
      4 import java.awt.Dimension;
      5 import java.awt.FlowLayout;
      6 import java.awt.Font;
      7 import java.awt.event.ActionEvent;
      8 import java.awt.event.ActionListener;
      9 
     10 import javax.swing.JButton;
     11 import javax.swing.JFrame;
     12 import javax.swing.JLabel;
     13 import javax.swing.JPanel;
     14 import javax.swing.JPasswordField;
     15 import javax.swing.JTextField;
     16 
     17 @SuppressWarnings("serial")
     18 public class LoginForm extends JFrame implements ActionListener {// 负责页面显示
     19 
     20     JTextField text_name = new JTextField();
     21     JPasswordField text_password = new JPasswordField();
     22     private boolean login=false;
     23 
     24     public void init() {// 用于初始化按钮、文本框等界面控件
     25         // 在init中实例化JFrame类的对象
     26         JFrame frame = new JFrame();
     27         // 设置窗体对象的属性值
     28         frame.setTitle("登录");// 设置窗体标题
     29         frame.setSize(400, 250);// 设置窗体大小,只对顶层容器生效
     30         frame.setDefaultCloseOperation(3);// 设置窗体关闭操作,3表示关闭窗体退出程序
     31         frame.setLocationRelativeTo(null);// 设置窗体相对于另一组间的居中位置,参数null表示窗体相对于屏幕的中央位置
     32         frame.setResizable(false);// 禁止调整窗体大小
     33         frame.setFont(new Font("宋体", Font.PLAIN, 14));// 设置字体,显示格式正常,大小
     34 
     35         // 实例化FlowLayout流式布局类的对象,指定对齐方式为居中对齐组件之间的间隔为10个像素
     36         FlowLayout fl = new FlowLayout(FlowLayout.CENTER, 10, 10);
     37         // 实例化流式布局类的对象
     38         frame.setLayout(fl);
     39 
     40         // 实例化JLabel标签对象,该对象显示“账号”
     41         JLabel labname = new JLabel("Name:");
     42         labname.setFont(new Font("宋体", Font.PLAIN, 14));
     43         // 将labname标签添加到窗体上
     44         frame.add(labname);
     45 
     46         // 实例化JTextField标签对象化
     47         Dimension dim1 = new Dimension(300, 30);
     48         text_name.setPreferredSize(dim1);// 设置除顶级容器组件以外其他组件的大小
     49         // 将textName标签添加到窗体上
     50         frame.add(text_name);
     51 
     52         // 实例化JLabel标签对象,该对象显示“密码”
     53         JLabel labpass = new JLabel("Password:");
     54         labpass.setFont(new Font("宋体", Font.PLAIN, 14));
     55         // 将labpass添加到窗体上
     56         frame.add(labpass);
     57 
     58         // 设置大小
     59         text_password.setPreferredSize(dim1);
     60         // 添加到窗体
     61         frame.add(text_password);
     62 
     63         // 实例化JButton组件
     64         JButton button1 = new JButton();
     65         // 设置按键的显示内容
     66         Dimension dim2 = new Dimension(100, 30);
     67         button1.setText("登录");
     68         button1.setFont(new Font("宋体", Font.PLAIN, 14));
     69         // 设置按键大小
     70         button1.setSize(dim2);
     71 
     72         button1.addActionListener(new ActionListener() {// 给按钮添加事件接收器
     73             @Override
     74             public void actionPerformed(ActionEvent e) {// 接受到事件后,进行下面的处理
     75                 validate();
     76             }
     77         });
     78 
     79         frame.add(button1);
     80         frame.setVisible(true);// 窗体可见,一定要放在所有组件加入窗体后
     81     }
     82 
     83     public void display() {// 用于向界面容器中增加页面控件并显示窗口
     84         int i = 3;// 3次登录机会
     85         Dimension dim3 = new Dimension(300, 30);
     86 
     87         // 生成新界面
     88         javax.swing.JFrame login2 = new javax.swing.JFrame();
     89         login2.setSize(400, 200);
     90         login2.setDefaultCloseOperation(3);
     91         login2.setLocationRelativeTo(null);
     92         login2.setFont(new Font("宋体", Font.PLAIN, 14)); // 宋体,正常风格,14号字体
     93         // 创建组件
     94         javax.swing.JPanel jp1 = new JPanel();
     95         javax.swing.JPanel jp2 = new JPanel();
     96         
     97         if(login==true) {
     98             JLabel message = new JLabel("登陆成功!");
     99             message.setFont(new Font("宋体", Font.PLAIN, 14)); // 宋体,正常风格,14号字体
    100             message.setPreferredSize(dim3);
    101             jp1.add(message);
    102             login2.add(jp1, BorderLayout.CENTER);
    103 
    104             login2.setResizable(false);
    105             login2.setVisible(true);
    106         }else {
    107             if (i >= 2) {
    108                 JLabel message = new JLabel("账号或密码错误,您今天还有" + (i - 1) + "次机会");
    109                 message.setFont(new Font("宋体", Font.PLAIN, 14)); // 宋体,正常风格,14号字体
    110                 message.setPreferredSize(dim3);
    111                 // 将textName标签添加到窗体上
    112                 jp1.add(message);
    113                 login2.add(jp1, BorderLayout.CENTER);
    114 
    115                 JButton close = new JButton("确定");
    116                 close.setFont(new Font("宋体", Font.PLAIN, 14));
    117                 // 设置按键大小
    118                 close.setSize(dim3);
    119                 jp2.add(close);
    120                 login2.add(jp2, BorderLayout.SOUTH);
    121 
    122                 i--;// 次数减少
    123                 close.addActionListener(new ActionListener() {
    124                     public void actionPerformed(ActionEvent e) {
    125                         login2.dispose();
    126                     }
    127                 });
    128 
    129                 login2.setResizable(false);
    130                 login2.setVisible(true);
    131             }
    132             else if (i == 1) {
    133                 JLabel message = new JLabel("账号已锁定,请明天再试");
    134                 message.setFont(new Font("宋体", Font.PLAIN, 14)); // 宋体,正常风格,14号字体
    135                 message.setPreferredSize(dim3);
    136                 // 将textName标签添加到窗体上
    137                 jp1.add(message);
    138                 login2.add(jp1, BorderLayout.CENTER);
    139 
    140                 JButton close = new JButton("确定");
    141                 close.setFont(new Font("宋体", Font.PLAIN, 14));
    142                 // 设置按键大小
    143                 close.setSize(dim3);
    144                 jp2.add(close);
    145                 login2.add(jp2, BorderLayout.SOUTH);
    146 
    147                 close.addActionListener(new ActionListener() {
    148                     public void actionPerformed(ActionEvent e) {
    149                         login2.dispose();
    150                     }
    151                 });
    152 
    153                 login2.setResizable(false);
    154                 login2.setVisible(true);
    155             }
    156         }
    157         
    158     }
    159 
    160     public void validate() {// 供登录按钮的事件处理方法调用,用于调用与数据库相关的方法完成登录处理,如果登录成功则进入主页面,否则提示错误信息
    161         if (UserDAO.findUser(text_name, text_password)) {
    162             System.out.println("登录成功");
    163             login=true;
    164             display();
    165         } else {
    166             System.out.println("登录失败");
    167             login=false;
    168             display();
    169         }
    170     }
    171 
    172     @Override
    173     public void actionPerformed(ActionEvent e) {
    174         // TODO Auto-generated method stub
    175         
    176     }
    177 
    178 }

    UserDAO.java

      1 package login;
      2 
      3 import java.sql.Connection;
      4 import java.sql.PreparedStatement;
      5 import java.sql.ResultSet;
      6 
      7 public class UserDAO {//负责用户表的增删改查操作,它封装了对用户表的全部操作代码,登录本质上是一个查询用户表的操作
      8     //登录的查询操作
      9     @SuppressWarnings("deprecation")
     10     public static boolean findUser(javax.swing.JTextField userName,
     11             javax.swing.JPasswordField userPassword) {//用于根据用户名和密码查询数据库中是否存在该用户,如果存在则返回true,否则返回false,该方法需要调用getConnection()方法连接数据库,并供validate()方法调用
     12         Connection conn=null;
     13         PreparedStatement pstm=null;
     14         ResultSet rs=null;
     15         try {
     16             conn=DBUtil.getConnection();
     17             String sql="select * from login where userName=? and userPassword=?";
     18             System.out.println(sql);
     19             pstm=conn.prepareStatement(sql);
     20             pstm.setString(1, userName.getText());
     21             pstm.setString(2, userPassword.getText());
     22             rs=pstm.executeQuery();
     23             while(rs.next()) {
     24                 System.out.println("userName:"+rs.getString("userName")+",userPassword:"+rs.getString("userPassword"));
     25                 return true;
     26             }
     27         }catch(Exception e) {
     28             e.printStackTrace();
     29         }finally {
     30             //SQL执行完成后释放相关资源
     31             DBUtil.close(conn,pstm,rs);
     32         }
     33         return false;    
     34     }
     35     //以下功能均暂未开放
     36 //    //增加用户操作
     37 //    public boolean addUser(String userName,String userPassword) {
     38 //        Connection conn=null;
     39 //        PreparedStatement pstm=null;
     40 //        boolean judge=false;
     41 //        try {
     42 //            conn=DBUtil.getConnection();
     43 //            String sql="insert into login(userName,userPassword) values(?,?)";
     44 //            pstm=conn.prepareStatement(sql);
     45 //            pstm.setString(1, userName);
     46 //            pstm.setString(2, userPassword);
     47 //            //执行插入操作
     48 //            int num=pstm.executeUpdate();
     49 //            if(num>0) {
     50 //                System.out.println("插入成功");
     51 //                judge=true;
     52 //            }else {
     53 //                System.out.println("插入失败");
     54 //                judge=false;
     55 //            }
     56 //        }catch(Exception e) {
     57 //            e.printStackTrace();
     58 //        }finally {
     59 //            //SQL执行完成后释放相关资源
     60 //            DBUtil.close(conn,pstm);
     61 //        }
     62 //        return judge;
     63 //    }
     64 //    //删除用户操作
     65 //    public boolean deleteUser(String userName) {
     66 //        Connection conn=null;
     67 //        PreparedStatement pstm=null;
     68 //        ResultSet rs=null;
     69 //        boolean judge=false;
     70 //        try {
     71 //            conn=DBUtil.getConnection();
     72 //            String sql="delete from login where userName=?";
     73 //            pstm=conn.prepareStatement(sql);
     74 //            pstm.setString(1, userName);
     75 //            int num=pstm.executeUpdate();
     76 //            if(num>0) {
     77 //                System.out.println("删除成功");
     78 //                judge=true;
     79 //            }else {
     80 //                System.out.println("删除失败");
     81 //                judge=false;
     82 //            }
     83 //        }catch(Exception e) {
     84 //            e.printStackTrace();
     85 //        }finally {
     86 //            //SQL执行完成后释放相关资源
     87 //            DBUtil.close(conn,pstm,rs);
     88 //        }
     89 //        return judge;
     90 //    }
     91 //    //修改用户操作
     92 //    public boolean alterUser(String userName){
     93 //        Connection conn=null;
     94 //        ResultSet rs=null;
     95 //        PreparedStatement pstm=null;
     96 //        try {
     97 //            conn=DBUtil.getConnection();
     98 //            String sql="select * from login where userName=?";
     99 //            pstm=conn.prepareStatement(sql);
    100 //            pstm.setString(1,userName);
    101 //            rs=pstm.executeQuery();
    102 //            while(rs.next()) {
    103 //                System.out.println("userName:"+rs.getString("name")+",userPassword:"+rs.getString("password"));
    104 //                return true;
    105 //            }
    106 //        }catch(Exception e) {
    107 //            e.printStackTrace();
    108 //        }finally {
    109 //            DBUtil.close(conn,pstm,rs);
    110 //        }
    111 //        return false;
    112 //    }
    113 //    //修改——更新用户操作
    114 //    public boolean updateUser(String userName,String userPassword,String judgeName) {
    115 //        Connection conn=null;
    116 //        PreparedStatement pstm=null;
    117 //        boolean judge=false;
    118 //        try {
    119 //            conn=DBUtil.getConnection();
    120 //            String sql="update login set userName=?,userPassword=? where userName=?";
    121 //            pstm=conn.prepareStatement(sql);
    122 //            pstm.setString(1, userName);
    123 //            pstm.setString(2, userPassword);
    124 //            pstm.setString(3, judgeName);
    125 //            //执行插入操作
    126 //            int num=pstm.executeUpdate();
    127 //            if(num>0) {
    128 //                System.out.println("修改成功");
    129 //                judge=true;
    130 //            }else {
    131 //                System.out.println("修改失败");
    132 //                judge=false;
    133 //            }
    134 //        }catch(Exception e) {
    135 //            e.printStackTrace();
    136 //        }finally {
    137 //            //SQL执行完成后释放相关资源
    138 //            DBUtil.close(conn,pstm);
    139 //        }
    140 //        return judge;
    141 //    }
    142 }
  • 相关阅读:
    如何提取Redis中的大KEY
    VIM标记 mark 详解
    JAVA编写的一个简单的Socket实现的HTTP响应服务器
    onenote 直接发布文章到CSDN
    guava学习笔记--字符串处理
    带打印子结点的自底向上算法
    动态规划算法3
    动态规划算法2
    一个菜鸟学习动态规划算法的过程
    php取得当前时间函数
  • 原文地址:https://www.cnblogs.com/miao-com/p/15362160.html
Copyright © 2011-2022 走看看