What's the difference between abstraction and generalization?

后端 未结 8 1308
滥情空心
滥情空心 2021-01-30 13:26

I understand that abstraction is about taking something more concrete and making it more abstract. That something may be either a data structure or a procedure. For example:

8条回答
  •  你的背包
    2021-01-30 13:46

    Not addressing credible / official source: an example in Scala

    Having "Abstraction"

      trait AbstractContainer[E] { val value: E }
    
      object StringContainer extends AbstractContainer[String] {
        val value: String = "Unflexible"
      }
    
      class IntContainer(val value: Int = 6) extends AbstractContainer[Int]
    
      val stringContainer = new AbstractContainer[String] {
        val value = "Any string"
      }
    

    and "Generalization"

      def specialized(c: StringContainer.type) =
        println("It's a StringContainer: " + c.value)
    
      def slightlyGeneralized(s: AbstractContainer[String]) =
        println("It's a String container: " + s.value)
    
      import scala.reflect.{ classTag, ClassTag }
      def generalized[E: ClassTag](a: AbstractContainer[E]) =
        println(s"It's a ${classTag[E].toString()} container: ${a.value}")
    
      import scala.language.reflectiveCalls
      def evenMoreGeneral(d: { def detail: Any }) =
        println("It's something detailed: " + d.detail)
    

    executing

      specialized(StringContainer)
      slightlyGeneralized(stringContainer)
      generalized(new IntContainer(12))
      evenMoreGeneral(new { val detail = 3.141 })
    

    leads to

    It's a StringContainer: Unflexible
    It's a String container: Any string
    It's a Int container: 12
    It's something detailed: 3.141
    

提交回复
热议问题