在java中设计灵活的Key类

时间:2012-09-02 07:50:52

标签: java design-patterns gwt

我试图在java中设计一个通用的Key类来表示主要的pojo键。

值可以是各种类型,即BigInteger,String,Uuid。我正在寻找实现这样一个类的最佳选择。我目前的实现看起来像这样。

任何人都可以帮助我更准确地实施或确定当前实施的问题吗?我还没有实现一个equals方法。欢迎任何指示。

此类需要与GWT兼容。

@SuppressWarnings("serial")
@GwtCompatible
public class Key<T extends Serializable> implements Serializable {

public enum KeyType {
    BigInt, Uuid, String ;

}

private final T keyValue  ;
private final KeyType keyType  ;

Key() {
    keyValue = null;
    keyType = null;
}

public Key(T value){
    this.keyValue =  value ;
    this.keyType = determineKeyType(value);
}

/**
 * @return
 */
private KeyType determineKeyType(Object value) {

    if ( isValueUuid(value))
        return KeyType.Uuid ;

    else if (value instanceof BigInteger)
        return KeyType.BigInt ;

    else 
        return KeyType.String; 
}

/**
 * @param value
 * @return
 */
private boolean isValueUuid(Object value) {
    // TODO Auto-generated method stub
    return false;
}

public Key(T val, KeyType tp){
    this.keyValue = val ;
    this.keyType = tp;
}

public KeyType getKeyType(){
    return keyType ;
}


@Override
public boolean equals(Object obj) {
    return super.equals(obj);
}

public T getKeyValue(){
    return this.keyValue ;
}
}

2 个答案:

答案 0 :(得分:1)

在我看来,你会从Factory pattern这里受益。

您可以拥有一个界面KeyAbstractKey以及此AbstractKey的所有实现(在您的示例中,它应为3)。 KeyFactory将负责创建密钥。

实际上,它会给出:

public interface Key<T> extends Serializable {
    T getKeyValue();
}

public abstract class AbstractKey<T> implements Key<T> {

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof AbstractKey) {
            return getKeyValue().equals(((AbstractKey) obj).getKeyValue());
        }
        return false;
    }
}

public class StringKey extends AbstractKey<String> {

    private String keyValue;

    StringKey() {
        super();
    }

    protected StringKey(String val) {
        super(val);
        this.keyValue = val;
    }

    @Override
    public String getKeyValue() {
        return keyValue;
    }
}

public class BigIntKey extends AbstractKey<BigInteger> {

    private BigInteger keyValue;

    BigIntKey() {
        super();
    }

    protected BigIntKey(BigInteger val) {
        super(val);
        this.keyValue = val;
    }

    @Override
    public BigInteger getKeyValue() {
        return keyValue;
    }
}

...

public class KeyFactory {
    public static Key<String> getKey(String obj) {
        return new StringKey(obj);
    }

    public static Key<BigInteger> getKey(BigInteger obj) {
        return new BigIntKey(obj);
    }
}

此解决方案的一个优点是,即使它比您已经拥有的解决方案更冗长,您也可以将Key的类型限制为您实际需要的类型。此外,对于可见性有限的构造函数(刚好足以使GWT正确编译),您可以强制执行代码以使用KeyFactory

答案 1 :(得分:0)

除了equals equals Object equals hashCode代表基于身份的{{1}}代表,我们不确定。这是你想要的吗?似乎没有,因为您要检查可能是各种类型的键 此外,如果您覆盖{{1}},则必须覆盖{{1}}

相关问题