Command Pattern & Singleton - LOG121

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

In the Command pattern, what is the primary purpose of encapsulating actions into objects?

  • To simplify the user interface design.
  • To improve the performance of the application by caching results.
  • To reduce the number of classes in the application.
  • To allow actions to be passed as parameters, queued, and logged. (correct)

In the context of the Command pattern, what role does the 'Invoker' play?

  • It holds and triggers the command to execute at a specific time. (correct)
  • It defines the interface for all command objects.
  • It creates the command object and sets its parameters.
  • It executes the command directly.

Within the Command pattern, what is the responsibility of the 'Receiver'?

  • To define the interface for executing commands.
  • To create command objects.
  • To perform the actual operation when the command is executed. (correct)
  • To manage the command queue.

Consider a scenario where multiple UI buttons in an application perform similar actions, like saving a document, but on different file types. How could the Command pattern be utilized effectively?

<p>Implement separate command classes for each file type, all implementing a common Command interface. (A)</p> Signup and view all the answers

In a text editor application, which component would most appropriately be the 'Receiver' in a Command pattern implementation for text formatting operations?

<p>The text editor's core logic that manipulates the document's text. (A)</p> Signup and view all the answers

What is the main goal of the Singleton pattern?

<p>To ensure that a class has only one instance and provide a global point of access to it. (A)</p> Signup and view all the answers

Which of the following is a crucial characteristic of a Singleton class?

<p>It must have a private constructor to prevent external instantiation. (B)</p> Signup and view all the answers

Why is the Singleton pattern often considered an anti-pattern in certain contexts?

<p>It encourages high coupling and makes testing more difficult. (B)</p> Signup and view all the answers

In a multi-threaded environment, what is a key consideration when implementing the Singleton pattern?

<p>Ensuring thread safety during the creation of the single instance. (D)</p> Signup and view all the answers

Consider a system that requires a single point of access to a configuration manager. How would you ensure that only one instance of the ConfigurationManager class exists?

<p>Implement the Singleton pattern with a private constructor and a static <code>getInstance</code> method in the <code>ConfigurationManager</code> class. (B)</p> Signup and view all the answers

Which of the following best describes the relationship between the 'Action' interface and 'ActionListener' in the Swing framework, as it relates to the Command pattern?

<p>'Action' extends 'ActionListener', providing a more specific implementation for handling actions. (C)</p> Signup and view all the answers

What is the primary advantage of using the 'Action' interface in Swing for handling UI events?

<p>It centralizes the action logic and allows it to be reused across multiple components. (A)</p> Signup and view all the answers

In the context of Swing, how does associating an 'Action' with a component (like a JButton) affect the component's state?

<p>The component's state is automatically updated to reflect the state of the associated 'Action' (e.g., enabled/disabled). (D)</p> Signup and view all the answers

Which of the following scenarios best illustrates the use of the Command pattern in a GUI application?

<p>Implementing an undo/redo feature by storing command objects. (C)</p> Signup and view all the answers

What problem does the Command pattern solve in the context of UI design with components like buttons?

<p>It decouples the UI components (invokers) from the actions they trigger (receivers). (C)</p> Signup and view all the answers

What is the role of the execute() method in the Command pattern?

<p>To perform the operations associated with the command. (D)</p> Signup and view all the answers

In an application using the Command pattern, how would you implement a macro (a series of commands executed in sequence)?

<p>By storing command objects in a list and iterating through them, calling <code>execute()</code> on each. (B)</p> Signup and view all the answers

What is the significance of the private constructor in the Singleton pattern?

<p>It prevents external classes from instantiating the Singleton class directly. (C)</p> Signup and view all the answers

How does the Singleton pattern help in reducing global variables?

<p>By providing a controlled access point to a single instance, instead of multiple global instances. (A)</p> Signup and view all the answers

When using the Singleton pattern, what is the purpose of the static getInstance() method?

<p>To provide a global access point to the single instance of the Singleton class. (A)</p> Signup and view all the answers

What is the primary benefit of having a single instance of a spooler (print queue) in a system, which is often implemented using the Singleton pattern?

<p>It ensures that print jobs are processed in the order they are received, avoiding conflicts and resource contention. (D)</p> Signup and view all the answers

In the given code snippet for the SingleRandom class, what is the purpose of the setSeed(int seed) method?

<p>To reset the random number generator with a specific starting value. (D)</p> Signup and view all the answers

What is a potential disadvantage of using the Singleton pattern excessively in an application?

<p>It can create tight coupling between different parts of the application. (B)</p> Signup and view all the answers

If a class uses only static methods and cannot be instantiated, such as the Math class in Java, can it be considered a Singleton?

<p>No, because the Singleton pattern requires a private constructor and a static instance variable. (B)</p> Signup and view all the answers

What is the purpose of the Java Runtime class?

<p>Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. (A)</p> Signup and view all the answers

In the context of the Command pattern, which participant is responsible for storing and executing the commands?

<p>The Invoker (B)</p> Signup and view all the answers

Which of the following represents a real-world analogy for the Command pattern?

<p>A remote control that operates various devices. (B)</p> Signup and view all the answers

In the Singleton pattern, which element is primarily in charge of ensuring the uniqueness of the instance?

<p>The private constructor. (D)</p> Signup and view all the answers

Which of the following is NOT an advantage commonly associated with the Singleton pattern?

<p>Easy extension to multiple instances. (D)</p> Signup and view all the answers

In a text editor application, 'Cut', 'Copy', and 'Paste' operations can be effectively implemented using which design pattern?

<p>Command (D)</p> Signup and view all the answers

Consider a scenario where you need to implement a logging mechanism in an application. Why might the Singleton pattern be a suitable choice for managing the logger?

<p>To ensure that all parts of the application use the same logger instance, configuring the writing in one single place. (B)</p> Signup and view all the answers

How does the Command pattern support the "Open/Closed Principle" (a class should be open for extension but closed for modification)?

<p>By allowing new commands to be added without modifying existing command classes or the invoker. (C)</p> Signup and view all the answers

Which scenario exemplifies a suitable use case for the Singleton pattern?

<p>A print spooler in an operating system, managing print jobs to a single printer. (A)</p> Signup and view all the answers

How does the Command Pattern improve testability in software systems?

<p>It makes easier to implement test cases for undoable action. (A)</p> Signup and view all the answers

Flashcards

Command Pattern

Encapsulates actions as objects, decoupling the invoker from the receiver.

Command Interface

Defines an interface with an execute() method for running a command.

Concrete Command

A class representing a specific action implementing the Command interface.

Invoker

Object that knows how to trigger a command.

Signup and view all the flashcards

Receiver

The object on which the command operates.

Signup and view all the flashcards

Advantage of Command Pattern

Removes coupling between the invoker and the object that carries out the action.

Signup and view all the flashcards

Singleton Pattern

Limits a class to a single instance with global access.

Signup and view all the flashcards

Purpose of Singleton

Ensures only one instance, provides global access.

Signup and view all the flashcards

Implementation of Singleton

A private constructer, a static instance of itself, and a public static method to get instance.

Signup and view all the flashcards

Advantages of Singleton

Controlled access, reduced globals, extensible.

Signup and view all the flashcards

Runtime Class (Java)

java.lang class that can only have have one instance per JVM.

Signup and view all the flashcards

Study Notes

Command Pattern and Singleton

  • LOG121 presents the Command and Singleton design patterns, instructed by Souad Hadjres

Plan

  • The presentation will cover the Command Pattern and the Singleton Pattern

Design Problem Example

  • The Swing framework offers graphical objects such as buttons
  • These graphical objects emit requests when a user interacts with them
  • Swing's designers didn't know which objects would receive the request or how it would be executed
  • Applications using Swing know which request is emitted and which object should react to it

Command Pattern Example

  • Shows a simple application with buttons "Ouvrir" (Open) and "Quitter" (Quit)
  • ActionListener interface is implemented by the Application class
  • The AbstractButton class has an addActionListener method to which the Application can subscribe

Sample Code

  • Java code is used to demonstrate how Swing buttons trigger actions through the ActionListener interface

Design Problem

  • The actionPerformed method in the example application is not very practical and can quickly become complex
  • The application may end up with many methods and too many responsibilities
  • The same action can be executed in different ways (e.g., from a button, a menu item)
  • Actions may not be permissible in certain contexts
  • For example, "paste" without having "copied" or "cut"
  • Indicates how Swing’s designers addressed these issues

