使用Java优化第一条提问代码:学生成绩信息管理系统要求实现通过账号登录系统,要求账号分为两类,教师类和学生类,教师类账号可使用系统全部功能,学生类账号只可使用查询功能
时间: 2024-03-11 21:48:39 浏览: 32
好的,我来为您优化代码。首先,我们可以将账号类型作为一个类,再让教师和学生分别继承这个类,这样就可以更好地体现面向对象的思想。同时,我们可以使用接口和权限控制来实现学生类账号只能使用查询功能。
具体实现如下:
```java
interface Account {
String getUsername();
String getPassword();
boolean hasPermission(String permission);
}
class TeacherAccount implements Account {
private final String username;
private final String password;
public TeacherAccount(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public boolean hasPermission(String permission) {
return true;
}
}
class StudentAccount implements Account {
private final String username;
private final String password;
public StudentAccount(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public boolean hasPermission(String permission) {
return permission.equals("query");
}
}
interface System {
Account login(String username, String password);
}
class StudentSystem implements System {
private final List<Account> accounts = new ArrayList<>();
public StudentSystem() {
accounts.add(new StudentAccount("student", "123456"));
}
@Override
public Account login(String username, String password) {
for (Account account : accounts) {
if (account.getUsername().equals(username) && account.getPassword().equals(password)) {
return account;
}
}
return null;
}
public void queryScore(Account account) {
if (account.hasPermission("query")) {
// 查询学生成绩的代码
} else {
System.out.println("Permission denied.");
}
}
}
class TeacherSystem implements System {
private final List<Account> accounts = new ArrayList<>();
public TeacherSystem() {
accounts.add(new TeacherAccount("teacher", "123456"));
}
@Override
public Account login(String username, String password) {
for (Account account : accounts) {
if (account.getUsername().equals(username) && account.getPassword().equals(password)) {
return account;
}
}
return null;
}
public void queryScore(Account account) {
if (account.hasPermission("query")) {
// 查询学生成绩的代码
} else {
System.out.println("Permission denied.");
}
}
public void addScore(Account account) {
if (account.hasPermission("add")) {
// 添加学生成绩的代码
} else {
System.out.println("Permission denied.");
}
}
}
```
这样,我们就将账号类型和权限控制分别封装成了接口和方法,实现了更好的代码复用和可维护性。同时,学生类账号只能使用查询功能,符合题目要求。
阅读全文