jeudi 14 juin 2018

Factory Design Pattern - defining methods in subclasses

I'm implementing a factory a class in charge of managing tokens across an application. I'll explain the problem I'm facing after this simplified example:

Suppose we have our factory class:

TokenManagerFactory.java:

public class TokenManagerFactory {

    public static TokenManager create(String tokenType)
    {
        if ("JWT".equals(tokenType))
            return new JwtTokenManagerImpl();

        return null;
    }


}

Then our abstract interface:

public abstract interface TokenManager {
    public  String       generateToken();
    public  boolean      verifyToken();
}

And finally the implementation JwtTokenManagerImpl:

public class JwtTokenManagerImpl implements TokenManager {
    //..Implementation of methods defined in interface (generateToken() and 
    //  verifyToken())

    public String aMethodNotDefinedInInterface() {
        return "A very cool String";
    }
}

Now in our main we want to create an instance of JwtTokenManager:

main {

    TokenManager tm = TokenManagerFactory.create("JWT");
    tm.aMethodNotDefinedInInterface(); // <-- Compilation error.

}

The method aMethodNotDefinedInInterface() is undefined for the type TokenManager

How do I adjust this design pattern so this error does not occur? Downcasting for when doing such calls seems like a harsh solution, is there a higher level adjustment I could make to accommodate this scenario?

Thanks.

Aucun commentaire:

Enregistrer un commentaire