jeudi 25 juin 2020

How to make sure that the implementation objects for an interface should only be created by implementation instances of another interface?

I have a set of data model classes, e.g. DataModel1, DataModel2 and so on. The parameters that are part of each data class are totally different. The only thing common about these data classes is the objects which are going to use their values. I have an interface 'Investigator', and only different implementation of these Investigator can use different type data of above model classes.

Initially I was having an empty interface for all data classes, like this

public interface DataModel {}

But then I realised that my scenario fits the visitor pattern. So, I made changes as below: I now have a DataModel interface

public interface DataModel {
    void accept (Investigator investigator)
}

public class DataModel1 implements DataModel {
    private String attribute1;
    private String attribute2;

    @Override
    void accept (Investigator1 investigator) {
        investigator.investigate(this);
    }

}

public class DataModel2 implements DataModel {
    private String attribute3;
    private String attribute4;

    @Override
    void accept (Investigator2 investigator) {
        investigator.investigate(this);
    }

}

and an Investigator interface:

public interface Investigator {
    void investigate(DataModel dataModel);
}

public class Investigator1 implements Investigator {

    @Override
    void investigate (DataModel dataModel) {
        // do some investigations of Type 1 here
    }

}

public class Investigator2 implements Investigator {

    @Override
    void investigate (DataModel dataModel) {
        // do some investigations of Type 2 here
    }

}

Now, for any kind of investigator and data model implementations, I just have to do:

dataModel.accept(investigator)

and the correct type of investigation will be done.

Now, my problem comes when I want to actually return a result from the investigation that was done. Similar to above requirements, an Investigator can return different types of InvestgationResult, so I have the interface and its implementations:

public interface InvestigationResult {
}

public class InvestigationResult1 implements InvestigationResult {
    public String investigationText1;
    public String detailedResults1;
}

public class InvestigationResult2 implements InvestigationResult {
    public String investigationText2;
    public String detailedResults2;
}

and the Investigator interface be changed to:

public interface Investigator { InvestigationResult investigate(DataModel dataModel); }

Requirement here is that an instance of a InvestigationResult should only be created by an Investigator class. My question here is that I don't want the 'InvestigationResult' interface to be am empty interface, but I am not very sure what common method it should contain? Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire