-->

Does Façade leverage the Open-Closed Principle?

2019-07-09 04:30发布

问题:

The Wikipedia page (as of today 2013-02-27) for the Open-Closed Principle says that it's realized via inheritance.

The name Open/Closed Principle has been used in two ways. Both ways use inheritance to resolve the apparent dilemma, but the goals, techniques, and results are different.

The "two ways" refers to Meyer's implementation inheritance and the more common Polymorphic extensions.

Anyway, my question is about the Façade pattern, which does not use inheritance. Since it defines an abstraction in the form of a simplified interface to a more complex sub-system (or library), can't this be seen also as the Open-Closed Principle? More specifically:

The sub-system (or library) is open for extension to a client that uses the Façade, whose interface is closed to modification.

Or am I just stretching the boundaries of information hiding (which is very close to OCP, especially if you consider it as Protected Variations).

回答1:

No, the Facade pattern addresses a different concern than the OCP. A Facade is just a class that fronts for some other classes. The Facade insulates its clients from changes in the classes it fronts for, but that's not the OCP. The OCP is about how individual classes change in response to changes in requirements. Nothing about a Facade is set up to channel those changes. If the client's requirements on the Facade change, so will the Facade. If any of the classes that the Facade fronts for change in ways that the Facade cares about, so will the Facade.

One can imagine a version of Facade that is set up to follow the OCP — perhaps a Facade whose interface to the client is an interface or abstract class which is closed for modification but can be extended to accomodate new requirements — and in fact I've always implemented Facades that way, but that's not part of the classic description of Facade.