lundi 29 janvier 2018

Is there a pattern for writting telescopic configureable classes in Java?

I'm thinking at the moment about the solution of a problem which might be already solved by a pattern but I can not find the correct one. I'll try to explain what I would like to do with a simplefied example.

There is a class which handles to connection to a database, let's call it DatabaseManager.java. With this class I would like to handle the fetchment of data from a database and I also would like to apply filter.

public class DatabaseManager {

    DatabaseFilter databaseFilter = new DatabaseFilter();

    public DatabaseManager() {
        // Do some stuff to init db connection
    }

    public DatabaseFilter configureFilter() {
        return databaseFilter;
    }

    public String getStringDataset() {
        String dataset = null;
        // Fill dataset with applied filter data
        return dataset;
    }

}

With the method call configureFilter() on the databse object, I would like to get the DatabaseFilter which contains particular nested filter classes.

public class DatabaseFilter {

    int[] filteredIds = null;

    public IdFilter onId() {
        return new IdFilter();
    }

    public class IdFilter {
        private void exclude(int[] ids) {
            filteredIds = ids;
        }
    }
}

On this way, I could write the follwing nice syntax to configure a filter which excludes particular filter.

DatabaseManager database = new DatabaseManager();
database.configureFilter().onId().exclude(idArray);
// Get filtered dataset
database.getStringDataset();

Is this an appropriate way to solve problems like this and is this a particular pattern? Are there any disadvantages?

Aucun commentaire:

Enregistrer un commentaire