mercredi 6 février 2019

Relevancy of Factory design pattern for multiple instances of same object?

I have a program that takes as input a feature string parameter and outputs an object accordingly.

I'm looking for the best way to design this code.

Currently, I have four possible features. Three of them share the same attributes and the same methods. One share some attributes and some methods. But maybe in the future, there would be more features.

I first considered to use the Factory Design Pattern. Two classes would implement an interface and the three similar features would extend from an abstract class.

public interface Feature{
    String getFeatureName();
}

public abstract class GroupA implements Feature{
    String featureName;
    String attrGroupA1;
    String attrGroupA2;
    String getFeatureName();

public class Feature1 extends GroupA{
    String featureName;
    String attrGroupA1;
    String attrGroupA2;

    Feature1(){
            this.featureName = "Feature1";
            this.attrGroupA1 = "feature1Attr1";
            this.attrGroupA2 = "feature1Attr2;
    }

    String getFeatureName(){
            return this.featureName;
    }
}

Feature2, Feature3 look the same as Feature1 with some attribute change in the constructor.

public class Feature4 implements Feature{
    String featureName;
    String attr1;

    Feature4(){
            this.featureName = "Feature4";
            this.attr1 = "feature4Attr";
    }

    String getFeatureName(){
            return this.featureName;
    }

    void otherMethod(){};

}

public class FeatureFactory {
    public Feature getFeature(String featureName) {
        if(featureName == "Feature1") {
            return new Feature1();
        }
    // etc
    }
}

Problems with this is the replicate codes of the classes Feature1, Feature2 and Feature3.

My second solution was to simply instantiate the same GroupA object (non-abstract this time) with a constructor with parameters for the three first features.

public class FeatureFactory {
    public Feature getFeature(String featureName) {
        if(featureName == "Feature1") {
            return new GroupA("Feature1","feature1Attr1", "feature1Attr2");
        }
    // etc
    }
}

However, it doesn't strike as clean as the first one specially because I have more attributes than this.

Aucun commentaire:

Enregistrer un commentaire