- Professional Scala
- Mads Hartmann Ruslan Shevchenko
- 42字
- 2021-07-23 17:24:27
OO in Our Chatbot
Now that you know the theoretical basics, let's look at these facilities and how they are used in our program. Let's open Lesson 2/3-project
in our IDE and extend our chatbot, which was developed in the previous chapter.
Decoupling Logic and Environment
To do this, we must decouple the environment and logic, and integrate only one in the main
method.
Let's open the EffectsProvider
class:
Note
For full code, refer to Code Snippets/Lesson 2.scala
file.
trait EffectsProvider extends TimeProvider { def input: UserInput def output: UserOutput } object DefaultEffects extends EffectsProvider { override def input: UserInput = ConsoleInput override def output: UserOutput = ConsoleOutput override def currentTime(): LocalTime = LocalTime.now() override def currentDate(): LocalDate = LocalDate.now() }
Here, we encapsulate all of the effects into our traits, which can have different implementations.
For example, let's look at UserOutput
:
For full code, refer to Code Snippets/Lesson 2.scala
file.
trait UserOutput { def write(message: String): Unit def writeln(message: String): Unit = { write(message) write("\n") } } object ConsoleOutput extends UserOutput { def write(message: String): Unit = { Console.print(message) } }
Here, we can see the trait and object, which implement the current trait. This way, when we need to accept commands that are not from standard input, but from the chatbot API or from Twitter, we only need to change the implementation of the UserOutput
/ ConsoleOutput
interfaces.
It's now time to implement ConsoleOutput
and DefaultTimeProvider
.
Replace ???
in main with the appropriative constructor.
These steps for implementing ConsoleOutput
and DefaultTimeProvider
are as follows:
- Ensure that
Lesson 2/3-project
is open in IDE. - In the
UserOutput
file, find theConsoleOutput
file and change???
to the body of thewrite
method. The resulting method should look like this:object ConsoleOutput extends UserOutput{ def write(message: String): Unit = { Console.print(message) } } }
- In the
TimeProvider
file, add theDefaultTimeProvide
object which extends fromTimeProvider
and implements thecurrentTime
andcurrentDate
functions. The resulting code should look like this:object DefaultTimeProvider extends TimeProvider { override def currentTime(): LocalTime = LocalTime.now() override def currentDate(): LocalDate = LocalDate.now() } }
- 自動駕駛網(wǎng)絡(luò):自智時代的網(wǎng)絡(luò)架構(gòu)
- 異構(gòu)基因共表達(dá)網(wǎng)絡(luò)的分析方法
- 網(wǎng)絡(luò)創(chuàng)新指數(shù)研究
- JBoss EAP6 High Availability
- Spring Cloud微服務(wù)架構(gòu)進(jìn)階
- 物聯(lián)網(wǎng)與無線傳感器網(wǎng)絡(luò)
- 計算機(jī)網(wǎng)絡(luò)工程實用教程(第2版)
- 城市治理一網(wǎng)統(tǒng)管
- CCNP TSHOOT(642-832)認(rèn)證考試指南
- Echo Quick Start Guide
- Learning Windows 8 Game Development
- 物聯(lián)網(wǎng)工程概論
- Getting Started with Memcached
- Dart Cookbook
- SRv6網(wǎng)絡(luò)部署指南