针对一个系统的权限管理这样的业务场景,使用各设计模式解说

news/2024/12/13 1:08:02/
aidu_pl">

通义灵码

下面将介绍如何在Java中使用不同的设计模式来实现权限管理系统。每个设计模式都有其特定的应用场景和实现方式,我们将逐一讲解。

1. 单例模式 (Singleton Pattern)

应用场景:确保权限管理服务在整个系统中只有一个实例,避免重复创建和资源浪费。

实现方式

java

public class PermissionService { private static PermissionService instance; private Map<String, User> users; private PermissionService() { users = new HashMap<>(); } public static PermissionService getInstance() { if (instance == null) { synchronized (PermissionService.class) { if (instance == null) { instance = new PermissionService(); } } } return instance; } public void addUser(User user) { users.put(user.getId(), user); } public User getUser(String id) { return users.get(id); } // 其他权限管理方法 } class User { private String id; private String role; public User(String id, String role) { this.id = id; this.role = role; } public String getId() { return id; } public String getRole() { return role; } }

2. 工厂方法模式 (Factory Method Pattern)

应用场景:根据不同类型的用户创建不同的权限对象。

实现方式

java

interface Permission { boolean checkAccess(Resource resource); } class AdminPermission implements Permission { @Override public boolean checkAccess(Resource resource) { return true; // 管理员有所有权限 } } class UserPermission implements Permission { @Override public boolean checkAccess(Resource resource) { return resource.isPublic(); // 用户只能访问公开资源 } } abstract class PermissionFactory { abstract Permission createPermission(String type); } class ConcretePermissionFactory extends PermissionFactory { @Override Permission createPermission(String type) { if ("admin".equals(type)) { return new AdminPermission(); } else if ("user".equals(type)) { return new UserPermission(); } return null; } } class Resource { private boolean isPublic; public Resource(boolean isPublic) { this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } }

3. 抽象工厂模式 (Abstract Factory Pattern)

应用场景:创建一系列相关的权限对象,例如不同角色的权限集合。

实现方式

java

interface PermissionFactory { Permission createUserPermission(); Permission createAdminPermission(); } class ConcretePermissionFactory implements PermissionFactory { @Override public Permission createUserPermission() { return new UserPermission(); } @Override public Permission createAdminPermission() { return new AdminPermission(); } } class UserPermission implements Permission { @Override public boolean checkAccess(Resource resource) { return resource.isPublic(); // 用户只能访问公开资源 } } class AdminPermission implements Permission { @Override public boolean checkAccess(Resource resource) { return true; // 管理员有所有权限 } } class Resource { private boolean isPublic; public Resource(boolean isPublic) { this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } }

4. 建造者模式 (Builder Pattern)

应用场景:逐步构建复杂的权限配置,例如多角色、多权限的组合。

实现方式

java

class PermissionBuilder { private List<Permission> permissions; public PermissionBuilder() { permissions = new ArrayList<>(); } public PermissionBuilder addAdminPermission() { permissions.add(new AdminPermission()); return this; } public PermissionBuilder addUserPermission() { permissions.add(new UserPermission()); return this; } public CompositePermission build() { return new CompositePermission(permissions); } } class CompositePermission implements Permission { private List<Permission> permissions; public CompositePermission(List<Permission> permissions) { this.permissions = permissions; } @Override public boolean checkAccess(Resource resource) { for (Permission permission : permissions) { if (permission.checkAccess(resource)) { return true; } } return false; } } class UserPermission implements Permission { @Override public boolean checkAccess(Resource resource) { return resource.isPublic(); // 用户只能访问公开资源 } } class AdminPermission implements Permission { @Override public boolean checkAccess(Resource resource) { return true; // 管理员有所有权限 } } class Resource { private boolean isPublic; public Resource(boolean isPublic) { this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } }

5. 适配器模式 (Adapter Pattern)

应用场景:将现有的权限管理系统适配到新的系统中,例如将旧版的权限管理适配到新版的系统中。

实现方式

java

interface NewPermissionSystem { boolean checkAccess(User user, Resource resource); } class OldPermissionSystem { public boolean checkAccess(User user, Resource resource) { // 旧版权限检查逻辑 return "admin".equals(user.getRole()) || resource.isPublic(); } } class NewPermissionSystemAdapter implements NewPermissionSystem { private OldPermissionSystem oldSystem; public NewPermissionSystemAdapter(OldPermissionSystem oldSystem) { this.oldSystem = oldSystem; } @Override public boolean checkAccess(User user, Resource resource) { return oldSystem.checkAccess(user, resource); } } class User { private String name; private String role; public User(String name, String role) { this.name = name; this.role = role; } public String getName() { return name; } public String getRole() { return role; } } class Resource { private boolean isPublic; public Resource(boolean isPublic) { this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } }

6. 装饰器模式 (Decorator Pattern)

应用场景:在不改变原有权限检查逻辑的情况下,动态添加新的权限检查逻辑,例如日志记录。

实现方式

java

interface PermissionChecker { boolean checkAccess(User user, Resource resource); } class BasePermissionChecker implements PermissionChecker { @Override public boolean checkAccess(User user, Resource resource) { return "admin".equals(user.getRole()) || resource.isPublic(); } } class LoggingPermissionChecker implements PermissionChecker { private PermissionChecker checker; public LoggingPermissionChecker(PermissionChecker checker) { this.checker = checker; } @Override public boolean checkAccess(User user, Resource resource) { boolean result = checker.checkAccess(user, resource); System.out.println("Access check for " + user.getName() + " on " + resource.getName() + ": " + result); return result; } } class User { private String name; private String role; public User(String name, String role) { this.name = name; this.role = role; } public String getName() { return name; } public String getRole() { return role; } } class Resource { private String name; private boolean isPublic; public Resource(String name, boolean isPublic) { this.name = name; this.isPublic = isPublic; } public String getName() { return name; } public boolean isPublic() { return isPublic; } }

7. 观察者模式 (Observer Pattern)

应用场景:当用户的权限发生变化时,通知相关的系统模块进行更新。

实现方式

java

import java.util.ArrayList; import java.util.List; interface Observer { void update(User user); } class Subject { private List<Observer> observers = new ArrayList<>(); public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); } public void notifyObservers(User user) { for (Observer observer : observers) { observer.update(user); } } } class User { private String name; private String role; public User(String name, String role) { this.name = name; this.role = role; } public String getName() { return name; } public String getRole() { return role; } public void changeRole(String newRole) { this.role = newRole; subject.notifyObservers(this); } private Subject subject = new Subject(); public void addObserver(Observer observer) { subject.addObserver(observer); } public void removeObserver(Observer observer) { subject.removeObserver(observer); } } class Logger implements Observer { @Override public void update(User user) { System.out.println(user.getName() + " changed role to " + user.getRole()); } } public class Main { public static void main(String[] args) { User user = new User("Alice", "user"); Logger logger = new Logger(); user.addObserver(logger); user.changeRole("admin"); } }

8. 策略模式 (Strategy Pattern)

应用场景:根据不同类型的资源或操作,选择不同的权限检查策略。

实现方式

java

interface PermissionStrategy { boolean checkAccess(User user, Resource resource); } class AdminStrategy implements PermissionStrategy { @Override public boolean checkAccess(User user, Resource resource) { return "admin".equals(user.getRole()); } } class PublicStrategy implements PermissionStrategy { @Override public boolean checkAccess(User user, Resource resource) { return resource.isPublic(); } } class PermissionContext { private PermissionStrategy strategy; public PermissionContext(PermissionStrategy strategy) { this.strategy = strategy; } public void setStrategy(PermissionStrategy strategy) { this.strategy = strategy; } public boolean checkAccess(User user, Resource resource) { return strategy.checkAccess(user, resource); } } class User { private String name; private String role; public User(String name, String role) { this.name = name; this.role = role; } public String getRole() { return role; } } class Resource { private String name; private boolean isPublic; public Resource(String name, boolean isPublic) { this.name = name; this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } } public class Main { public static void main(String[] args) { PermissionContext context = new PermissionContext(new AdminStrategy()); System.out.println(context.checkAccess(new User("Alice", "admin"), new Resource("Document", false))); // true context.setStrategy(new PublicStrategy()); System.out.println(context.checkAccess(new User("Bob", "user"), new Resource("Document", true))); // true System.out.println(context.checkAccess(new User("Bob", "user"), new Resource("Document", false))); // false } }

9. 责任链模式 (Chain of Responsibility Pattern)

应用场景:通过一系列的权限检查器依次检查权限,直到某个检查器通过或全部失败。

实现方式

java

abstract class PermissionHandler { protected PermissionHandler successor; public void setSuccessor(PermissionHandler successor) { this.successor = successor; } public boolean handle(User user, Resource resource) { if (checkAccess(user, resource)) { return true; } if (successor != null) { return successor.handle(user, resource); } return false; } abstract boolean checkAccess(User user, Resource resource); } class AdminHandler extends PermissionHandler { @Override boolean checkAccess(User user, Resource resource) { return "admin".equals(user.getRole()); } } class PublicHandler extends PermissionHandler { @Override boolean checkAccess(User user, Resource resource) { return resource.isPublic(); } } class User { private String name; private String role; public User(String name, String role) { this.name = name; this.role = role; } public String getRole() { return role; } } class Resource { private String name; private boolean isPublic; public Resource(String name, boolean isPublic) { this.name = name; this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } } public class Main { public static void main(String[] args) { AdminHandler adminHandler = new AdminHandler(); PublicHandler publicHandler = new PublicHandler(); adminHandler.setSuccessor(publicHandler); System.out.println(adminHandler.handle(new User("Alice", "admin"), new Resource("Document", false))); // true System.out.println(adminHandler.handle(new User("Bob", "user"), new Resource("Document", true))); // true System.out.println(adminHandler.handle(new User("Bob", "user"), new Resource("Document", false))); // false } }

10. 状态模式 (State Pattern)

应用场景:根据用户的不同状态(例如登录状态、角色状态)来决定权限检查的逻辑。

实现方式

java

interface State { boolean checkAccess(Resource resource); } class LoggedInState implements State { @Override public boolean checkAccess(Resource resource) { return resource.isPublic(); } } class AdminState implements State { @Override public boolean checkAccess(Resource resource) { return true; } } class User { private String name; private State state; public User(String name, State state) { this.name = name; this.state = state; } public void setState(State state) { this.state = state; } public boolean checkAccess(Resource resource) { return state.checkAccess(resource); } } class Resource { private String name; private boolean isPublic; public Resource(String name, boolean isPublic) { this.name = name; this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } } public class Main { public static void main(String[] args) { User user = new User("Alice", new LoggedInState()); System.out.println(user.checkAccess(new Resource("Document", true))); // true user.setState(new AdminState()); System.out.println(user.checkAccess(new Resource("Document", false))); // true } }

11. 中介者模式 (Mediator Pattern)

应用场景:协调多个权限管理模块之间的交互,例如用户认证、角色分配、权限检查等。

实现方式

java

interface Mediator { boolean authenticate(User user, String password); boolean checkAccess(User user, Resource resource); } class PermissionMediator implements Mediator { private AuthService authService; private RoleService roleService; private PermissionService permissionService; public PermissionMediator(AuthService authService, RoleService roleService, PermissionService permissionService) { this.authService = authService; this.roleService = roleService; this.permissionService = permissionService; } @Override public boolean authenticate(User user, String password) { if (authService.authenticate(user, password)) { roleService.assignRole(user); return true; } return false; } @Override public boolean checkAccess(User user, Resource resource) { String role = roleService.getRole(user); return permissionService.checkAccess(role, resource); } } class AuthService { public boolean authenticate(User user, String password) { // 认证逻辑 return user.getPassword().equals(password); } } class RoleService { public void assignRole(User user) { // 分配角色逻辑 user.setRole("user"); } public String getRole(User user) { return user.getRole(); } } class PermissionService { public boolean checkAccess(String role, Resource resource) { // 权限检查逻辑 return "admin".equals(role) || resource.isPublic(); } } class User { private String name; private String password; private String role; public User(String name, String password) { this.name = name; this.password = password; } public String getPassword() { return password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } } class Resource { private String name; private boolean isPublic; public Resource(String name, boolean isPublic) { this.name = name; this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } } public class Main { public static void main(String[] args) { AuthService authService = new AuthService(); RoleService roleService = new RoleService(); PermissionService permissionService = new PermissionService(); PermissionMediator mediator = new PermissionMediator(authService, roleService, permissionService); User user = new User("Alice", "password"); if (mediator.authenticate(user, "password")) { System.out.println(mediator.checkAccess(user, new Resource("Document", true))); // true } } }

12. 备忘录模式 (Memento Pattern)

应用场景:记录用户权限的状态,以便在需要时恢复到之前的权限状态。

实现方式

java

class User { private String name; private String role; public User(String name, String role) { this.name = name; this.role = role; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Memento createMemento() { return new Memento(role); } public void restoreMemento(Memento memento) { this.role = memento.getRole(); } } class Memento { private String role; public Memento(String role) { this.role = role; } public String getRole() { return role; } } public class Main { public static void main(String[] args) { User user = new User("Alice", "user"); System.out.println(user.getRole()); //

文兴快码

在设计一个系统的权限管理时,可以使用多种设计模式来优化系统结构、增强系统的可扩展性和可维护性。以下是根据提供的背景知识,针对权限管理系统中可能用到的几种设计模式及其解说:

1. 策略模式(Strategy Pattern)

解说: 策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互换。在权限管理中,可以使用策略模式来处理不同类型的权限验证逻辑。例如,对于页面权限、操作权限和数据权限,可以分别设计不同的验证策略,然后在运行时根据具体需求选择合适的策略进行验证。

代码示例(伪代码):

Java

interface PermissionStrategy { boolean validate(User user, Resource resource); } class PagePermissionStrategy implements PermissionStrategy { @Override public boolean validate(User user, Resource resource) { // 页面权限验证逻辑 return user.hasPagePermission(resource); } } class OperationPermissionStrategy implements PermissionStrategy { @Override public boolean validate(User user, Resource resource) { // 操作权限验证逻辑 return user.hasOperationPermission(resource); } } class PermissionChecker { private PermissionStrategy strategy; public void setStrategy(PermissionStrategy strategy) { this.strategy = strategy; } public boolean checkPermission(User user, Resource resource) { return strategy.validate(user, resource); } }

2. 观察者模式(Observer Pattern)

解说: 观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。在权限管理系统中,可以使用观察者模式来监听用户权限的变化,并通知相关的组件进行更新。

代码示例(伪代码):

Java

interface PermissionObserver { void update(User user, PermissionChange change); } class PermissionManager implements PermissionObserver { @Override public void update(User user, PermissionChange change) { // 更新权限逻辑 if (change.getType() == PermissionChangeType.GRANT) { grantPermission(user, change.getPermission()); } else if (change.getType() == PermissionChangeType.REVOKE) { revokePermission(user, change.getPermission()); } } } class PermissionSubject { private List<PermissionObserver> observers = new ArrayList<>(); public void addObserver(PermissionObserver observer) { observers.add(observer); } public void removeObserver(PermissionObserver observer) { observers.remove(observer); } public void notifyObservers(User user, PermissionChange change) { for (PermissionObserver observer : observers) { observer.update(user, change); } } }

3. 工厂模式(Factory Pattern)

解说: 工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在权限管理系统中,可以使用工厂模式来创建不同类型的权限对象,例如页面权限、操作权限和数据权限对象。

代码示例(伪代码):

Java

interface Permission { void validate(User user, Resource resource); } class PagePermission implements Permission { @Override public void validate(User user, Resource resource) { // 页面权限验证逻辑 } } class OperationPermission implements Permission { @Override public void validate(User user, Resource resource) { // 操作权限验证逻辑 } } class PermissionFactory { public static Permission createPermission(PermissionType type) { switch (type) { case PAGE: return new PagePermission(); case OPERATION: return new OperationPermission(); default: throw new IllegalArgumentException("Unsupported permission type"); } } }

4. 代理模式(Proxy Pattern)

解说: 代理模式为其他对象提供一个代理或占位符,以控制对这个对象的访问。在权限管理系统中,可以使用代理模式来代理用户的操作,以便在操作执行前后添加额外的权限验证逻辑。

代码示例(伪代码):

Java

interface UserService { void performOperation(User user, Operation operation); } class RealUserService implements UserService { @Override public void performOperation(User user, Operation operation) { // 执行实际的操作逻辑 } } class PermissionProxyService implements UserService { private RealUserService realService; public PermissionProxyService(RealUserService realService) { this.realService = realService; } @Override public void performOperation(User user, Operation operation) { if (hasPermission(user, operation)) { realService.performOperation(user, operation); } else { throw new PermissionDeniedException("Permission denied"); } } private boolean hasPermission(User user, Operation operation) { // 权限验证逻辑 return true; // 示例代码,实际应实现具体的验证逻辑 } }

5. 装饰者模式(Decorator Pattern)

解说: 装饰者模式允许向一个现有的对象添加新的功能,同时又不改变其结构。在权限管理系统中,可以使用装饰者模式来增强用户对象的功能,例如添加一个权限检查器装饰器来检查用户的权限。

代码示例(伪代码):

Java

interface User { void performAction(); } class RealUser implements User { @Override public void performAction() { // 执行用户操作 } } class PermissionCheckerDecorator implements User { private User user; public PermissionCheckerDecorator(User user) { this.user = user; } @Override public void performAction() { if (hasPermission()) { user.performAction(); } else { throw new PermissionDeniedException("Permission denied"); } } private boolean hasPermission() { // 权限验证逻辑 return true; // 示例代码,实际应实现具体的验证逻辑 } }

通过以上几种设计模式的应用,可以构建出一个灵活、可扩展且易于维护的权限管理系统。这些设计模式不仅有助于优化代码结构,还能提高系统的可重用性和可测试性。


http://www.ppmy.cn/news/1554631.html

相关文章

虚幻引擎开发命名规则

UE的命名规则如下: 模版类以T作为前缀,例如TArray, TMap, TSet。UObject派生类都以U前缀。AActor派生类都以A前缀。SWidget派生类都以S前缀。全局对象使用G开头,如GEngine。抽象接口以I前缀。枚举以E开头。bool变量以b前缀,如bPendingDestruction。其他的大部分以F开头,如…

【ubuntu】ubuntu24.04.1的apt源配置

阿里云镜像格式重新整理 sudo vim /etc/apt/sources.list.d/ubuntu.sources粘贴以下内容 # Ubuntu 24.04 (Noble) 官方源 Types: deb URIs: https://mirrors.aliyun.com/ubuntu/ Suites: noble noble-updates noble-backports noble-securityComponents: main restricted u…

亚马逊、TEMU测评:安全稳定的操作方法,多元化下单方式的优势

在亚马逊、TEMU等跨境电商平台上&#xff0c;产品的销量和评论质量对于潜在买家的购买决策以及产品的销售排名都有着至关重要的影响。以下是对测评重要性、操作方法、风险规避以及更安全稳定的测评方法的详细分析。 测评的重要性 1. 提高页面权重&#xff1a;产品页面的权重由标…

ElK 8 收集 MySQL 慢查询日志并通过 ElastAlert2 告警至飞书

文章目录 1. 说明2. 启个 mysql3. 设置慢查询4. filebeat 设置5. 触发慢查询6. MySQL 告警至飞书 1. 说明 elk 版本&#xff1a;8.15.0 2. 启个 mysql docker-compose.yml 中 mysql&#xff1a; mysql:# restart: alwaysimage: mysql:8.0.27# ports:# - "3306:3306&q…

C# .NET CORE 开发问题汇总

1. error MSB4803: .NET Core 版本的 MSBuild 不支持“ResolveComReference”。请使用 .NET Framework 版本的 MSBuild。 引用了一个COM组件, 使用donet 命令时,提示不支持, 可以先将项目设置为x86以构建, 将COM引用添加到核心项目中&#xff0c;构建它&#xff0c;在obj\x86\…

HDFS完全分布模式安装部署

本次实验请在hadoop01、hadoop02和hadoop03上完成 实验步骤 前提条件&#xff1a;ZooKeeper集群模式已经部署完成。获取安装包&#xff1a;安装包在本地&#xff1a;可通过XFTP等工具进行上传&#xff1b;安装包在网络&#xff1a;虚拟机可以访问互联网&#xff1a;可直接通过…

40分钟学 Go 语言高并发:服务监控与追踪

服务监控与追踪 一、知识要点总览 模块核心内容技术选型难度监控指标请求量、响应时间、错误率、资源使用Prometheus Grafana中链路追踪分布式调用链、性能瓶颈分析Jaeger, OpenTelemetry高日志处理日志收集、分析、存储ELK Stack中告警系统告警规则、通知渠道、告警分级Ale…

【过滤器】.NET开源 ORM 框架 SqlSugar 系列

目录 0、 过滤器介绍 1、表过滤器 &#xff08;推荐&#xff09; 1.1 手动添加过滤器 1.2 禁用、清空、备份和还原 1.3 联表查询设置 1.4 动态添加 2、修改和删除用过滤器 2.1 局部设置 2.2 全局设置 &#xff08;5.1.4.62&#xff09; 3、子查询用过滤器 4、联表过滤…