Chapter 8: Behavioral Patterns

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/71

encourage image

There's no tags or description

Looks like no tags are added yet.

72 Terms

1
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Let’s say you have a WeatherStation. It stores Humidity, Temperature, and Wind Speed.  Multiple objects are interested in gathering weather data. This includes: <em>Phone Display, Desktop Display, Weather App, Weather Logger, Weather Alert System. </em>So you create the following class. </strong></span></p><p><span style="color: rgb(255, 6, 159);"><strong>What’s the problem with this class?</strong></span></p>

Let’s say you have a WeatherStation. It stores Humidity, Temperature, and Wind Speed. Multiple objects are interested in gathering weather data. This includes: Phone Display, Desktop Display, Weather App, Weather Logger, Weather Alert System. So you create the following class.

What’s the problem with this class?

The problem is that weather station is tightly coupled to every other class it needs information from. This includes: Display, Phone, Logger, and AlertSystem.

Now every time we want to add new devices, for example, Smartwatches, we have to go in and modify the original class.

2
New cards

What category does the Observer Design Pattern fall into?

The Observer Design Pattern falls into the Behavioral Patterns category.

3
New cards

What is the main idea behind the Observer Design Pattern?

The main idea behind the Observer Design Pattern is to treat individual classes all as subscribers.

For example, in the WeatherStation example, instead of knowing about multiple devices that want updates, the WeatherStation only knows that it has subscribers that want to receive updates. All of the devices fall under the same category of “Subscriber”.

4
New cards

What is the goal of the Observer Design Pattern?

The goal is to reduce coupling.

5
New cards

What is a good analogy for the Observer Data Pattern?

A good analogy are subscribers on YouTube.

Whenever a creator uploads a YouTube video, the creator doesn’t manually contact Sofia, Anas, Lachesis, and Jason, one by one, it just notifies all subscribers in the same way.

6
New cards

What does a Publish-Subscribe relationship refer to?

It refers to a relationship in which you have one Publisher, and one or more Subscribers.

The Publisher is the object that owns the information, for example: WeatherStation.

The Subscriber are the objects that care about receiving updates, for example: PhoneDisplay, DesktopDisplay, and WeatherApp.

7
New cards

In the Observer Pattern, we __________ information to all subscribers.

broadcast

8
New cards

What is a Subject?

Subject is the object being observed. It owns information or state that other objects are interested in. It is generally designed as an abstract class that contains methods such as attach(), detach(), and notify() which allows other classes to register as subscribers and receive notifications.

For example: WeatherStation, StockMarket, NewsFeed, GameScoreboard, etc.

9
New cards

What is an Observer?

An Observer is an object that wants to be notified whenever the Subject changes state.

For example: PhoneDisplay, Logger, NotificationSystem

10
New cards

Let’s say we apply the Observer pattern to WeatherStation.

Describe what happens when WeatherStation sends an update to all observers about its temperature. For example, it notifies all subscribers that the Temperature has gone from 25 to 30 degrees celsius.

After the information has been sent to all of the observers, each observer needs to decide what to do. For example, the PhoneDisplay might decide to display 30 degrees on the screen, the Logger might save something that says: The temperature changed to 30 degrees, while the AlertSystem might send a Heat Warning.

11
New cards

What makes the Observer Design Pattern good?

What makes it good is the fact that it reduces coupling. Instead of needing to know about every other class that wants to receive updates, it only knows that it has subscribers, and therefore, it is not dependent on multiple other classes.

Additionally, it supports the Open/Closed Principle, because every time you want to add or remove a subscriber, you don’t have to go back and modify the Subject class. To add a new observer, you would just register it as a subscriber within its own class, and to remove it, you would just unregister it.

12
New cards

What is a ConcreteSubject?

A ConcreteSubject is the implementation of a Subject.

Usually, a Subject by itself is just an abstract class, while a ConcreteSubject is the actual implementation of a Subject.

<p>A ConcreteSubject is the implementation of a Subject.</p><p>Usually, a Subject by itself is just an abstract class, while a ConcreteSubject is the actual implementation of a Subject.</p>
13
New cards

What is a ConcreteObserver?

A ConcreteObserver is the implementation of an Observer.

14
New cards

