Week 6/7 Flashcards

1
Q

Various Degrees of Undo:

A
  1. Undo last (one level)2. Limited undo (fixed nr of levels)3. Arbitrary undo (limited by memory only)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Various Degree of Redo:

A
  1. Not available2. Redo last3. Limited redo4. Arbitrary undo
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Solutions for Undo Redo Facility

A
  1. Storing full model states:- one stack of states for undo and one for redo- requires the ability to clone and restore a given state- pro is that it is simple, but there is a performance loss when the state is large
  2. Storing state-changing commands:- user invokes commands via GUI, changing data in the models- these commands are stored in two stacks, one of executed commands for undo, and one of undone-but-redoable commands for redo- commands are stored using Command design pattern- commands must have the ability to revert functionality
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Command design pattern

A

encapsulates a request as an object, allowing for parameterization of clients with different requests, queuing of requests, and the ability to support undoable operationsaims to decouple the sender of a request from the object that performs the request, promoting flexibility, extensibility, and better organisation of code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Components of Command Design Pattern

A
  1. Command:- interface/abstract class that declares the execute method2. Concrete Command:- implements Command interface and represents a specific command with a set of actions- holds a reference to the object on which the actions should be perceived (the receiver)3. Invoker:- class responsible for invoking commands- holds a reference to a command object and calls its execute method4. Receiver:- class that performs the actual operation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Code Example for Command Design Pattern

A

// Command interfaceinterface Command { void execute();}// Concrete command classesclass LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOn(); }}class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOff(); }}// Receiver classclass Light { void turnOn() { System.out.println(“Light is ON”); } void turnOff() { System.out.println(“Light is OFF”); }}// Invoker classclass RemoteControl { private Command command; void setCommand(Command command) { this.command = command; } void pressButton() { command.execute(); }}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Client Code Example for Command Design Pattern

A

// Client codepublic class CommandPatternExample { public static void main(String[] args) { // Creating instances of the receiver and concrete command classes Light light = new Light(); Command lightOn = new LightOnCommand(light); Command lightOff = new LightOffCommand(light); // Creating an invoker and associating commands RemoteControl remote = new RemoteControl(); remote.setCommand(lightOn); // Pressing the button, which will execute the associated command remote.pressButton(); // Changing the command associated with the invoker remote.setCommand(lightOff); remote.pressButton(); }}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Relation of Command Design Pattern to Strategy Design Pattern

A

command interface can be viewed as a strategy interface with concrete commands as concrete strategiesinvoker plays role of context in strategy pattern and only knows about abstract commandclient plays client role of strategy pattern and selects/creates concrete commands

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Undo via Command Design Pattern

A

Invovles providing each concrete command with a revert method to revert the effect of execute.Moreover, a command undo stack must be introduced.The controller creatses Command objects, executes them, and then pushes them onto the undo stack.Undo is implemented by popping a command from the undo stack and invoking its revert method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Compound Command Design Pattern

A

allows clients to treat a group of commands as a single commandparticularly useful for implementing undo/redo functionality or for managing complex sequences of operations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Components of Compound Command Design Pattern

A
  1. Command Interface:- an interface/ abstract class with an execute method2. Concrete Command:- implements the Command interface, representing individual commands- holds a reference to a receiver, on which the action is performed3. Receiver:- represents the object that performs the actual actions4. Compound/Macro Command:- implements the Command interface, but internally manages a collection of other commands- its execute method executes the execute methods of all the commands it holds references too5. Invoker:- invokes the actual compound command
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Code Example for Compound Command Pattern

A

// Command interfaceinterface Command { void execute();}// Concrete command classesclass LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOn(); }}class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOff(); }}// Compound command classclass MacroCommand implements Command { private List commands; public MacroCommand() { commands = new ArrayList<>(); } public void addCommand(Command command) { commands.add(command); } @Override public void execute() { for (Command command : commands) { command.execute(); } }}// Receiver classclass Light { void turnOn() { System.out.println(“Light is ON”); } void turnOff() { System.out.println(“Light is OFF”); }}// Invoker classclass RemoteControl { private Command command; void setCommand(Command command) { this.command = command; } void pressButton() { command.execute(); }}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Client Code for Compound Command pattern

A

