Facade Pattern is used in many source codes, such as slf4j, which can be understood as the application of Facade Pattern. This is a simple design pattern, but it is seldom used in Java. The main reasons are as follows:
- Java developers usually require a holistic understanding of the tools in the library, and the appearance pattern may limit this way of using the system.
- Java class libraries provide few appearance classes.
Just lift a chestnut.
First, we define an interface:
public interface Shape { void draw(); }
Define several implementation classes:
public class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } }
Client call:
public static void main(String[] args) { // Draw a circle Shape circle = new Circle(); circle.draw(); // draw a rectangle Shape rectangle = new Rectangle(); rectangle.draw(); }
These are the codes we often write. We need to instantiate the circle first when we draw a circle. We need to instantiate a rectangle first when we draw a rectangle, and then call the corresponding draw() method.
Next, let's see how to use the facade mode to make client calls more friendly.
Let's first define a facade:
public class ShapeMaker { private Shape circle; private Shape rectangle; private Shape square; public ShapeMaker() { circle = new Circle(); rectangle = new Rectangle(); square = new Square(); } /** * Next, we define a bunch of methods, and it's up to this facade to decide what method to call. */ public void drawCircle(){ circle.draw(); } public void drawRectangle(){ rectangle.draw(); } public void drawSquare(){ square.draw(); } }
See how the client calls now:
public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); // Client calls are now clearer shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); }
The advantage of the facade mode is obvious. The client no longer needs to pay attention to which implementation class should be used when instantiating. That is to say, it does not need to inform the user of the specific implementation, that is to say, the user does not need to care about the specific implementation. It is OK to call the method provided by the facade directly, because the method name of the method provided by the facade class is right. It's very friendly to the client.