简体   繁体   中英

How to design class hierarchy?

I'm programming in Java 7 and now I need to create a base class BaseCondition for all concrete Conditions. What do I mean is that I have some types: Date , Integer , and some enum s and I need to store conditions like _ALL_INTEGERS > 100 and < 200 , _ALL_INTEGERS > 100 , _ALL_INTEGERS < 200 and so for Dates (more, less, between). For enum s I'm going to chose only one value now, so If

enum BonusType{
    BIRTHDAY,
    REGISTRATION
}

then the conditions will look like BonusType= BIRTHDAY and BonusType= REGISTRATION .

So what I was trying to write was

public class <T> ConditionBase{
    private T low;
    private T high;
    //GET, SET
}

and used low=high when I would need to create a condition for enum. All conditions would be a derived class as follows:

public class DateCondition extends BaseCondition<Date>{ }
public class BonusTypeCondition extends BaseCondition<BonusType>{ }

Example of a concrete condition:

BaseCondition c = new BonusTypeCondition();
c.setLow(BonusType.BIRTHDAY);
c.setHigh(BonusType.BIRTHDAY);

QUESTION : I'm not sure about if won't get into troubles when I try to extend some functionality (adding more complicated conditions). Couldn't you suggest something more scalable?

Well, your concept is very close to storing a Java 8 Lambda/closure on each case. If you can't switch versions, you have to abstract the fact that low or 'high` might not be reasonable for Enums. So your true base for condition should be like this:

public interface ConditionBase<T>
{
   boolean fulfills(T object);  // True if this object fullfills the condition.
}

That is the only general case. You can then create some implementations for classes with upper bounds.

public class<T extends Comparable> LessThanX() implements ConditionBase<T>
{
   ...
   private T value;

   ...
   public boolean fullfills(T object)
   {
      return object.compareTo(value) < 0;
   }
}

Forgive me if there are any syntax errors there, my Java is rusty since I moved to Scala.

You can define as many type of conditions as you want, with one or more internal values (between for isntance). You can also create some wrappers that contain several conditions inside them and check the object against all of them, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM