Week 5 Flashcards

1
Q

Textual User Interface

A
  • typically character-based and rely on text characters for communication
  • possesses a textual interface where users interact with the system by typing text commands
  • user needs to understand and input specific commands or sequences of text to perform tasks
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Graphical User Interface

A
  • interaction is more visual and intuitive, with graphical elements such as icons, buttons, windows, and menus- user can generate events through keyboard, mouse, etc.- the main event loop dispatches events by calling appropriate event handling methods (event handlers)- program consists of initialisation code and event handlers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Event in GUIS

A

a user-initiated action, such as a mouse click or keyboard input, which triggers a specific response or function within the graphical user interface

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

Main Event Loop

A

a continuous program structure that waits for and dispatches user input events, updating the graphical interface and executing corresponding functions to provide a responsive and interactive user experience

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

Event Handlers

A

functions or routines that are programmed to respond to specific user-initiated events, such as mouse clicks or keyboard inputs, by executing predetermined actions or processes within the graphical user interface

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

Listeners

A

an object or function that is programmed to detect and respond to specific events triggered by user interactions with graphical components, such as buttons or text fields

to handle events, a listener must implement the relevant listener interface(s) and must be registered with the component

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

Different Components of GUIs

A

frames - the top-level containers in a GUI, serving as the main application window that holds other components

panels - containers used to organize and group other components within a GUI, helping to structure the layout

labels - used to display text or images, providing descriptive information in the GUI

buttons - interactive elements that users can click to trigger predefined actions or functions in the application
- check boxes - allow users to make binary choices (selected or unselected) by toggling a checkbox

text fields - areas where users can input and edit single lines of text, such as entering names or numbers

text areas - larger input areas that allow users to enter and edit multiple lines of text, suitable for longer pieces of information or messages

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

Handling Button Events

A
  1. Set up a button. E.g., JButton myButton = new JButton(“Click Me”);
  2. Create an ActionListener. E.g.,ActionListener myActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Code executed when button is clicked }};
  3. Attach ActionListener to the Button.E.g., myButton.addActionListener(myActionListener);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Replacing functionality at runtime through GUI

A

Can make use of checkboxes, using a switch statement based on the values of the these checkboxes to decide which of the methods will be called.

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

Suppose you have a generator that takes all of the outputs of a method and does something with them. If we would like to have the possibility of choosing what to do them in real-time based on GUI user-inputs, what could be some solutions?

A
  1. List:- let the generator (printer of method returns) return a list of all generated objects, and the client code can then process that list independently of the generator- however, enough memory will be needed to store the entire result and generation and processing won’t be able to take place concurrently
  2. Iterator:- offer the computation as an iterator, doing the client-part of the computation outside the generator so the core of the computation resides inside the iterator- however, harder to do for recursive computations, and can only supply functionality that handles each computed item
  3. Template Method Pattern:- generator algorithm is the template method- process algorithm is hook method, either abstract or with default implementation- client class subclasses the generator and overrides process with desired functionality- this can insert several steps in different places in generator, but client code can only be used with a specific generator
  4. Strategy Design Pattern:- specify the method void process(String s) in an abstract class or interface- implement it by overriding process() in a subclass- pass an object of this subclass to the generator (known as dependency injection DI)- this makes client code less coupled to generator, but there is more overhead
  5. Callbacks:- provide one or more methods as parrameter to the computation- this should provide ideal decoupling, and allows the client to define the processing to be done in the callback method
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Observer Design Pattern

A

behavioural design pattern where an object, known as the subject, maintains a list of dependents, called observers, that are notified of any changes in the subject’s state

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

Components of Observer Design Pattern

A
  1. Subject:- maintains a list of observers- provides methods to add and remove observers- provides a method to notify observers of changes in its state- could also be an abstract class/interface
  2. Observer:- an interface/ abstract class with an update method that is meant to respond to a change in the subject
  3. Concrete Subject:- has functionality of subject but with any additional, specific properties
  4. ConcreteObserver:- implements the observer interface- registers with a concrete subject to receive notifications- responds to updates initiated by the subject
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Code Example for Observer Design Pattern

A

// Subject interfaceinterface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers();}// Observer interfaceinterface Observer { void update(String message);}// Concrete subjectclass ConcreteSubject implements Subject { private List observers = new ArrayList<>(); private String state; public void setState(String newState) { this.state = newState; notifyObservers(); } @Override public void registerObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.update(state); } }}// Concrete observerclass ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + “ received an update: “ + message); }}

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

Client Code Example for Observer Design Pattern

A

// Client codepublic class Client { public static void main(String[] args) { // Creating a concrete subject ConcreteSubject subject = new ConcreteSubject(); // Creating concrete observers Observer observer1 = new ConcreteObserver(“Observer 1”); Observer observer2 = new ConcreteObserver(“Observer 2”); // Registering observers with the subject subject.registerObserver(observer1); subject.registerObserver(observer2); // Updating the state of the subject, which triggers notification to observers subject.setState(“New State”); }}

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

Facade Design Pattern

A

a design pattern looking to provide a simplified and unified interface to a set of interfaces or complex subsystem by creating a single, straightforward entry point for clients

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

Components of Facade Design Pattern

A
  1. Facade:- main entry point for the client to access the functionalities of the subsystem(s)- provides a simplified, higher-level interface that delegates the client requests to the appropriate substystem components- may hold objects of the subsytems in order to call operations on them
  2. Subsystem(s):- a set of classes or interfaces that perform the actual work- facade delegates client requests to the subsystem
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Code Example for Facade Design Pattern

A

// Subsystem componentsclass CPU { void start() { System.out.println(“CPU is starting”); } void execute() { System.out.println(“CPU is executing”); }}class Memory { void load() { System.out.println(“Memory is loading”); }}class HardDrive { void read() { System.out.println(“Hard Drive is reading”); }}// Facade classclass ComputerFacade { private CPU cpu; private Memory memory; private HardDrive hardDrive; public ComputerFacade() { this.cpu = new CPU(); this.memory = new Memory(); this.hardDrive = new HardDrive(); } // Facade method to start the computer public void startComputer() { cpu.start(); memory.load(); hardDrive.read(); cpu.execute(); System.out.println(“Computer started successfully”); }}

18
Q

Client Code for Facade Design Pattern

A

// Client codepublic class Client { public static void main(String[] args) { // Using the ComputerFacade to start the computer ComputerFacade computerFacade = new ComputerFacade(); computerFacade.startComputer(); }}

19
Q

Adapter Design Pattern

A

structural design pattern that allows the interface of an existing class to be used as another interfacei.e., enables classes with incompatible interfaces to work together by providing a wrapper/adapter that converts one interface into another, making the object compatible

20
Q

Components of Adapter Design Pattern

A
  1. Target:- the interface that the client code expects or depends on- the target defines the specific methods or operations that the client code uses
  2. Adaptee:- the existing class or interface that needs to be integrated into the system- has an interface that is incompatible with the client’s expectations (target)
  3. Adapter:- a wrapper class that implements the Target interface- holds an instance of the Adaptee class to call methods on that it gets as an argument- delegates calls to the methods of the target interface to the corresponding methods of the adaptee- makes adaptee’s interface compatible with the target interface
21
Q

Code Example for Adapter Design Pattern

A

// Target interfaceinterface Target { void request();}// Adaptee (existing class)class Adaptee { void specificRequest() { System.out.println(“Adaptee’s specificRequest called”); }}// Adapter class implementing the Target interfaceclass Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void request() { adaptee.specificRequest(); }}

22
Q

Client Code for Adapter Design Pattern

A

Adaptee adaptee = new Adaptee();Target adapter = new Adapter(adaptee);adapter.request(); // calls a method of adaptee

23
Q

Decorator Design Pattern

A

structural design pattern that allows behaviour to be added to an individual object, either statically or dynamically, without affecting the behaviour of other objects from the same classused to extend or augment the behaviour of objects in a flexible and reusable way, providing an alternative to subclassing for extending functionality

24
Q

Components of Decorator Design Pattern

A
  1. Component:- the interface or abstract class that defines the common interface for all concrete components and decorators
  2. ConcreteComponent:- basic implementation of the component interface- represents the core functionality that decorators can extend
  3. Decorator:- abstract class or interface that implements the component interface- has a reference to a component and can dynamically add additional behaviour to the component
  4. ConcreteDecorator:- adds specific functionalities to the component it holds a reference to by overriding or extending its methods- multiple concrete decorators can be combined to create a variety of configurations
25
Q

Code Example for Decorator Design Pattern

A

// Component interfaceinterface Coffee { double cost(); String description();}// Concrete componentclass SimpleCoffee implements Coffee { @Override public double cost() { return 2.0; // Base cost of simple coffee } @Override public String description() { return “Simple Coffee”; }}// Decorator abstract classabstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee = decoratedCoffee; } @Override public double cost() { return decoratedCoffee.cost(); } @Override public String description() { return decoratedCoffee.description(); }}// Concrete decoratorclass MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } @Override public double cost() { return super.cost() + 0.5; // Additional cost for milk } @Override public String description() { return super.description() + “ with Milk”; }}// Concrete decoratorclass SugarDecorator extends CoffeeDecorator { public SugarDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } @Override public double cost() { return super.cost() + 0.2; // Additional cost for sugar } @Override public String description() { return super.description() + “ with Sugar”; }}

26
Q

Client Code for Decorator Design Pattern

A

Coffee simpleCoffee = new SimpleCoffee(); System.out.println(“Cost: “ + simpleCoffee.cost() + “, Description: “ + simpleCoffee.getDescription()); Coffee milkCoffee = new MilkDecorator(simpleCoffee); System.out.println(“Cost: “ + milkCoffee.cost() + “, Description: “ + milkCoffee.getDescription()); Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee); System.out.println(“Cost: “ + sugarMilkCoffee.cost() + “, Description: “ + sugarMilkCoffee.getDescription());

27
Q

Composite Design Pattern

A

structural design pattern that lets one compose objects into tree structures to represent part-whole hierarchiesallows clients to treat individual objects and compositions of objects uniformly

28
Q

Components of Composite Design Pattern

A
  1. Component:- a common interface or abstract class for all concrete components (leaf nodes) and their compositions (composite nodes)- declares the methods common to both leaves and composites
  2. Leaf:- basic building block of the hierarchy- represents an individual object that haas no children- implements the component interface

3.Interface:- complex object that can have children (leaves or other composites)- implements the component interface and defines methods to add, remove, and get child components- delegates all other operations to children

29
Q

Code Example Composite Design Pattern

A

// Component interfaceinterface Graphic { void draw();}// Leaf classclass Circle implements Graphic { @Override public void draw() { System.out.println(“Drawing Circle”); }}// Leaf classclass Square implements Graphic { @Override public void draw() { System.out.println(“Drawing Square”); }}// Composite classclass CompositeGraphic implements Graphic { private List graphics = new ArrayList<>(); // Adds the graphic to the composition void addGraphic(Graphic graphic) { graphics.add(graphic); } // Draws all the graphics in the composition @Override public void draw() { System.out.println(“Drawing Composite Graphic”); for (Graphic graphic : graphics) { graphic.draw(); } }}

30
Q

Client Code Example Composite Design Pattern

A

// Client codepublic class Client { public static void main(String[] args) { // Creating leaf objects Circle circle = new Circle(); Square square = new Square(); // Creating a composite object CompositeGraphic composite = new CompositeGraphic(); // Adding leaf objects to the composite composite.addGraphic(circle); composite.addGraphic(square); // Drawing the composite, which in turn draws the leaf objects composite.draw(); }}

31
Q

Dependency Inversion Principle

A

states that high-level modules should not depend on low-level modules; both should depend on abstractionsmoreover, abstractions should not depend on details but details should depend on abstractions