Solution to the Problem

  • The Action interface extends ActionListener
  • An action can have a name and an associated icon
  • An action can be associated with different interface elements
  • An action can be activated or deactivated
  • One action can declare another action as its opposite

Code Solution

  • Code is written so when an action is attached to a component using the setAction method
  • The component's state is updated to match the action's state
  • The Action object is registered as a listener on the component
  • When the action's state changes, the component's state is adjusted accordingly

Solution to the Problem

  • Actions to be executed are encapsulated in objects that extend the AbstractAction class
  • These objects handle the execution of the actions
  • They can be used by multiple graphical components
  • States (enabled, disabled) can be associated with them
  • G actions managed, composed, and reverted (undo, redo)
  • Decouples the source object of the action from the object on which the action is executed

CommandTester Code

  • Demonstrates a command tester using GreetingAction extending AbstractAction

The Command Pattern

  • Emphasizes the implementation of commands as objects for associating information or tracking for re-execution, undo, or grouping
  • Focuses on decoupling the object initiating the command from the one receiving it

Command Pattern Details

  • Involves defining a Command interface with a method to execute the command
  • The interface defines methods for accessing the command's state
  • Each concrete class implements the interface and represents a command
  • Invoking the command means calling the execution method

Command Pattern Structure

  • Simplified structure highlights the Client and Command interfaces, and the concrete commands without showing the objects being acted upon

Command Pattern Structure

  • Full structure used in the course, consists of the Client, Invoker, Command, Receiver, and ConcreteCommand elements

Command Pattern: Roles

  • Clarifies the roles within the Command Pattern, in terms of their equivalent in a Swing example

Application Example

  • Shows an example of applying the Command Pattern in an application
  • Highlights the relationships between the Client, Receiver, Invoker and Commands

Object Interactions

  • Client creates a concrete command, specifies its receiver, and configures an invoker with a concrete command
  • The invoker calls the Execute method of the ConcreteCommand object
  • Concrete command's execute method invokes the receiver object’s operations to fulfill the request

Command Pattern Application

  • A calculator application supports basic operations, and also has undo

Code Example

  • Example code for command pattern

Implementation Code

  • Java code defines the interfaces and classes
  • Includes ICommand, Addition, Multiplication, Calculateur (Receiver), and Usager (Invoker) implementing the command pattern for basic calculator operations

Advantages of the Command Pattern

  • Helps decouple the object invoking a command from the object that knows how to perform it
  • All command objects have a common interface for invocation
  • Allows assembling command objects into a composite command
  • Helps control their sequencing
  • Allows the insertion into queues
  • Also allows to implement reversion of operations (Undo and Redo)

Singleton Pattern

  • Overview of what is coming next

Design Problem Example: Singleton Pattern

  • Many situations require only one instance of a class with global access to it
  • Examples include a spooler, an object factory, or a class managing database access

Examples of Problems: Random Number Generation

  • Example program which uses multiple classes and needs random numbers to be generated
  • Example uses number generation using seeds and a set calculation
  • To debug the number generation, the program needs to debug using the same sequence of numbers

Solution

  • Ensure there is only one random number generator
  • A class is designed with a private constructor and the class provides a static method that returns the instance of the class

The Singleton Pattern

  • Ensures a class has only one instance and provides a global point of access to it

Singleton

  • Entrusts the class itself with the responsibility of ensuring the uniqueness of its instance
  • Class should define a private constructor that returns a reference the instance, only constructing a single instance of itself
  • The class controls how and when client classes access it

Singleton Structure

  • Shows the structure of a Singleton class with a private uniqueInstance attribute, a private constructor, and a public getInstance() method

Pattern Advantages

  • Controlled access to a single instance
  • Reduces global variables
  • Permits extension to single instance
  • Can be adapted for a variable number of instances

Patterns Disadvantages

  • Java's Math class defines methods for performing basic numeric operations, and exclusively defines static methods
  • The Math class cannot be instantiated and cannot be extended
  • Therefore, the pattern is not singleton: rather it groups all the functions together.

Application Example

  • Demonstrates the Runtime class as a Singleton class in Java.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Shell Pattern Matching Quiz
5 questions
Command Economy Flashcards
20 questions

Command Economy Flashcards

ChivalrousSard7112 avatar
ChivalrousSard7112
Use Quizgecko on...
Browser
Browser