Skip to content

Instantly share code, notes, and snippets.

@mariussoutier
Last active December 16, 2015 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariussoutier/5387104 to your computer and use it in GitHub Desktop.
Save mariussoutier/5387104 to your computer and use it in GitHub Desktop.
Bridge Pattern in Scala
// Adding new functionality via inheritance leads to combinatorial explanation
abstract class Serializer {
def write(string: String): Unit
}
class CsvFileWriter extends FileWriter {
def writeFile(file: java.io.File) = //...
}
class JsonFileWriter extends FileWriter {
def writeFile(file: java.io.File) = //...
}
// Separate out the concern that doesn't belong in the class hierarchy, thus creating a separate hierarchy
type Format = (String => String)
class FileWriter {
def writeFile(file: java.io.File, format: Format): Unit = format(...)
}
class EncryptedFormat extends Format {
def apply(str: String) = //...
}
class CSVFormat extends Format {
def apply(str: String) = //...
}
val EncryptedCSV = new EncryptedFormat compose new CSVFormat
trait Format extends (String => String)
object Format {
implicit object EncryptedFormat extends Format {
def apply(str: String) = //...
}
}
import Format._
class DiskWriter extends Writer {
def writeFile(file: java.io.File)(implicit format: Format): Unit = format(...)
}
class DatabaseWriter extends Writer {
def writeFile(file: java.io.File)(implicit format: Format): Unit = format(...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment