Last active
December 16, 2015 05:49
-
-
Save mariussoutier/5387104 to your computer and use it in GitHub Desktop.
Bridge Pattern in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) = //... | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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