我有一个将给定字符串映射到另一个字符串的方法,例如如果该方法的输入是"RS256",它将返回"SHA256WithRSA"等等。我的方法如下
public String getAlgorithm(String alg) {
// The internal crypto provider uses different alg names
switch(alg) {
case "RSA256" : return "SHA256withRSA";
case "SHA384" : return "SHA384withRSA";
case "SHA512" : return "SHA512withRSA";
}
throw new Exception("Not supported");
}
有没有其他方法可以做到这一点(我不想使用MAP)。我正在寻找是否有任何设计模式或任何OOP概念来做到这一点。
使用真实映射,我的意思是java.util.Map
保持键值对 ex。Map<Key,Value>
Map<String,String> map= new HashMap<String,String>();
map.add("RSA256","SHA256withRSA");
map.add("SHA384","SHA384withRSA");
map.add("SHA512","SHA512withRSA");
...
public String getAlgorithm(String alg) {
return map.get(alg);
}
您实际上在这里编写了一个外观模式,我认为您正在包装某种库。 开关大小写语句应该没问题。 使用地图会带来开销,所以最好不要使用它。
您可以使用if-else
来检查alg
等于您的条件并返回与此类似的值。但目前的方式与此非常相似。
为什么你不能使用Map
? 这是更好的方法。
Map<String,String> algoMap=new HashMap<>(String,String);
现在你可以把algoMap.put("algoName","Value")
使用 HashMap
HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("RSA256", "SHA256withRSA");
newMap.put("SHA384", "SHA384withRSA");
newMap.put("SHA512", "SHA512withRSA");
String value = (String) newMap.get("RS256");
您也可以使用枚举类型,但无论哪种方式,您都必须使用没有映射的 switch 语句。
enum Algorithm {
RSA256,
SHA384,
SHA512;
public String name(String pValue) throws Exception {
switch(this) {
case RSA256:
return "SHA256withRSA";
case SHA384:
return "SHA384withRSA";
case SHA512:
return "SHA512withRSA";
default:
throw new Exception("Not supported");
}
}
}