Search code examples
javadesign-patternsinterfacefacade

Can I have an interface in facade design pattern?


I want to know if I have a facade class, can I create an interface and have multiple implementations of the class.

E.g.:

interface IUserDetailFacade{}

public class UserDetailsFacade implements IUserDetailFacade{}

public class UserDetailsLdapFacade implements IUserDetailFacade{}

Solution

  • Of course you can.

    The example that you have shared isn't quite detailed for me to understand how one more layer of abstraction (the interface you want to create) fits in.

    But let me give you an example where this would make sense.

    Example

    Suppose you are creating an application that tests how efficiently different C++ compilers compile the same source code.

    You can create CppCompiler as an interface to different facades, one each for each type of CppCompiler.

    public interface CppCompiler {
        void compile(String sourceFile);
    }
    

    TurboCppCompiler, BorlandCppCompiler, GccCppCompiler, etc. are facades of a subsystem of classes which do different steps in the compilation like parsing, assembling, linking, etc. For example, TurboCppCompiler implementation would look something like this.

    public class TurboCppCompiler implements CppCompiler {
    
        // .. private variables
    
        public TurboCppCompiler(TurboParser parser, TurboAssembler assembler, TurboLinker linker) {
            this.parser = parser;
            this.assembler = assembler;
            this.linker = linker;
        }
    
        public void compile(String sourceFile) {
            /* Compile the code Borland Cpp style using the subsystems Parser, Assembler, Linker */
        }
    }
    

    Usage

    You can create a factory method that gets a compiler (notice how the CppCompiler is used as a return type here)

    public static CppCompiler createCppCompiler(CompilerType type) {
        switch (type) {
            case TURBO:
                return new TurboCppCompiler(new TurboParser(), new TurboAssembler(), new TurboLinker());
            case BORLAND:
                return new BorlandCppCompiler(new BorlandParser(), new BorlandAssembler(), new BorlandLinker());
            case GCC:
                return new GccCppCompiler(new GccParser(), new GccAssembler(), new GccLinker());
        }
        throw new AssertionError("unknown compiler type:" + type);
    }
    

    Hope this helps.