Facade

If a class has a complex interface, we can use the facade pattern. According to this pattern, we should create a new class that contains an instance of a class that we want to use. The following diagram demonstrates when we want to use the Preferences API (https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html) to persist the state of the User class:

The preceding diagram contains the User class, which is responsible for simplifying a public interface of the Preference class.  The end user works with an instance of the User class instead of Preference.

The User class may look like this:

data class User(
private val preferences: Preferences = Preferences.userRoot().node(User::class.java.simpleName),
val id: Int = preferences.getInt(User::id.name, 0),
val firstName: String = preferences.get(User::firstName.name, ""),
val lastName: String = preferences.get(User::lastName.name, "")
) {
init {
with(preferences) {
putInt(User::id.name, id)
put(User::firstName.name, firstName)
put(User::lastName.name, lastName)
}
}
}

In the preceding snippet, we use the User class as a facade to simplify work with the Preferences API. We also use it as follows:

fun main(args: Array<String>) {
User(id = 1, firstName = "Igor", lastName = "Kucherenko").apply {
println(this)
}
println(User())
}

The output looks like this:

User(preferences=User Preference Node: /User, id=1, firstName=Igor, lastName=Kucherenko)
User(preferences=User Preference Node: /User, id=1, firstName=Igor, lastName=Kucherenko)

We can use the User class to persist information about a currently logged in user in our system.

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

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