Facade Design Pattern in Swift


Greetings, traveler!

So, we gathered again to explore another Design Pattern — the Facade. This Structural Pattern is pretty simple to understand but very effective and commonly used. Its essence lies in hiding complex data manipulation behind a user-friendly interface. Anything can happen behind this modest facade, and as a result, you will get the desired outcome, even though the implementation details are not exposed to the outside.

Example of usage

Let’s examine an example of how this works. As has become a tradition, we’ll use the production of a hamburger to demonstrate the process. What do you need to make a juicy burger with a tender patty, fresh vegetables, and a soft, slightly sweet bun?

We must chop the vegetables (and remember to add more slices of pickled cucumber), fry the patty, and bake a soft bun. Let’s get started, then!

struct Vegetables {
    func chop() {
        print("The vegetables are chopped")
    }
}

struct Patty {
    func fry() {
        print("The patty is fried")
    }
}

struct Bun {
    func bake() {
        print("The bun is baked")
    }
}

Now, let’s put all of this together and make a burger.

final class BurgerFacade {
    
    private let patty = Patty()
    private let veggies = Vegetables()
    private let bun = Bun()
    
    func makeBurger() {
        patty.fry()
        veggies.chop()
        bun.bake()
    }
    
}

To create a burger, we need to call a single function.

let facade = BurgerFacade()
facade.makeBurger()

Conclusion

We have become familiar with the Facade design pattern in this simple example. It is a handy pattern that helps to organize code clearly and efficiently. 

Alright then. The following article will examine another Design Pattern, the Flyweight pattern. See you there!