public class CompoundCommandExample { public static void main(String[] args) { // Creating instances of the receiver and concrete command classes Light light = new Light(); Command lightOn = new LightOnCommand(light); Command lightOff = new LightOffCommand(light); // Creating a compound command and adding individual commands to it MacroCommand macroCommand = new MacroCommand(); macroCommand.addCommand(lightOn); macroCommand.addCommand(lightOff); // Creating an invoker and associating the compound command RemoteControl remote = new RemoteControl(); remote.setCommand(macroCommand); // Pressing the button, which will execute the associated compound command remote.pressButton(); }}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Backtracking

A

an algorithmic approach that incrementally builds and explores potential solutions to a problem, abandoning and backtracking when it determines that a partial solution cannot be completed to a valid solutionoften used for solving constraint satisfaction problems by systematically exploring the search space of possibilities

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Backtracking Algorithm for Puzzle Assistant

A
  1. Apply reasoning to find “forced” digits.2. Find an open cell c. If not found and the puzzle is valid, then puzzle is solved. If not found and the puzzle is not valid, then backtrack (if possible).3. If open cell c found, for each possible cell state s, speculatively, set c to s, and if state still valid, solve remainder of puzzle recursively.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Concurrency

A

the simultaneous execution of multiple tasks or processes that can progress independentlyIn GUI programming, concurrency is crucial for maintaining responsive user interfaces, allowing tasks like user input handling, background processing, and UI updates to occur concurrently without blocking the main thread, ensuring smooth interaction and responsiveness for the end user

17
Q

Some Dangers of Concurrency

A
  1. Operation interleaving is non-deterministic and hence not reproducible, hindering reasoning, testing, and debugging.
  2. Thread Interference - occurs when two or more threads access shared data concurrently, and the final outcome is dependent on the timing or interleaving of their executions.
  3. Memory consistency errors - occurs when different threads have inconsistent views of shared data due to the lack of proper synchronisation mechanisms
  4. Race conditions - occurs when the behaviour of a program depends on the relative timing or interleaving of multiple threads, and the result is unpredictable or incorrect.
18
Q

SwingWorker Class

A

part of the Swing concurrency framework introduced to facilitate background tasks and updates in GUI applications without freezing the user interfacemakes it easy to run some code in a background thread, and still interact with it in a controlled way

19
Q

Steps Defined by SwingWorker Class

A

SwingWorker Class uses Template Method pattern to let clients define the following:
1. which computation to do in background doInBackground()
2. optionally: how to handle intermediate results: process()
3. what to do with the final result: done()

20
Q

How to Use SwingWorker

A

T is the type of result returned by SwingWorker’s doInBackground and get methods (void can be used to ignore result)

A new instance of SwingWorker must be created for each run of background task.

Once a new instance of SwingWorker is created, it is executed using the .execute() method.

@Override T doInBackground() - method that implements the background task, called automatically in a new thread, after execute()

@Override void done() - implement finalisation here, called automatically in GUI thread when background task ends.get() method can be called to get the result of the doInBackground() operation.cancel() used to cancel the execution of the background task

21
Q

Two Methods to use SwingWorker thread .cancel():

A
  1. In GUI thread, call worker.cancel(true) to request cancellation of the background task.In background task, either

a. Regularly inspect Thread.interrupted() and terminate if true as this means that an interrupt signal has been sent to the thread.

b. If your background task involves one of the methods Thread.sleep/join/wait then note that they will throw an InterruptedException when run on an interrupted thread, and catch this exception, terminating your background task.

