vendredi 2 mars 2018

Java design pattern to avoid duplication

I have the following classes

public class MyCustomFactory extends SomeOther3rdPartyFactory {

    // Return our custom behaviour for the 'string' type
    @Override
    public StringType stringType() {
        return new MyCustomStringType();
    }

    // Return our custom behaviour for the 'int' type
    @Override
    public IntType intType() {
        return new MyCustomIntType();
    }

    // same for boolean, array, object etc
}

Now, for example, the custom type classes:

public class MyCustomStringType extends StringType {
    @Override
    public void enrichWithProperty(final SomePropertyObject prop) {
        super.enrichWithProperty(prop);

        if (prop.getSomeAttribute("attribute01")) {
            this.doSomething();
            this.doSomethingElse();
        }

        if (prop.getSomeAttribute("attribute02")) {
            this.doSomethingYetAgain();
        }

        // other properties and actions
    }
}

But each custom type class like the string one above might have exactly the same if (prop.getSomeAttribute("blah")) { // same thing; }

Suppose I was to add another attribute, is there a nice way I can avoid having to duplicate if statements in each custom type class that needs it? I can move each if statement to utility class but I still need to add the call to the method in the utility class. I think we can do better.

Aucun commentaire:

Enregistrer un commentaire