HooneyLog

Facade Pattern

프로필 이미지

Seunghoon Shin

2022년 7월 30일 12:34

What is Facade Pattern?

you can use this pattern to hide highly some complexity codes behind a method, which makes your codes so much clearer.

Example

I’m going to watch a movie at my home.

But, I need to do lots of things to do it. I need popcorn, coke, dimmed light, TV, video..

They are pretty a lot, but I don’t want to expose complex codes. Therefore, I’m going to make codes by using facade pattern

class PopcornMaker {
    turnOn() {
        console.log("Turn on popcorn maker");
    }

    pop() {
        console.log("Popping")
    }
}

class Beverage {
    getCoke() {
        console.log('Getting a cup of coke');
    }
}

class Light {
    dim() {
        console.log("Lights are dimming")
    }
}

class TV {
    turnOn() {
        console.log("Turn on TV");
    }
}

class Video {
    play() {
        console.log("Playing a video")
    }
}

class HomeTheaterFacade {
    private popconMaker:PopcornMaker;
    private beverage:Beverage;
    private light:Light;
    private tv:TV;
    private video:Video;

    constructor(popconMaker:PopcornMaker,beverage:Beverage, light:Light,tv:TV,video:Video) {
        this.popconMaker = popconMaker;
        this.beverage = beverage;
        this.light = light;
        this.tv = tv;
        this.video = video
    }

    watchMovie() {
        this.popconMaker.turnOn();
        this.popconMaker.pop();

        this.beverage.getCoke();

        this.light.dim();

        this.tv.turnOn();

        this.video.play();
    }
}

const popconMaker = new PopcornMaker();
const beverage = new Beverage();
const light = new Light();
const tv = new TV();
const video = new Video();

const homeTheater = new HomeTheater(popconMaker,beverage,light,tv,video);
homeTheater.watchMovie();

Conclusion

As you see, you don’t have to know complex codes in “watchMovie” method to understand what the method do and it is so clean that it is easy to refactor in the future.