[scala]Scala 设计模式笔记

1 适配器模式

import java.util.logging.Level
import java.util.logging.Level._

// 适配器model
object Adapter extends App {
  trait Log {
    def warn(msg: String)
    def error(msg: String)
  }

  final class Logger {
    def log(level: Level, message: String) = {}
  }

  implicit class LoggerToLogAdapter(logger: Logger) extends Log {
    def warn(msg: String) = { logger.log(WARNING, msg) }
    def error(msg: String) = { logger.log(INFO, msg) }
  }

  val log = new Logger()

  log.warn("warn")
  log.error("error")
}

2 装饰模式


// 在以下两种情况下可以考虑使用装饰器模式:
// (1)需要在不影响其他对象的情况下,以动态、透明的方式给对象添加职责。
// (2)如果不适合使用子类来进行扩展的时候,可以考虑使用装饰器模式。


object Decorator extends App {
  trait OutStream {
    def write(b: Array[Byte])
  }

  class FileOutputStream(path: String) extends OutStream {
    override def write(b: Array[Byte]) = {
      println("do something")
    }
  }

  trait Buffering extends OutStream {
    abstract override def write(b: Array[Byte]) = {
      println("do something before super.write buffering")
      super.write(b)
    }
  }

  new FileOutputStream("hi") .write("hi fileoutput stream".getBytes())

  (new FileOutputStream("hi") with Buffering).write("buffering".getBytes())
}

3 策略模式

object Strategy extends App {
  type Strategy = (Int, Int) => Int
  class Context(s: Strategy) {
    def use(a: Int, b: Int) = s(a, b)
  }

  val add: Strategy = _ + _

  println(new Context(add).use(2, 3))
}

4 责任链模式


object Chain extends App {

  case class Event(source: String)
  trait Handler {
    def handle(event: Event)
  }

  class DefaultHandler extends Handler {
    def handle(event: Event) = { println("default handler handle")}
  }

  trait KeyboardHandler extends Handler {
    abstract override def handle(event: Event): Unit = {
      if (event.source == "keyboard") {
        println("keyboard handler handle")
      } else {
        super.handle(event)
      }
    }
  }

  trait MouseHandler extends Handler {
    abstract override def handle(event: Event): Unit = {
      if (event.source == "mouse") {
        println("mouse handler handle")
      } else {
        super.handle(event)
      }
    }
  }

  val handler = new DefaultHandler with KeyboardHandler with MouseHandler

  handler.handle(new Event(source  = "a"))
  handler.handle(new Event(source  = "keyboard"))
  handler.handle(new Event(source  = "mouse"))

}

5 依赖注入模式

object CI extends App {

  case class User()

  trait Repository {
    def save(user: User)
  }

  trait DefaultRepository extends Repository {
    def save(user: User) = {
      println("save user")
    }
  }

  trait UserService { self: Repository =>
    def create(user: User): Unit = {
      save(user)
    }
  }

  (new UserService with DefaultRepository).create(new User)

}

你可能感兴趣的:([scala]Scala 设计模式笔记)