32
Q

Definition of Callback

A

a function or a piece of code that is passed as an argument to another functionusually implemented by passing an object of an interface or superclass as an argument

33
Q

Downside of Not Using Callback

A

Higher-levels depend on lower-levels, which does not satisfy DIP.

34
Q

Alternative: Adaptor via Inheritance Explanation and Example

A

Explanation:- - class with incompatible interface implements/extends both abstract classes/interfaces (both Target and Adaptee superclass)- Thus, it is now compatible with Target interface, and can override target method in Target interface such that this method calls the desired method in AdapteeExample:// Target interfaceinterface Target { void request();}// Adaptee (existing class)class Adaptee { void specificRequest() { System.out.println(“Adaptee’s specificRequest called”); }}// Adapter class via inheritanceclass Adapter extends Adaptee implements Target { @Override public void request() { specificRequest(); }}// Client codepublic class AdapterInheritanceExample { public static void main(String[] args) { // Using the Adapter class to make Adaptee compatible with Target Target adapter = new Adapter(); adapter.request(); }}

35
Q

Adaptor via Inheritance vs via Composition for Class with Incompatible Interface

A
  1. Adaptor via Inheritance:- Adapter has hard coupling to Adaptee class implementation, meaning that if you have a different Adaptee class that extends the initial Adaptee, you need a new class to adapt it- i.e., for even slightly different implementations of adaptee class, you need different adaptor classes- yields a class with a larger interface, which violates the Interface Segregation Principle2. Adaptor via Composition:- removes hard coupling problem from previous solution by coupling solely to objects- however, there is a run-time penalty and the design has become more complex- moreover, there is indirection via stored reference to adapted (extra) object
36
Q

What to do if you want your functionality A to do multiple things, e.g., both count and print?

A

Use the observer design pattern, which can also be done to include adapters and composite functionalitiesSpecifically, create composite functionalities that hold the sub functionalities and call the operation only on the highest level functionalities. Once the functionality is called on the highest level one, it is called on all of them, and all of the specific operations are carried out.

37
Q

What to do if the class has the right interface but the class’ functionality is wrong and must be changed?

A
  1. Using inheritance; create a new class that extends the former class and edit the functionality- however this involves creating a new class for every functionality2 AND 3, USE DECORATORS2. Create a class that does what this class does but generally- like a decorator, takes the class with wrong functionality as a parameter, and adds the desired functionality to it- e.g., if the initial class wrongfully does not add quotation marks around its printed statement, this class does3. Create a class that does the same as the above class, but also gets sent a pattern that must be contained by the data to have the doB run- decorator class gets as parameter the class to be decorated and a pattern- the pattern is used to determine whether a certain condition is satisfied, and only if it is, is the operation passed onto the parameter class- in this way, the functionality of the wrong class can be changed in certain situations
38
Q

Flexible Callback Toolkit

A

a toolkit involving decorators, compositions, adapter, observers, etc.allow callbacks to be used in programs, significantly enhancing their functionalities

39
Q

Disadvantages of Flexible Callback Toolkit

A

performance penalty because of all indirections and data transfersconfiguration needs to be programmed and is created at run time

40
Q

Variations on What Data to Transfer in Observer Pattern Context

A
  1. pushing data to observers irregardless of the situation, meaning that the Subject decides whether or not to actually do something with the data that was indiscriminately sent2. notifying the observers of the need to act, and then the subject can decide whether they need data and select which data they need (through getter methods)
41
Q

Variations on the direction of data transfer

A
  1. Updating the Observers (Push Model):- the subject actively pushes updates to its observers- when the state of the subject changes, it sends the updated information to all registered observers without them explicitly requesting it- push-based approach, e.g., stock market application pushing real-time stock price updates to various subscribed clients2. Observers to Subject:- observer actively pulls information from the subject when it needs an update- observers explicitly request the current state or data from the subject when they decide to check for updates- pull-based approach, e.g., weather station providing data, and various clients pulling the latest weather information when they need it