Facade

The facade design pattern is used to provide a clean and simple interface to certain functionalities. Encapsulation and abstraction layers are certainly among the most important principles for writing code. We introduce facades which encapsulate complex functionality or legacy components that are cumbersome to use, into simpler interfaces. A facade is therefore a prime example for abstraction.

Let's consider a rather complex setup in a coffee shop. There are grinders, coffee machines, scales, and various tools in use that all need to be configured accordingly:

public class BaristaCoffeeShop {

    private BeanStore beanStore;
    private Grinder grinder;
    private EspressoMachine espressoMachine;
    private Scale scale;
    private Thermometer thermometer;
    private Hygrometer hygrometer;

    public GroundBeans grindBeans(Beans beans, double weight) { ... }

    public Beans fetchBeans(BeanType type) { ... }

    public double getTemperature() { ... }

    public double getHumidity() { ... }

    public Coffee makeEspresso(GroundBeans beans, Settings settings) { ... }
}

One could certainly argue that this class already needs refactoring. However, legacy classes may not be changeable easily. We will introduce a barista that acts as a facade:

@Stateless
public class Barista {

    @Inject
    BaristaCoffeeShop coffeeShop;

    public Coffee makeCoffee() {
        // check temperature & humidity
        // calculate amount of beans & machine settings
        // fetch & grind beans
        // operate espresso machine
    }
}

In the Java EE world, the most prominent example of facades are boundaries implemented with EJBs. They provide the facade to the business use cases that are part of our business domain. Besides that, facades can be implemented using all kinds of managed beans. Facades delegate and orchestrate complex logic appropriately. Well-chosen abstractions improve the software design and are an aim to strive for.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.252