What problem does the Observer Pattern solve?

The Observer Pattern solves the problem of keeping multiple objects synchronized to another object without tightly coupling them together. It allows for one object to notify many other objects about a change without introducing high coupling.

15
New cards

How is the Observer Design Pattern implemented?

It is implemented by:

  • Creating an abstract Observer class that defines an update() method.

  • Creating multiple Concrete Observer classes that inherit from this interface and provide their own implementation of update().

  • Creating a subject class that maintains a collection of observers, and provides methods such as attach(), detach(), and notify(). It also provides an additional method to prevent notify() from ever taking any parameters.


16
New cards

What are the advantages of using Observer?

  1. It allows for loose coupling between classes.

  2. It supports the Open/Closed Principle

  3. It makes it easy to add new functionality

  4. It allows for a single event to notify multiple objects.


17
New cards

What are the disadvantages of using Observer?

  1. It leads to more classes

  2. It can be harder to debug

  3. If you have 50 observers, it means every change will cause 50 update() calls. This can become inefficient, especially if the observers don’t need all of the updates.


18
New cards

When should you use Observer?

When only one object changes state and multiple other objects need to know about it.

19
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Describe what is happening in each of the following lines of code.</strong></span></p><p><span style="color: rgb(255, 6, 159);"><strong>Identify the Subject and the ConcreteSubject.</strong></span></p>

Describe what is happening in each of the following lines of code.

Identify the Subject and the ConcreteSubject.

knowt flashcard image
20
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Describe what is happening in each of the following lines of code.</strong></span></p><p><span style="color: rgb(255, 6, 159);"><strong>Identify the Observer and the ConcreteObserver.</strong></span></p>

Describe what is happening in each of the following lines of code.

Identify the Observer and the ConcreteObserver.

knowt flashcard image
21
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Given the following Subject &amp; Observer, create a Main class that:</strong></span></p><ul><li><p><span style="color: rgb(255, 6, 159);"><strong>Creates a Subject and an Observer</strong></span></p></li><li><p><span style="color: rgb(255, 6, 159);"><strong>Comes out with 2 new movies (of your choice)</strong></span></p></li></ul><p></p>

Given the following Subject & Observer, create a Main class that:

  • Creates a Subject and an Observer

  • Comes out with 2 new movies (of your choice)


knowt flashcard image
22
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What will be the output of main?</strong></span></p>

What will be the output of main?

knowt flashcard image
23
New cards

What methods are most commonly seen in Observer?

What methods are most commonly seen in Subject?

Why is this?

Common Observer Methods:

  • update() = because an Observer’s entire purpose is to update its internal state based on changes received from the Subject

Common Subject Methods:

  • attach() = because a Subject should allow Observers to subscribe

  • detach() = because a Subject should allow Observers to unsubscribe

  • notify() = because the main job of a Subject is to notify its Observers of a change


24
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What is the problem with the following code?</strong></span></p>

What is the problem with the following code?

The problem is that there is very high coupling.

Course contains Professor, Scheduler, and AttendanceSystem, so any time these classes change, they can cause Course to break.

Additionally, it violates the Open/Closed Principle.

If you wanted to add a third class called PlannerApp, and add it to Course, you would need to go in and modify Course again.

25
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Identify the Observers and the Subject in the following code:</strong></span></p>

Identify the Observers and the Subject in the following code:

The Observers:

  • Professor

  • Scheduler

  • AttendanceSystem

The Subject:

  • Course


26
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What are we trying to notify Subscribers about in the following example?</strong></span></p><p><span style="color: rgb(255, 6, 159);"><strong>Who are the subscribers we are trying to notify, and what message are we trying to send them?</strong></span></p>

What are we trying to notify Subscribers about in the following example?

Who are the subscribers we are trying to notify, and what message are we trying to send them?

Our subscribers are Professor, Scheduler, and AttendanceSystem. We are trying to notify them about updates related to student.

For example, a Student might join a course, a Student might drop a course, or the Course might be cancelled. These are all things a subscriber like a Professor, AttendanceSystem, or Scheduler might care about.

In case you’re confused, the way to think about it is: “Who cares about updates?”

And then think of information those subscribers might be interested in.

