定义:一个类只专注于做一件事和仅有一个引起变化的原因。
优点:1、降低类的复杂性
2、提高类的可读性
3、提高代码的可维护性和复用性
4、降低因变更引起的风险
例子:用户管理
user类:实体对象定义
package srp;
public class User {
private String username;
private String userpass;
private int role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return userpass;
}
public User(String username, String userpass, int role) {
super();
this.username = username;
this.userpass = userpass;
this.role = role;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
}
UserDao类:数据访问层(list<User>)数组可以是数据可,文件等。
package srp;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
private List<User> list;
public UserDao() {
super();
list = new ArrayList<User>();
}
public void addUser(User user)
{
list.add(user);
}
public boolean remove(User user)
{
return list.remove(user);
}
public void getAllUser()
{
for(User user:list)
{
System.out.println(user.toString());
}
}
}
UserManager用户管理类:管理用户数据
package srp;
public class UserManager {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDao userDao=new UserDao();
userDao.addUser(new User("1","2",3));
userDao.getAllUser();
}
}
总结:让类的功能尽量单一