原:
package com.maom.design.P_2_Single_Responsibility_Principle;
import java.util.Scanner;
/**
* @Title: P_2_Single_Responsibility_Principle
* @Description: 2. 单一职责原则
* @Author maohb
* @Version 1.0
*/
public class P_2_Single_Responsibility_Principle_0 {
public static void main(String[] args) {
// 接受客户端的输入
SaveToDB std = new SaveToDB();
std.shuru();
if (std.validate()) {
std.getConnection();
std.save();
}
}
}
/** 兼容职责太多 */
class SaveToDB {
private String username;
private String upassword;
//获得客户端输入
public void shuru() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名");
username = scanner.nextLine();
System.out.println("请输入密码");
upassword = scanner.nextLine();
}
//进行数据校验
public boolean validate() {
if (username == null || "".equals(username.trim())) {
System.out.println("用户名不能为空");
return false;
}
if (upassword == null || "".equals(upassword.trim())) {
System.out.println("密码不能为空");
return false;
}
return true;
}
//连接数据库
public void getConnection() {
System.out.println("获得数据库连接");
}
//进行数据操作
public void save() {
System.out.println("将" + username + "保存到了数据库");
System.out.println("将" + upassword + "保存到了数据库");
}
}
改:
package com.maom.design.P_2_Single_Responsibility_Principle;
import java.util.Scanner;
/**
* @Title: P_2_Single_Responsibility_Principle
* @Description: 2. 单一职责原则
* @Author maohb
* @Version 1.0
*/
public class P_2_Single_Responsibility_Principle {
public static void main(String[] args) {
Input input = new Input();
// 输入
input.shuru();
// 校验
Validator validator = new Validator();
if (validator.validate(input.getUsername(), input.getUpassword())) {
// 获取连接
DBManager.getConnection();
// 存入数据库
DAOImp dao = new DAOImp();
dao.save(input.getUsername(), input.getUpassword());
}
}
}
/** 输入功能 */
class Input {
private String username;
private String upassword;
// 获得客户端输入
public void shuru() {
Scanner scanner = new Scanner(System.in);
System.out.println(" 请输入用户名 ");
username = scanner.nextLine();
System.out.println(" 请输入密码 ");
upassword = scanner.nextLine();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
}
/** 校验功能 */
class Validator {
// 进行数据校验
public boolean validate(String username, String upassword) {
if(username == null || "".equals(username.trim())) {
System.out.println("用户名不能为空");
return false;
}
if(upassword == null || "".equals(upassword.trim())) {
System.out.println("密码不能为空");
return false;
}
return true;
}
}
/** 连接管理功能 */
class DBManager {
// 连接数据库
public static void getConnection() {
System.out.println("获得数据库连接");
}
}
/** 数据库操作 */
class DAOImp {
// 进行数据操作
public void save(String username,String upassword) {
System.out.println("将 " + username + " 保存到了数据库");
System.out.println("将 " + upassword + " 保存到了数据库");
}
}