Lecture - Imperative Programming TT23, V


  • Abstract classes vs traits
    • E.g. for a “Change” like in the editor
    • Abstract classes contain “abstract” methods that are not implemented
    • May also contain instance variables and ordinary methods
    • Can’t create instances of an abstract class
    • But can have subclasses of an abstract class that do implement
    • In Scala, you can extend multiple traits but not multiple abstract classes
  • Memento pattern
    • Taking a memory of the state so that we can return to it later
    • Using an inner class, stores all of the outer class’ state on construction
  • Decorator pattern
    • Using a mixin or a subclass to add functionality to a component class

Flashcrds (GPT-4)

What is the main difference between abstract classes and traits in Scala?


In Scala, you can extend multiple traits but not multiple abstract classes.

What are abstract methods in abstract classes?


Abstract methods are methods declared in an abstract class without implementation, meant to be implemented by subclasses.

Can you create instances of an abstract class in Scala?


No, you cannot create instances of an abstract class, but you can create instances of its subclasses that implement the abstract methods.

What is the Memento pattern?


A design pattern that captures an object’s state at a specific point, allowing the state to be restored later.

How can the Memento pattern be implemented using an inner class?


The inner class stores the state of the outer class upon construction, preserving the outer class’s state at a specific moment.

What is the Decorator pattern?


A design pattern that allows adding new functionality to an object without altering its structure, often using mixins or subclasses.

What is an example of using the Decorator pattern in Scala?


Using a mixin (trait) to add functionality to a component class, extending the base class and mixing in the trait.

What is the primary purpose of the Decorator pattern?


To add or modify behavior of an object dynamically at runtime without affecting other instances of the same class.

How does the Decorator pattern maintain the original object’s interface while adding new functionality?


By having the decorator class implement the same interface as the original object and wrapping the original object, forwarding method calls to the wrapped object and adding or modifying behavior as needed.




Related posts