将所有字段放在同一个对象中?

时间:2015-04-17 10:55:30

标签: java class

我有以下类层次结构:

public enum Bonus{
    FP,
    PRECOIL,
    //some ohter types
};

public interface Generator{

    public Object generate();

};


public class DateGenerator implements Generator{

   public String queryString;

   public Integer order;

   //GET, SET

   public Date generate(){
       //implementation
   }
};

public class BonusEnumGenerator implements Generator{

   public Date bonusAppliedDate;

   public String description;

   //GET, SET

   public Bonus generate(){
       //implementation
   }
}

所以我需要把那些用于生成对象的参数放到一个通用对象中。

如果我创建了这个课程,它会被认为是好的,比如说GeneratorParams并为所有Generator的实现设置所有参数。在我的特殊情况下,我会:

public class GeneratorParams{

    public String queryString;

    public Integer order;

    public Date bonusAppliedDate;

    public String description;
}

令我讨厌的是,我把同一物体中彼此不相关的参数放在了一起。好吗?

为什么我要将所有参数放入单个对象?

Beucase我想写更多通用代码。在那种情况下,我会:

public interface Generator{

    public Object generate();

    public void applyParams(GeneratorParams params);

};

applyParams方法将针对每种类型的Generator实施。

所以我可以这样写:

Generator g = GeneratorPrototypeFactory.createGenerator(TypeId typeId);
GeneratorParams p;
//Getting params
g.applyParams(p);
Object generated = g.generate();

我如何以更恰当的方式解决这个问题?

1 个答案:

答案 0 :(得分:1)

简单地将GeneratorParams设为抽象类,并将任何常见(在DateBonusEnum生成器中)参数移动到:

public abstract class GeneratorParams {

    public String commonParam;
    //GET, SET
}

然后添加两个子类:

public class DateGeneratorParams extends GeneratorParams {

    public String queryString;
    public Integer order;   
    //    GET, SET
}

public class BonusEnumGeneratorParams implements GeneratorParams {

    public Date bonusAppliedDate;
    public String description;    
    //    GET, SET 
}

现在在applyParamDateGenerator中实施适当的BonusEnumGenerator

public class DateGenerator implements Generator {    
    public String queryString;
    public Integer order;    
    //GET, SET

    public Date generate(){
        //implementation
    }

    @Override
    public void applyParams(GeneratorParams params) throws InvalidParamException {
        if(!(params instanceof DateGeneratorParams))
            throw new InvalidParamException();
        else
        // assign values
    }    
}

public class BonusEnumGenerator implements Generator {

    public Date bonusAppliedDate;
    public String description;    
    //GET, SET

    public Bonus generate() {
        //implementation
    }

    public void applyParams(GeneratorParams params) throws InvalidParamException {
        if(!(params instanceof BonusEnumGeneratorParams))
            throw new InvalidParamException();
        else
            // assign values
    }    
}