1

Following on from the question How do the Proxy, Decorator, Adapter, and Bridge Patterns differ?, how would you describe the following pattern which I've needed to implement on several occasions?

The scenario is that I'm referencing a static method or variable from a third-party class, but I want to hide it behind an interface so that I can mock it for testing.

For example, in Java the commons-lang library has a SystemUtils class with constants IS_OS_WINDOWS etc. I want to run tests which are independent of the underlying OS and mimic various OSs, so I wrap access to the constant as follows:

interface ISystemUtils {
    boolean isOsWindows();
}

class SystemUtilsImpl implements ISystemUtils {
    @Override
    public boolean isOsWindows() {
        return SystemUtils.IS_OS_WINDOWS;
    }
}

Is this a Proxy, a generic "wrapper", or something else?

Community
  • 1
  • 1
Richard
  • 143
  • 1
  • 10

2 Answers2

5

This is called a Facade:

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system
  • wrap a poorly designed collection of APIs with a single well-designed API.
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
  • Thanks for the fast answer @adriaan. Facade "feels" right although my understanding was that it usually (always?) involved covering elements of _multiple_ underlying classes. However my example arguably covers most of the above bullet points, particularly the first one. – Richard Dec 15 '16 at 10:33
  • 1
    @Gendarme Fixed the layout of the Facade link, tnx – Adriaan Koster Dec 15 '16 at 12:50
1

The Facade pattern is a good answer, although I do agree that it normally (in my experience at least) expose a number of different operations/classes. With that said, a number of other patterns can also serve the same purpose - Proxy would likely be my first choice, but Adaptor or Mediator could also be a good fit. Another term for this that you may also come across is a "delegate".

Riaan Nel
  • 2,425
  • 11
  • 18