  1. In GUI thread, call worker.cancel(false) to request cancellation of background task.In background task, regularly inspect worker.isCancelled() and terminate if true.
22
Q

.cancel(true) vs .cancel(false)

A

.cancel(true) - method is used to request cancellation of the SwingWorker and, if specified, to interrupt the thread that is currently running the background task- to be used when immediate termination and interruption of the background thread are required, especially if the thread is blocked or waiting.

.cancel(false) - method is used to request cancellation of the SwingWorker without interrupting the thread that is currently running the background task- when a more graceful termination is acceptable, allowing the background task to complete its current operation before checking for cancellation

23
Q

State Design Pattern

A

behavioural design pattern that allows an object to alter its behaviour when its internal state changesparticularly useful when an object transitions between different states, and its behaviour depends on the current state

24
Q

Components of State Design Pattern

A
  1. State Interface:- interface that defines the behaviour that different states should implement2. Concrete State Classes:- classes that implement the State Interface- each class provides a specific implementation of the methods of State interface, representing behaviour associated with that state3. Context Class:- maintains a reference to the current state and delegates state-specific behaviour to it- has a setState(State state) method that allows changing the current state dynamically- has different methods that call the relevant methods on the current state
25
Q

Example Code for State Design Pattern

A

class Context { private State state; public Context() { // Set the initial state this.state = new StateA(); } public void setState(State state) { this.state = state; } public void request() { state.handle(this); }}// State interfaceinterface State { void handle(Context context);}// Concrete State classesclass StateA implements State { @Override public void handle(Context context) { System.out.println(“Handling request in State A”); // Transition to a different state if needed context.setState(new StateB()); }}class StateB implements State { @Override public void handle(Context context) { System.out.println(“Handling request in State B”); // Transition to a different state if needed context.setState(new StateA()); }}

26
Q

Client Code Example for State Design Pattern

A

// Client codepublic class StatePatternExample { public static void main(String[] args) { Context context = new Context(); // Perform a series of requests, observing state transitions context.request(); // Output: Handling request in State A context.request(); // Output: Handling request in State B context.request(); // Output: Handling request in State A }}

27
Q

Three Components of Model-View-Controller Design Pattern

A
  1. Model:- represents application’s data and business logic- responsible for managing the data, processing user inputs, enforcing business rules- represents the core functionality of the application without concern for how it is presented or how the user interacts with it
  2. View:- displays the information from the Model and provides a user interface for the interaction- the View receives updates from the Model and reflects any changes in the user interface- however, does not directly interact with the data or handle user input processing as it delegates all these tasks to the Controller
  3. Controller: - handles user inputs, processes them, and updates the model accordingly- interprets user actions and initiates the appropriate changes in the Model or View- unlike the View, the Controller is responsible for handling user input and translating it into commands for the Model or the View- helps decouple the user interface from underlying logic
28
Q

Specific Workings of MVC Design Pattern

A
  1. User interacts with the View, providing some input.2. The View forwards the input to the Controller.3. Controller processes the input and updates the Model accordingly.4. The Model notifies the View about changes in the data.5. The View queries the Model for updated data and refreshes the user interface.
29
Q

MVC and Observer Pattern

A

Model acts as the Subject/Observable, maintaining a list of observers (typically the Views) that need to be notified of any changes in its stateWhen there is a change in the Model’s data, it notifies all registered observers about the changeThe View acts as the Observer in the design pattern, registering itself with the Model as an observer during initialisationThe View also provides an update mechanism that the Model can invoke when its state changesWhen the Model’s data is updated, it iterates through its list of observers, i.e., views and calls their update methodsEach View, being an observer, receives the notification and can query the Model for the updated data

30
Q

SOLID Object Oriented Design Principle

A
  1. Single Responsibility Principle2. Open Closed Principle3. Liskov Substitution Principle4. Interface Segregation Principle5. Dependency Inversion Principle
31
Q

Two Ways of Reusing a Class

A
  1. Regular Client Code (including use by composition)- you use a class by creating new objects of that class and interacting with them through their public interface- contracts usually specify this interface, and only public members can be accessed2. Code in Subclass that Extends the Class:- reuse a class by creating a subclass that extends it- subclass can access and reuse superclass members, contracts are harder to specify, and subclass can access protected members
32
Q

Open-Closed Principle

A
  1. Modules should be open for extension via inheritance.2. Modules should be closed for modification by clients- instance variables should be private, or at least protected- code should not be modified in order to add or adapt functionality; instead, subclasses should be used- e.g., through Adapter, Decorator, State design patterns
33
Q

Interface Segregation Principle

A

states that a class should not be forced to implement interfaces it does not useencourages the creation of specific, focused interfaces tailored to the requirements of the classes that implement them, promoting cleaner and more modular designs

34
Q

Example of Interface Segregation Principle - Client Perspective

A

Given a class Service with a number of methodsAnd two clients - ClientA, ClientBThat each only use two of those methods -Method1A, Method2A and Method1B, Method2B, respectively.Instead of loading a class with all the methods that different clients need - i.e., service class and making each client depend on the complete interfaceCreate specific interfaces for each kind of client - InterfaceA, InterfaceB - make each client dependent on its interface, and implement all interfaces in the class, i.e., class Service implements InterfaceA, InterfaceB.

35
Q

Functional Interface

A

an interface that defines exactly one abstract method@FunctionalInterface put before interface heading checks this

36
Q

Lambda Expression

A

concise way to express anonymous functions or methods, primarily used to implement functional interfacesallows the definition of a method body directly within the code, often reducing verbosity and enhancing readability

37
Q

Lambda Expression Example

A

// Traditional anonymous classRunnable traditionalRunnable = new Runnable() { @Override public void run() { System.out.println(“Hello, world!”); }};// Lambda expression equivalentRunnable lambdaRunnable = () -> System.out.println(“Hello, world!”);