27
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Refactor the code to use the Observer Design Pattern.</strong></span></p>

Refactor the code to use the Observer Design Pattern.

Our Observers are Professor, Scheduler, and AttendanceSystem

Our Subject is Course

Observers contain the methods: update()

Subjects contain the methods: notify(), attach(), detach()

What information do we want to notify the Professors, Scheduler, and Attendance System about?

We want to notify them about Students.

MUST ALWAYS PUT Observer class before the Subject class, because otherwise,

Our Subject class would not compile. This is because it has never seen Observer

before.​‌

We generally want notify() to be parameterless​‌

<p><em>Our Observers are Professor, Scheduler, and AttendanceSystem</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>Our Subject is Course</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>Observers contain the methods: update()</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>Subjects contain the methods: notify(), attach(), detach()</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>What information do we want to notify the Professors, Scheduler, and Attendance System about?</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>We want to notify them about Students.</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>MUST ALWAYS PUT Observer class before the Subject class, because otherwise,</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>Our Subject class would not compile. This is because it has never seen Observer</em></p><p class="___1ehrlty f1s184ao fpgzoln"><em>before.</em><span>​‌</span></p><p class="___1ehrlty f1s184ao fpgzoln"><em>We generally want notify() to be parameterless</em><span>​‌</span></p>
28
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Refactor the code to use the Observer Design Pattern.</strong></span></p>

Refactor the code to use the Observer Design Pattern.

knowt flashcard image
29
New cards

What are the symbols for public, protected, & private in a UML Diagram?

+ is public

- is private

# is protected

30
New cards

What is the structure of a UML Diagram like?
Explain using the example of:
class: Animal, public method: speak, private data: name


<p></p>
31
New cards

What are all the UML symbols you need to know?

knowt flashcard image
32
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What is the problem with the following code?</strong></span></p>

What is the problem with the following code?

It violates the Open/Closed principle. Each time you want to add a new check, you have to modify the original class. Eventually, you end up adding so many checks that you create a monster function.

33
New cards

What is the Chain of Responsibility?

The Chain of Responsibility Pattern is a pattern that passes a request through a sequence of handler objects. Each handler performs one responsibility and then decides whether to stop processing or pass the request to the next handler in the chain.

34
New cards

What problem does the Chain of Responsibility Solve?

It solves the problem of processing a request that requires multiple different independent validations or steps. It separates each into its own handler class, which makes the system easier to maintain.

35
New cards

When should you use Chain of Responsibility?

Whenever one request must go through multiple processing steps.

36
New cards

How is the Chain of Responsibility implemented?

It is implemented by:

  • Creating an abstract Handler class that contains a handle() method and a reference to another Handler.

  • Concrete Handler classes inherit from the abstract base Handler class and implement a specific processing step.

  • Each handler can process the request and pass it to the next handler by calling nextHandler→handle()


37
New cards

What are the advantages of using Chain of Responsibility?

  1. It allows for Smaller Classes

  2. It also creates handlers that can be reused (for example, reusing the same handlers in other forms)

  3. It allows for flexible ordering, where you can change the order of responsibilities in the chain; For example, going from Student → Course → Fees or Fees → Course → Student


38
New cards

What are the disadvantages of using Chain of Responsibility?

  1. It can lead to more classes being created.

  2. It can be easy to make a mistake and accidentally miss one of the handlers when assigning the nextHandler pointer. For example: doing firstHandler.setNextHandler(nullptr); by accident.


39
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What does the Chain of Responsibility state that we should do for the following class?</strong></span></p>

What does the Chain of Responsibility state that we should do for the following class?

It states that we should break this large process down into several smaller classes. Particularly, that we should create a separate class for each individual check.

So one class to check and see if the course still exists, one class to check if the student is valid, one class to check if fees have been paid, etc.

40
New cards

Describe how classes are broken up in the Chain of Responsibility.

The Chain of Responsibility breaks up a large class by first creating a Base Handler class. The Handler class contains a pointer to the next Handler in the chain. It also contains two methods: setNextHandler and a virtual function called handle().

The next Handler is generally a specific version of the Base Handler to perform a specific function. This next Handler

41
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Explain each line of code in the following example showing chain of responsibility.</strong></span></p>

