小明:嘿,小王,我正在尝试设计一个大学教师管理系统,但我不确定该如何处理权限控制。
小王:哦,这个问题挺常见的。你可以考虑使用代理模式来解决。代理模式允许你提供一个代理对象来控制对另一个对象的访问。
小明:听起来不错。那你能给我举个例子吗?
小王:当然可以。假设我们有一个Teacher类,代表教师。现在,我们需要添加一些额外的功能,比如权限检查。我们可以创建一个TeacherProxy类作为Teacher的代理。
小明:明白了。那我们就从定义Teacher类开始吧。
public class Teacher {
private String name;
private int id;
public Teacher(String name, int id) {
this.name = name;
this.id = id;
}
public void teach() {
System.out.println(name + " is teaching.");
}
}
]]>
小王:很好。接下来,我们来定义TeacherProxy类。
public class TeacherProxy implements Teacher {
private Teacher teacher;
private boolean isAdmin;
public TeacherProxy(Teacher teacher, boolean isAdmin) {
this.teacher = teacher;
this.isAdmin = isAdmin;
}
@Override
public void teach() {
if (isAdmin) {
System.out.println("Admin access granted.");
teacher.teach();
} else {
System.out.println("Access denied.");
}
}
}
]]>
小明:这看起来很清晰。我们现在可以在系统中使用TeacherProxy了。
public static void main(String[] args) {
Teacher t = new Teacher("张老师", 1);
TeacherProxy proxy = new TeacherProxy(t, true);
proxy.teach(); // 输出: Admin access granted. 张老师 is teaching.
TeacherProxy proxy2 = new TeacherProxy(t, false);
proxy2.teach(); // 输出: Access denied.
}
]]>