All Downloads are FREE. Search and download functionalities are using the official Maven repository.

au.id.tmm.utilities.collection.Flyweight.scala Maven / Gradle / Ivy

There is a newer version: 0.4.7
Show newest version
package au.id.tmm.utilities.collection

import scala.collection.mutable

/**
  * A simple implementation of the flyweight pattern
  */
final class Flyweight[A, B] private (generator: A => B) {
  private val map: mutable.Map[A, B] = mutable.Map()

  def apply(key: A): B =
    map.synchronized {
      if (map.contains(key)) {
        map(key)
      } else {
        val value = generator(key)
        map.put(key, value)
        value
      }
    }
}

object Flyweight {
  def apply[A, B](generator: A => B): Flyweight[A, B] = new Flyweight[A, B](generator)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy