jeudi 23 mars 2023

Java Creational design pattern

I am trying to create a class which returns me XX(XX could be either String or List based upon 2 different implementations) based on the input I provide.

I was thinking of building this using Factory/Abstract design pattern wherein the parent class will have 2 subclasses implementing their own logic and then returning String or List.

Can someone please tell if this can be achieved with above mentioned patterns or not?

public class DisplayFactory {

    public Display getDisplay( String device) {
        if ("D".equals(device))
            return new StringDisplay();
        return new StringListDisplay();
    }
}

public abstract class Display<T> {
    T displayFormat;
}

public class StringListDisplay extends Display {
    public StringListDisplay() {
        List<String> stringListDisplay = new ArrayList()<>;
        // some logic
        return stringListDisplay
    }
}

public class StringDisplay extends Display {
    public StringDisplay() {
        String stringDisplay;
        // some logic
        return stringListDisplay
    }
}

Problem with above approach is that the variable displayFormat needs to public to be used in other packages... Can someone share what could be a better approach here? The ideal solution would look like(please do share if its not possible to achieve below requirements):

  1. We should be able to return the specific datatype(String or List) and not some generic datatype(like Object).
  2. Should be able to fetch the value somehow.

Thanks

Aucun commentaire:

Enregistrer un commentaire