使这段代码更面向对象的最好方法是什么?



我是Java和面向对象设计概念的新手。我有一段代码,我知道可以改进,但我不确定最好的方法。

我有一个数据流(授权值)进来,我试图将其转换为授权ID映射到值的有效性。为了测试有效性,我需要检查授权值的类型,并将其发送到远程客户端以确保它有效。

我正在这里创建授权有效性映射:

private Map<UUID, Boolean> getAuthorizationValidityMap(UUID accountId) {
final Map<UUID, Boolean> authValidity = findCredentialsByAccountId(accountId)
.parallelStream()
.map((auth -> Pair.of(auth.getId(), isAuthValid(auth))))
.collect(Collectors.toMap(res -> res.getLeft(), res -> res.getRight()));
return authValidity;
}

查找授权值是否有效的函数。有多种授权值类型,每种授权值需要以不同的方式检查有效性。我实现它的方式感觉很笨拙,因为随着添加更多的验证类型,它只会导致更多的else if语句。

private Boolean isAuthValid(AuthorizationValue authValue) {
if (authValue.getType().equals(AUTH_TYPE_A)) {
return isAuthTypeAValid(authValue);
} else if (authValue.getType().equals(AUTH_TYPE_B)) {
return isAuthTypeBValid(authValue);
} else if (authValue.getType().equals(AUTH_TYPE_C)) {
return isAuthTypeCValid(authValue);
} 
return false;
}

在运行时,您可以决定应该使用哪个Authorize对象来检查您的凭据。这可以通过战略模式来实现。授权策略将存储在集合中,您可以获得的实例使用工厂模式授权。

我们来看一个实现的例子。我将通过c#展示一个例子,但是我已经注释了什么数据结构可以在Java中使用。这是Auth的属性类型:

public enum AuthType
{ 
A, B, C, D
} 

然后你可以创建抽象类Authorization,它将定义所有派生类的行为。这些派生类将验证值:

public abstract class Authorization 
{
public abstract bool IsValid(string value);
}
public class Authorization_A : Authorization
{
public override bool IsValid(string value)
{
// null check should be implemented
return true;
}  
}
public class Authorization_B : Authorization
{
public override bool IsValid(string value)
{
// null check should be implemented
return true;
}
}

我们需要一个工厂,它将返回AuthType授权的实例:

public class AuthorizationFactory 
{
// HashTable in Java
private Dictionary<AuthType, Authorization> _authByType
= new Dictionary<AuthType, Authorization>()
{
{ AuthType.A, new Authorization_A() },
{ AuthType.B, new Authorization_B() }
};
public Authorization GetInstance(AuthType authType)
{ 
return _authByType[authType];
}
}

这是一个获取认证类型的模拟方法:

AuthType GetAuthType() 
{
// your logic here of getting AuthType
return AuthType.A;
}

和一个使用factory:

的方法
bool IsAuthValid(AuthType authType) 
{
AuthorizationFactory authorizationFactory = new AuthorizationFactory();
Authorization authorization = authorizationFactory.GetInstance(authType);
return authorization.IsValid("some value");
}

你可以这样命名它:

AuthType authType = GetAuthType();
bool isAuthValid = IsAuthValid(authType);

所以我们得到授权实例来检查基于AuthType属性。模式名称为Strategy。

所以我们的代码遵循SOLID原则的开闭原则。当您想要添加新的授权策略时,您将需要一个新的FooAuthorization类。

最新更新