Pergunta

I'm trying to understand the strategy pattern and asking myself: is the context class must-have or can I leave it out without compromising pattern's purpose ?

I was under the impression I needed some kind of switch for reading different types of files but didn't want to just hack something and later deal with refactoring (although, of course it always happens that code can be refactored but the idea was: try to be as smart as possible in the design beforehand...):

enter image description here

Image taken from wikimedia

Can the client delegate directly to the Strategy interface or is there something I just missed to understand about the context class?

interface Reader {
    // read information from file and fill data list field of Client
    readFile();
}
class ExcelReader implements Reader{ /* */ }
class PdfReader implements Reader{ /* */}

class Client{
    // strategic choice
    Reader r;

    // data list field
    List<Data> data;

    // Client Constructor
    public Client(){
        if(<file ends in .xls>)
            r = new ExcelReader();
        else
            r = new PdfReader();
        r.readFile();
    }
}

So, above depicted is the context class missing. Does the code adhere to the strategy pattern?

Nenhuma solução correta

Licenciado em: CC-BY-SA com atribuição
scroll top