jeudi 17 mars 2016

Design. A class containing a field which may or may not have multiple (different) fields

Sorry for the unclear title. Couldn't come up with a short description.

Imagine I have a class that has a field that represents some kind of tag. e.g.

public class Foo() {

    //other parameters.
    private Tag tag;

    //Bunch of methods.
}

public abstract class Tag() {

    //implementation
}

public class ATag() extends Tag {

    private String string;
    private int value;

    //...
}

public class BTag() extends Tag {

    private Foo object;

    //...
}

public class CTag() extends Tag {

   //no fields here
   //...
}

Here, three kinds of Tags are represented; ATag, BTag en CTag. There could be more kinds of Tags in the future. Each type of Tag may or may not have one or more field.

When I have an instance of Foo, I want to get a (the) field(s) that belong to its Tag. For example, when my foo instance's tag field contains an instance of BTag which again has an (other) instance of Foo, I want to get the Foo instance from the tag field in my first Foo instance and potentially perform operations on it.

Is there a well known software pattern to deal with this? Or what is a good approach for this problem?

Aucun commentaire:

Enregistrer un commentaire