【发布时间】:2017-02-07 09:05:29
【问题描述】:
我有这些课程: 包实用程序;
public final class Constant {
private Constant() {
throw new AssertionError();
}
public static class Product {
public static final String CODE = "Product";
public static final String A = "product_5g2g";
public static final String B = "product_a45h";
public static final String C = "product_a3ag";
//more constants..
}
public static class Employee {
public static final String CODE = "Employee";
public static final String A = "employee_1g3f";
public static final String B = "employee_h52d";
public static final String C = "employee_h5d2";
//more constants..
}
public static class Client {
public static final String CODE = "Client";
public static final String A = "client_h5ad";
public static final String B = "client_1df1";
public static final String C = "client_6g23";
//more constants..
}
}
和:
package util;
import util.Constant.*;
public class Main {
public void run() {
if (isSelected(Product.CODE)) {
if (isSelected(Product.A) || isSelected(Product.B)) {
//do something
}
compute(Product.C);
//more similar instruction that use constants from Product class
}
if (isSelected(Employee.CODE)) {
if (isSelected(Employee.A) || isSelected(Employee.B)) {
//do something
}
compute(Employee.C);
//more similar instruction that use constants from Employee class
}
if (isSelected(Client.CODE)) {
if (isSelected(Client.A) || isSelected(Client.B)) {
//do something
}
compute(Client.C);
//more similar instruction that use constants from Client class
}
}
public boolean isSelected(String s) {
return true;
}
public void compute(String s) {
}
}
如你所见,这段代码
if (isSelected(StaticClass.CODE)) {
if (isSelected(StaticClass.A) || isSelected(StaticClass.B)) {
//do something
}
compute(StaticClass.C);
//more similar instruction that use constants from Product class
}
是重复的,但不能放在单独的方法中,因为java不允许静态类作为参数public void method(StaticClass) {}。
如何重构上面的代码?我的第一个想法是制作扩展基类或实现通用接口的单例。有更好的解决方案吗?
【问题讨论】:
-
你检查枚举了吗?
-
我会推荐 Enums 并考虑 switch-case 和提取方法。
-
@Jorji 您的问题有两个答案。如果您需要进一步说明,请对答案发表评论,或通过单击勾选标记接受其中一个答案为正确答案。投票是免费的。接受答案会给你两分。你有什么可失去的。如果您有任何问题阻止您发表评论或接受答案,请告诉我。
标签: java oop design-patterns polymorphism constants