请你基于责任链模式写一个简单的功能供我学习与参考。
时间: 2024-05-09 17:17:36 浏览: 14
好的,下面是一个基于责任链模式的简单功能——身份验证:
首先,我们定义一个身份验证器接口:
```java
public interface Authenticator {
boolean authenticate(String username, String password);
}
```
然后,我们实现两个身份验证器:基础身份验证器和高级身份验证器。
基础身份验证器:
```java
public class BasicAuthenticator implements Authenticator {
@Override
public boolean authenticate(String username, String password) {
if (username.equals("admin") && password.equals("123456")) {
System.out.println("基础身份验证通过");
return true;
} else {
System.out.println("基础身份验证未通过");
return false;
}
}
}
```
高级身份验证器:
```java
public class AdvancedAuthenticator implements Authenticator {
private Authenticator next;
public AdvancedAuthenticator(Authenticator next) {
this.next = next;
}
@Override
public boolean authenticate(String username, String password) {
if (username.equals("admin") && password.equals("123456789")) {
System.out.println("高级身份验证通过");
return true;
} else {
System.out.println("高级身份验证未通过,继续下一个身份验证");
if (this.next != null) {
return this.next.authenticate(username, password);
} else {
System.out.println("没有更多的身份验证器");
return false;
}
}
}
}
```
在高级身份验证器中,如果当前身份验证器不能通过验证,它会将验证请求传递给下一个身份验证器,直到所有的身份验证器都无法通过验证或者其中一个身份验证器通过验证为止。
现在,我们可以使用这些身份验证器来进行身份验证了:
```java
public class AuthenticationDemo {
public static void main(String[] args) {
Authenticator authenticator = new BasicAuthenticator();
authenticator = new AdvancedAuthenticator(authenticator);
boolean result = authenticator.authenticate("admin", "123456789"); // 高级身份验证通过
System.out.println("身份验证结果:" + result);
}
}
```
运行结果:
```
高级身份验证通过
身份验证结果:true
```
这就是一个简单的基于责任链模式的身份验证功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)