Explain each line of code in the following example showing chain of responsibility.

knowt flashcard image
42
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Refactor the following code so that it applies the Chain of Responsibility.</strong></span></p>

Refactor the following code so that it applies the Chain of Responsibility.

knowt flashcard image
43
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Refactor the following code so that it applies the Chain of Responsibility.</strong></span></p>

Refactor the following code so that it applies the Chain of Responsibility.

knowt flashcard image
44
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Convert the following into a UML Diagram</strong></span></p>

Convert the following into a UML Diagram

45
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Convert the following into a UML Diagram</strong></span></p>

Convert the following into a UML Diagram

46
New cards

What is the Strategy Design Pattern?

The strategy design pattern is a pattern we use when we have multiple different ways of doing the same task.

It encapsulates each algorithm, or each alternative of doing the same thing in its own individual class. This way, you can swap the algorithms and have them be interchangeable at runtime, which supports the Liskov Substitution Principle.

47
New cards

How is the Strategy Design Pattern implemented?

It is implemented by:

  • Creating a General Strategy class with a name that describes what type of algorithm we are dealing with.

  • This General Class should contain: a virtual method describing the action to be performed

  • Multiple concrete Strategy classes should be created for each variation of the algorithm.

  • A Context class that stores a pointer to a Strategy object and uses it to perform the operation.


48
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What is the problem with the following example?</strong></span></p>

What is the problem with the following example?

The problem is that you have to modify the original class each time you want to add a mode of travel. This violates the Open/Closed Principle.

49
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Describe the most important lines of code in the following example of the Strategy Pattern.</strong></span></p>

Describe the most important lines of code in the following example of the Strategy Pattern.

50
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Fix the code by implementing the Strategy Design Pattern.</strong></span></p>

Fix the code by implementing the Strategy Design Pattern.

knowt flashcard image
51
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Fix the code by implementing the Strategy Design Pattern.</strong></span></p>

Fix the code by implementing the Strategy Design Pattern.

knowt flashcard image
52
New cards

What are the Advantages of Strategy?

It supports the Open/Closed Principles because it allows you to add new algorithms without modifying existing code.

It gets rid of long conditional statements like:
if(payment type == “Credit”)

if(payment type == “Cash”)…

It allows for algorithms to be swapped at runtime.

It promotes the Single Responsibility Principle because each Strategy class is responsible for only one algorithm.

53
New cards

What are the Disadvantages of Strategy?

It creates more classes

It forces the client class to choose a strategy (they have to choose either between things like credit card, paypal, etc)

It may be overkill for simple problems

Strategies must all implement the same general operation (for example, payment processing)

54
New cards

What is the State Design Pattern?

The State Design Pattern is a Pattern that allows an object to change its behavior when its internal state changes. The behavior for each state is stored in separate State classes.

55
New cards

What problem does the State Design Pattern solve?

The State Design Pattern solves the problem of objects whose behavior changes significantly depending on their current state. As more states are added, the conditional statements appear in more methods and become harder to maintain.

For example:

if(state == “Happy”)

else if(state == “Sad”)

else if(state == “Excited”)

56
New cards

How is the State Design Pattern implemented?

It is implemented by:

  • Creating an abstract State interface that defines all the behaviors which may vary by state.

  • Creating multiple State classes that inherit from this interface and provide different implementations of those behaviors.

  • Creating a Context class, which stores a pointer to the current State object and decides behavior. When the Object’s state changes, the Context replaces the current State object with another State object.


57
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What is the problem with the following code?</strong></span></p>

What is the problem with the following code?

The problem is that each time we add a new state, say: Angry, Sad, Excited, we have to modify existing methods and add more else blocks. This violates the Open/Closed Principle.

58
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Describe how the following code solves the state problem.</strong></span></p><p><span style="color: rgb(255, 6, 159);"><strong>Describe each line of code.</strong></span></p>

Describe how the following code solves the state problem.

Describe each line of code.

It solves the state problem by creating a separate class for each state. Each individual state class contains methods that behave differently according to that current state.

<p>It solves the state problem by creating a separate class for each state. Each individual state class contains methods that behave differently according to that current state.</p>
59
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>Implement the main method for the following State class.</strong></span></p><p><span style="color: rgb(255, 6, 159);"><strong>Make sure to include both a Sad and Happy state.</strong></span></p>

Implement the main method for the following State class.

Make sure to include both a Sad and Happy state.

knowt flashcard image
60
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What is the problem with the following code?</strong></span></p>

What is the problem with the following code?

The problem is that each time we add a new state, we have to go in and modify the methods with a new else block to create a new variation of the same behavior for a different state.

This violates the Open/Closed Principle.

61
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>How can we implement the State Design Problem in the following code?</strong></span></p>

How can we implement the State Design Problem in the following code?

knowt flashcard image
62
New cards

What Mathematical Concept is the State Design Pattern Based on?

Finite State Machines

63
New cards

When should we use the State Design Pattern?

We should use it whenever the same object needs to behave differently at different times, depending on what state it is in.

64
New cards

What problem does the State Design Pattern solve?

The State Design Pattern solves the problem of large conditional blocks that need to be continuously added to methods in order to accommodate variations of a behavior for a particular state.

65
New cards

What are the Advantages of the State Design Pattern?

It follows the single responsibility principle, because each state class only contains behaviors pertaining to that state.

It follows the open/closed principle, because it prevents methods from needing to be modified in order to add variations of a behavior.

It eliminates large conditional statements

It makes state-dependent behavior easier to maintain

66
New cards

What are the Disadvantages of the State Design Pattern?

It creates more classes

It can be overkill for simple objects

State transitions can become complicated as the number of states grows

67
New cards

How is State different from Strategy?

The Strategy Design Pattern is for encapsulating multiple algorithms, and creating separate Strategy classes for each Algorithm, allowing you to select one at runtime.

Whereas the State Design Pattern is for encapsulating state-defined behavior into one class, then creating State classes for each state. It allows an object’s behavior to change automatically when its state changes.

In the Strategy Design Pattern, the behavior never changes, it is just implemented in a different way. For example, you may be trying to calculate routes, but each in a different way: cycling, walking, running, etc.

Whereas in the State Design Pattern, the behavior changes according to the state. It is implemented differently based on the state. For example, barking may be different based on the current state: happy, sad, angry, etc.

In the Strategy Design Pattern, Strategies generally do not know about each other. For example, DrivingStrategy knows nothing about WalkingStrategy, they are each independent alternatives.

Whereas in the State Design Pattern, different States do know about each other. This is because one state is usually involved in the transition to the next state. For example, HappyState may transition the object into SadState. This also makes sense because the State Design Pattern is based on Finite State Machines.

Also, in the State Design Pattern, State classes can hold a reference to the Context class. For example, DogState might hold a reference to the Context class, Dog, for example. But this is not as likely to happen in the Strategy Design class.

68
New cards

What is the Mediator Pattern?

The Mediator Pattern is when we centralize communication between multiple objects by introducing a separate middleman object called the Mediator that allows for communication between them.

69
New cards

What problem does the Mediator Design Pattern Solve?

The Mediator Design Pattern solves the problem of excessive coupling between multiple objects that need to communicate with one another. As more components are added to a system, communication can become more and more complicated because of all the dependencies there are between objects. So the Mediator Design Problem solves this.

For example:

You may have relationships between the Username Field, Password Field, Login Button, and Status Label that all need to communicate with each other.

If every component references every other component, suddenly the relationships become very complicated.

Imagine:
Username → Password

Username → Login Button

Username → Status Label

Password → Login Button

Password → Status Label

Login Button → Status Label (and vise versa for all the relationships)

All of these relationships would be incredibly complicated to maintain without a mediator.

70
New cards

How is the Mediator Pattern implemented?

The Mediator Pattern is implemented by:

  • Creating a Mediator interface

  • Creating a Base Component

  • Creating Concrete Mediators that are


71
New cards
<p><span style="color: rgb(255, 6, 159);"><strong>What is the problem with the following code? </strong></span></p>

What is the problem with the following code?

The problem is that TrafficLight currently knows about Car. So later, if we want to add Pedestrian Crossing or a Camera System, TrafficLight will need to know about those too. This means that the TrafficLight class becomes increasingly more coupled.

72
New cards
knowt flashcard image