The literal meaning of Facade is the ‘outward look’ or ‘appearance’ of something. Facade lies in the category of Structural Design Patterns. Facade pattern creates a gateway to access one or more complex objects. It encapsulates all the complex logic from the client. As a result, making the use of multiple objects simpler by exposing one or more functions to the client to use and do the required operations.

Class Diagram

 

Implementation

A facade is a class that composes and controls all the complex objects within. Providing one or more points of usages outside to the client.  Have a look at the following code snippet:

SwiftKotlin
class FileReader {
    func getFilePath(fileName: String) -> String {
        //.. Logic to read file path
        return "/path/\(fileName)"
    }
}

class FileOpener {
    func open(filePath: String) {
        //.. Logic to open File
    }
}

class FileOpenerFacade {
    
    private let fileReader = FileReader()
    private let fileOpener = FileOpener()

    
    func open(fileName: String) {
        let filePath = fileReader.getFilePath(fileName: fileName)
        fileOpener.open(filePath: filePath)
    }
}
class FileReader {
    fun getFilePath(fileName: String) : String {
        //.. Logic to read file path
        return "/path/${fileName}"
    }
}

class FileOpener {
    fun openFile(path: String) {
        //.. Logic to open File
    }
}

class FileOpenerFacade {
    
    private val fileReader = FileReader()
    private val fileOpener = FileOpener()

    
    fun openFile(name: String) {
        val filePath = fileReader.getFilePath(name)
        fileOpener.openFile(filePath)
    }
}

Usage

Using a facade class is pretty simple.

SwiftKotlin
let fileOpenerFacade = FileOpenerFacade()
fileOpenerFacade.open(fileName: "kodesnippets.doc")
val fileOpenerFacade = FileOpenerFacade()
fileOpenerFacade.openFile("kodesnippets.doc")

Pros

One of the most important benefits of the Facade design pattern is that it hides all the unnecessary logic from the client that it might not be interested in. For instance, the client doesn’t care how a file is opened internally. Another good thing is even in the future if the implementation of any of the subsystems (FileReader, or FileOpener) changes. It will not affect how it is used outside by the client. It promotes less coupling between client and subsystems.

Cons

If the internal structure of subsystem changes. The facade class needs to be changed as well. It may become large and difficult to maintain if not used efficiently.

Conculsion

Facade design pattern is used when sophisticated subsystems are needed to be hidden from the client. Facade simplifies a large and complex set of systems into a small and easy to use the system by providing a single gateway.

If you have any questions please feel free to leave them in the comment section below.

2 Comments

Leave a Reply

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