Search code examples
javaoopdesign-patternsfacade

Java's "Scanner" Method vs. Facade GoF Design Pattern


I'm studying design patterns to improve my programming skills. Right now, I'm exploring the facade design pattern.

I may be confusing myself, but, as an example: isn't the Scanner is a facade? Note that I'm not asking what is a Facade, but trying to identify if Scanner is.

Well, I declare it so I can use certain features without contacting complex and deeper functions, right?

I declare

Scanner sc = new Scanner(System.in);

so I can:

String x = sc.nextLine();

Solution

  • This is a good example of class which simplifies an API and makes it clear and closer to what is used for. When we want to read data from user in console app InputStream would be hard to use. Let's take a look on some definition of Facade pattern and match with Scanner class:

    Intent

    • Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
    • Wrap a complicated subsystem with a simpler interface.

    Scanner class matches both above points.

    Check list

    1. Identify a simpler, unified interface for the subsystem or component.
    2. Design a 'wrapper' class that encapsulates the subsystem.
    3. The facade/wrapper captures the complexity and collaborations of the component, and delegates to the appropriate methods.
    4. The client uses (is coupled to) the Facade only.
    5. Consider whether additional Facades would add value.

    Scanner class matches all above points. So, we can consider Scanner as a facade for InputStream.