Saturday, April 29, 2017

Scala Dessign Patterns: AOP(Aspect Oriented Programming)

Introduction:

AOP(Aspect Oriented Programming) Recommends that, Cross-Cutting concerns are abstracted and encapsulated in their own Module.

Agenda:

AOP(Aspect Oriented Programming) using Scala.

Code: 


trait LoggingPersonDAOReader extends PersonDAO {

  override abstract def readDataFromDatabase: List[Person] = {
    val starttime = System.currentTimeMillis()
    val result = super.readDataFromDatabase
    val totalTime = System.currentTimeMillis() - starttime
    println(s"It tooks $totalTime milliseconds ... ")
    result
  }
}



case class Person (name: String)

trait PersonDAO {
  def readDataFromDatabase: List[Person]
}

class PersonDAOImplWithoutAOP extends PersonDAO{

  def readDataFromDatabase: List[Person] = {
    println("In PersonDAOImplWithoutAOP ... ")

    val starttime = System.currentTimeMillis()
    println("Start reading data from database ..... ")
    Thread.sleep(3000)
    println("End reading data from database ..... ")
    val totalTime = System.currentTimeMillis() - starttime
    println(s"It tooks $totalTime milliseconds ... ")

    List(Person("Knoldus"), Person("James"), Person("Taara"))
  }
}

class PersonDAOImplWithAOP extends PersonDAO {

  def readDataFromDatabase: List[Person] = {
    println("In PersonDAOImplWithAOP ... ")

    println("Start reading data from database ..... ")
    Thread.sleep(3000)

    List(Person("Knoldus"), Person("James"), Person("Taara"))
  }
}

object AOPExample extends App {

  new PersonDAOImplWithoutAOP().readDataFromDatabase
  println()
  val string =
    """
      |  /$$$$$$   /$$$$$$  /$$$$$$$
      | /$$__  $$ /$$__  $$| $$__  $$
      || $$  \ $$| $$  \ $$| $$  \ $$
      || $$$$$$$$| $$  | $$| $$$$$$$/
      || $$__  $$| $$  | $$| $$____/
      || $$  | $$| $$  | $$| $$
      || $$  | $$|  $$$$$$/| $$
      ||__/  |__/ \______/ |__/
    """.stripMargin
  println(string)
  println()
  (new PersonDAOImplWithAOP with LoggingPersonDAOReader).readDataFromDatabase
}

Download Code from Github Repo

 

References:

Scala Design Patterns By Ivan Nikolov