Nice programing

추상 클래스보다 특성을 사용하는 장점은 무엇입니까?

nicepro 2020. 10. 5. 20:55
반응형

추상 클래스보다 특성을 사용하는 장점은 무엇입니까?


누군가 Scala의 특성을 설명해 주시겠습니까? 추상 클래스를 확장하는 것에 비해 트레이 트의 장점은 무엇입니까?


짧은 대답은 여러 특성을 사용할 수 있다는 것입니다. 또한 트레이 트는 생성자 매개 변수를 가질 수 없습니다.

특성이 쌓이는 방법은 다음과 같습니다. 특성의 순서가 중요합니다. 그들은 오른쪽에서 왼쪽으로 서로를 부를 것입니다.

class Ball {
  def properties(): List[String] = List()
  override def toString() = "It's a" +
    properties.mkString(" ", ", ", " ") +
    "ball"
}

trait Red extends Ball {
  override def properties() = super.properties ::: List("red")
}

trait Shiny extends Ball {
  override def properties() = super.properties ::: List("shiny")
}

object Balls {
  def main(args: Array[String]) {
    val myBall = new Ball with Shiny with Red
    println(myBall) // It's a shiny, red ball
  }
}

사이트 는 특성 사용의 좋은 예를 제공합니다. 특성의 큰 장점 중 하나는 여러 특성을 확장 할 수 있지만 하나의 추상 클래스 만 확장 할 수 있다는 것입니다. 특성은 다중 상속으로 많은 문제를 해결하지만 코드 재사용을 허용합니다.

루비를 아시면 믹스 인과 비슷한 특성


package ground.learning.scala.traits

/**
 * Created by Mohan on 31/08/2014.
 *
 * Stacks are layered one top of another, when moving from Left -> Right,
 * Right most will be at the top layer, and receives method call.
 */
object TraitMain {

  def main(args: Array[String]) {
    val strangers: List[NoEmotion] = List(
      new Stranger("Ray") with NoEmotion,
      new Stranger("Ray") with Bad,
      new Stranger("Ray") with Good,
      new Stranger("Ray") with Good with Bad,
      new Stranger("Ray") with Bad with Good)
    println(strangers.map(_.hi + "\n"))
  }
}

trait NoEmotion {
  def value: String

  def hi = "I am " + value
}

trait Good extends NoEmotion {
  override def hi = "I am " + value + ", It is a beautiful day!"
}

trait Bad extends NoEmotion {
  override def hi = "I am " + value + ", It is a bad day!"
}

case class Stranger(value: String) {
}
출력 :

목록 (I am Ray
, 나는 레이, 나쁜 날입니다!
, 나는 레이입니다, 아름다운 날입니다!
, 나는 레이, 나쁜 날입니다!
, 나는 레이입니다, 아름다운 날입니다!
)


This is the best example I've seen

Scala in practice: Composing Traits – Lego style: http://gleichmann.wordpress.com/2009/10/21/scala-in-practice-composing-traits-lego-style/

    class Shuttle extends Spacecraft with ControlCabin with PulseEngine{

        val maxPulse = 10

        def increaseSpeed = speedUp
    }

Traits are useful for mixing functionality into a class. Take a look at http://scalatest.org/. Note how you can mix in various domain-specific languages (DSL) into a test class. look at the quick start guide to look at some of the DSL's supported by Scalatest ( http://scalatest.org/quick_start )


Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods.

Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods.

In contrast to classes, traits may not have constructor parameters. Traits are like classes, but which define an interface of functions and fields that classes can supply concrete values and implementations.

Traits can inherit from other traits or from classes.


I am quoting from the website of the book Programming in Scala, First Edition and more specifically the section called "To trait, or not to trait?" from Chapter 12.

Whenever you implement a reusable collection of behavior, you will have to decide whether you want to use a trait or an abstract class. There is no firm rule, but this section contains a few guidelines to consider.

If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.

If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy.

There is a bit more information in the above link regarding traits and I suggest you read the full section. I hope this helps.

참고URL : https://stackoverflow.com/questions/1229743/what-are-the-pros-of-using-traits-over-abstract-classes

반응형