Design patterns

The Facade pattern

Facade is a struc­tur­al design pat­tern that pro­vides a sim­pli­fied inter­face to a library, a frame­work, or any other com­plex set of classes.

Facade is a struc­tur­al design pat­tern that pro­vides a sim­pli­fied inter­face to a library, a frame­work, or any other com­plex set of classes.

A facade is a class that pro­vides a sim­ple inter­face to a com­plex sub­sys­tem. A facade might pro­vide lim­it­ed func­tion­al­i­ty, how­ev­er, it includes only those fea­tures that clients need. This is very important when you need to inte­grate your application with a sophis­ti­cat­ed library, but you only need a small part of its func­tion­al­i­ty. Sub­sys­tem class­es aren’t aware of the facade’s exis­tence. They oper­ate with­in the sys­tem and work with each other directly.

How it works (code examples):

public class Blender {
    public void blend(){
        System.out.println("Blending fruits and nuts smoothie.");
    }
}
public class CoffeePot {
    public void boil(){
        System.out.println("Boiling coffee.");
    }
}
public class Toaster {
    public void heat(){
        System.out.println("Heating bread.");
    }
}
public class PrepareBreakfastFacade {

    Blender belnder;
    CoffeePot coffeePot;
    Toaster toaster;

    public PrepareBreakfastFacade (
        Blender blender, 
        CoffeePot coffeePot, 
        Toaster toaster) {
            this.blender = belnder;
            this.coffeePot = coffeePot;
            this.toaster = toaster;
        }

    public prepare() {
        System.out.println("Preparing breakfast.");
        blender.blend();
        coffeePot.boil();
        toaster.heat();
    }
}
public class PrepareBreakfastTest{
    public static void main (String[] args) {
        Blender blender = new Blender();
        CoffeePot coffeePot = new CoffeePot();
        Toaster toaster = new Toaster();

        PrepareBreakfastFacade prepareBreakfastFacade = new PrepareBreakfastFacade (blender, coffeePot, toaster);
        prepareBreakfastFacade.prepare();
    }
}

Related patterns: Adapter, Abstract Factory, Flyweight, Mediator, Singleton, Proxy.

Leave a Reply

Your email address will not be published. Required fields are marked *