设计一个用户认证类,使用策略模式实现用户名密码认证、短信验证码认证、第三方登录认证,写出程序源代码和类图
时间: 2024-05-02 12:20:20 浏览: 9
程序源代码:
// 用户认证接口
interface IAuthStrategy {
authenticate(credentials: any): boolean;
}
// 用户名密码认证策略
class UsernamePasswordAuth implements IAuthStrategy {
authenticate(credentials: any): boolean {
// 实现用户名密码认证逻辑
console.log('使用用户名密码认证');
return true;
}
}
// 短信验证码认证策略
class SmsCodeAuth implements IAuthStrategy {
authenticate(credentials: any): boolean {
// 实现短信验证码认证逻辑
console.log('使用短信验证码认证');
return true;
}
}
// 第三方登录认证策略
class ThirdPartyAuth implements IAuthStrategy {
authenticate(credentials: any): boolean {
// 实现第三方登录认证逻辑
console.log('使用第三方登录认证');
return true;
}
}
// 用户认证类
class UserAuth {
private authStrategy: IAuthStrategy;
constructor(authStrategy: IAuthStrategy) {
this.authStrategy = authStrategy;
}
authenticate(credentials: any): boolean {
return this.authStrategy.authenticate(credentials);
}
}
// 使用示例
const userAuth = new UserAuth(new UsernamePasswordAuth());
userAuth.authenticate({ username: 'admin', password: 'admin123' });
const userAuth2 = new UserAuth(new SmsCodeAuth());
userAuth2.authenticate({ phone: '13888888888', code: '123456' });
const userAuth3 = new UserAuth(new ThirdPartyAuth());
userAuth3.authenticate({ provider: 'wechat', openid: 'wx123456' });
类图:
```
+----------------+ +-----------------+
| IAuthStrategy|<-------|UsernamePasswordAuth|
+----------------+ +-----------------+
|authenticate() | |authenticate() |
+----------------+ +-----------------+
+----------------+ +-------------+
| IAuthStrategy|<-------| SmsCodeAuth|
+----------------+ +-------------+
|authenticate() | |authenticate()|
+----------------+ +-------------+
+----------------+ +---------------+
| IAuthStrategy|<-------| ThirdPartyAuth|
+----------------+ +---------------+
|authenticate() | |authenticate() |
+----------------+ +---------------+
+------------+ +---------+
| UserAuth |--------|IAuthStrategy|
+------------+ +---------+
|authenticate()| |authenticate()|
+------------+ +---------+
```
注:类图中未显示的类包括 Object 等基础类。