If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Tuesday, July 9, 2013

constructing simple pipelines in Scala

Playing a bit with constructing pipelines logically in Scala. A pipeline MUST start with a generator, folllowed by 0 to many transformers and MUST end with a serializer.
trait PipelineComponent {
def execute: Unit
}
trait Generator extends PipelineComponent {
override def execute: Unit = print("Generator executing\n")
}
trait Transformer extends PipelineComponent {
override def execute: Unit = print("Transformer executing\n")
}
trait Serializer extends PipelineComponent {
override def execute: Unit = print("Serializer executing\n")
}
abstract class AbstractPipeline(pipelineComponents: List[PipelineComponent])
case class EmptyPipeline extends AbstractPipeline(List()) {
def add(generator: Generator): NonEmptyPipeline = new NonEmptyPipeline(List(generator))
}
case class NonEmptyPipeline(pipelineComponents: List[PipelineComponent]) extends AbstractPipeline(pipelineComponents) {
def add(transformer: Transformer): NonEmptyPipeline = new NonEmptyPipeline(pipelineComponents :+ transformer)
def add(serializer: Serializer): FinishedPipeline = new FinishedPipeline(pipelineComponents :+ serializer)
}
case class FinishedPipeline(pipelineComponents: List[PipelineComponent]) extends AbstractPipeline(pipelineComponents) {
def execute(): Unit = pipelineComponents.foreach(_.execute)
}
/**
object PipelineApp extends App {
val generator = new Object with Generator
val transformer1 = new Object with Transformer
val transformer2 = new Object with Transformer
val serializer = new Object with Serializer
new EmptyPipeline().add(generator).add(transformer1).add(transformer2).add(serializer).execute
}
this will print:
Generator executing
Transformer executing
Transformer executing
Serializer executing
**/
view raw gistfile1.scala hosted with ❤ by GitHub

No comments:

Post a Comment