考虑我有Algorithm
enum as
public enum Algorithm {
SHA1("sha1"),
HMAC("hmac"),;
Algorithm(final String algorithm) {
this.algorithm = algorithm;
}
private final String algorithm;
public String getAlgorithm() {
return algorithm;
}
}
我有不同的算法
public class Sha1 {
public static String hash(final String text, final byte[] sb) {...}
}
和
public class Hmac {
public static String hash(final String text, final byte[] sb) {...}
}
我想在有人要求举例
时返回他们的实例Algorithm.SHA1.getInstance()
问题
答案 0 :(得分:6)
当方法是静态的时,你不能返回一个实例,而是you can make your enum
implement an interface,并使一个调用静态方法的实例方法为你执行虚拟调度:
public interface EncryptionAlgo {
String hash(final String text, final byte[] sb);
}
public enum Algorithm implements EncryptionAlgo {
SHA1("sha1") {
public String hash(final String text, final byte[] sb) {
return Sha1.hash(text, sb);
}
},
HMAC("hmac") {
public String hash(final String text, final byte[] sb) {
return Hmac.hash(text, sb);
}
};
Algorithm(final String algorithm) {
this.algorithm = algorithm;
}
private final String algorithm;
public String getAlgorithm() {
return algorithm;
}
}
现在,您可以在hash
或SHA1
个实例上致电HMAC
,如下所示:
Algorithm.HMAC.hash(someText, sb);
或传递EncryptionAlgo
个实例,如下所示:
EncryptionAlgo algo = Algorithm.SHA1;