我正在寻找一种设计模式或方法来整理我的代码。这是在安全和检查给定主题权限的上下文中。 这是一个简化的示例:
public Pizza bakePizza() throws UnauthorizedException{
if (subject.isPermitted("BAKE_PIZZA")){
return new Pizza();
} else {
throw new UnauthorizedException();
}
}
有没有办法让它更干净一点,因为当我有很多不同类型的方法时,这会变得非常困惑。
最佳答案
我认为通过使用类似 decorator pattern 的东西来拆分安全约束和业务逻辑将是一个好的开始。
这样的事情怎么样:
// an interface defines the operations
public interface PizzaService {
Pizza bakePizza();
}
// standard implementation that contains the business logic
public class PizzaServiceImpl implements PizzaService {
@Override
public Pizza bakePizza() {
// implementation ..
}
}
// implementation with security constraints that delegates to the real implementation
public class SecurePizzaService implements PizzaService {
private PizzaService service;
public SecurePizzaService(PizzaService service) {
this.service = service;
}
@Override
public Pizza bakePizza() {
if (!subject.isPermitted("BAKE_PIZZA")){
throw new UnauthorizedException();
}
service.bakePizza()
}
}
// usage
PizzaService pizzaService = new SecurePizzaService(new PizzaServiceImpl());
...
Pizza pizza = pizzaService.bakePizza();
这样您就可以在不触及业务逻辑的情况下更改安全约束,反之亦然。
关于java - 在运行方法时是否有一个好的设计模式来检查权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20443074/