Design Patterns Flashcards

(90 cards)

1
Q

What is a design pattern

A

A proven solution for a recurring problem

a solution idea, scheme or template

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

Blackboard

A

collaborate on common data to get the best solution

have a common data store and let several competing nodes work collaboratively or against each other on that common data the one with the best performance/data wins, will get selected by the client

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

Scoped resource

A

make object available in a specifically defined scope, when exiting the scope, the object gets destroyed

create a critical section and requiring resources in that section

client cannot forget to release the resource

e.g. using statement which works as the context manager, or the “with” statement in python

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

Bridge

A
  • Decoupling abstractions from implementations with adapters
    • abstraction interface (client-requirements)
    • implementor interface
  • Both sides can evolve independently from each other
  • client is only allowed to use abstraction interface
  • abstraction interface only allowed to use implementor interface, not concrete implementations
  • hide implementation side completely from the client
  • improves extensibility, both sides can grow
  • hiding implementation details from the client
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Early aqcuisition

A

make resources available as early as possible

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

Eager Aqcuisition

A

make resource available as early as possible when the context is opened (e.g. a window)

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

[E] what do scoped lock, scoped resource and scope.. have in common?

A

all of them use common mechanism to automatically release the scoped resource in the end

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

[E] What is the difference between lazy and eager loading?

A

Lazy = load resource as late as possible (on access)

Eager = load resource when needed but also rather early than late

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

Flyweight

A

Store away similar values to only have one instance of them

You have only one instance for similar/same attributes

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

Pooling

A

You store multiple objects or reserve a bigger block of memory to be reused over and over again

until pool is used up

when more objects are needed, client has to wait until objects are freed again

store the results temporarily to be used again

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

[E] How does Caching differ from Pooling?

A

In Pooling: you reuse the already allocated memory instead of freeing/destroying. Only one client should use a resource at a time (exclusive access). Can be predefined or builds up over time.

In Caching: always builds up over time, non exclusive access

both have upper limits

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

[E] What is better for accessing a Database: Active Object or Active Record? Explain why!

A

Active record, contains CRUD operations

Active object is not at all about the database

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

Active Object

A

asynchronious thread pool

execute the command in a different thread than it was created initially

contains tasks the execution about commands that get executed in other threads

you have to encapsulate the command with its context

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

What is the purpose of design patterns

A

Easier knowledge transfer

efficient problem solving by reusing existing ideas

common vocabulary, terminology, or language

usefulness of an idea by generalizing the solution

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

What types of design patterns are there

A

Architechtural (fundamental structural patterns, Layers, Pipes-And-Filters, Broker, MVC)

Idioms (fine graned patterns for spec. contexts, Composite, Adapter, Proxy)

Design Patterns (more isolated problems, Counted Pointer, Scoped Locking)

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

What types of design patterns are there

A

Architechtural (fundamental structural patterns)

Idioms (fine graned patterns for spec. contexts)

Design Patterns (more isolated problems)

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

Pattern Format

A
  • *Name**: A catchy name for the pattern
  • *Context**: The situation where the problem occurs
  • *Problem**: General Problem Description
  • *Forces**: Requirements and Constraints - why does problem hurt?
  • *Solution**: Generic Description of a proven solution.
  • *Consequences** (Rationale, Resulting Context): What are the benefits and drawbacks? Pro and Contra?
  • *Known-Uses**: Real Life Examples
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How Design Patterns emerge?

A

Design Patterns are found - not invented!
They emerge out of real use-cases/known-uses

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

Pattern Languages

A

coherent systems of patterns

consisting of Patterns, Relations and Principles

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

SOLID

A

Single Responsibility: A class should have one, and
only one, reason to change.
Open Closed: You should be able to extend a class’s
behavior, without modifying it.
Liskov Substitution: Derived classes must be
substitutable for their base classes.
Interface Segregation: Make fine grained
interfaces that are client specific.
Dependency Inversion: Depend on abstractions,
not on concrete implementations.

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

Principles of Good Programming

A
  • Decomposition make a problem manageable decompose it into sub-problems
  • Abstraction wrap around a problem abstract away the details
  • Decoupling reduce dependencies, late binding shift binding time to “later”
  • Usability & Simplicity make things easy to use right, hard to use wrong adhere to expectations, make usage intuitive
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Decorator

A

Extend the functionality of an object, while maintaining the same interface.

add responsibilities to individual objects without affecting other
objects

reuse funcionality

disadvantages: hard to learn and debug

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

Proxy

A

Provide a placeholder for another object to control it.

Maintain a reference that lets the proxy access
the real subject and provide interface identical
to Subject

Control access to the real subject

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

Layers

A

Split your large system into layers based on abstraction levels

Problem: Hard to understand structure, many dependencies

Every layer uses defined services of sublayer
Every layer provides defined services to upper layer

Defined Interfaces between Layers

Dependencies/Changes are kept local

e.g.: Network stack, API’s, Operating Systems

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Layers - Properties
Who composes the layers at runtime? Layers are Black Boxes Skip layers? Stateless / Stateful Interfaces defined
26
Broker
Manage dynamic communication between clients and servers in distributed systems ## Footnote complex systems as a set of decoupled and interoperating components Specify broker API (client side and server side) addition, exchange, or removal of services shall be supported dynamically Interoperability between different broker
27
Broker Pros/Cons
Pros: Changeability & extensibility of components (with proxies and bridges) Broker is a server (location transparency) Reusability Cons: Broker is single point of failure Hard to test and debug
28
Pipes & Filters
Form a sequence of processing steps using a common interface. Processing of data streams decomposed into several processing stages exchange or reordering of processing steps push or pull pipes storage of interim steps, defined data format along each pipe Multiprocessing
29
Pipes & Filters Pros
Pros: exchange and reordering parallel processing
30
Master-Slave
Distribute work amongst some helpers partition identical work and separate concerns multi-threaded applications maybe master: coordination instance between clients maintaining slaves slaves: only communicate with the Master
31
Master-Slave Pros/Cons
Pros: Exchangeability and extensibility Separation of concerns Efficiency : parallel processing (multi-thread) Cons: Partitioning & control can be tricky
32
Client-Server
Let clients send requests to servers which answers with responses. Distributed applications. one dedicated provider (centralized system) Client might not have processing power serving a request/response communication over protocol Server waits for requests, client sends request and waits for responses
33
Client-Server Pros/Cons
Pros: Service-Oriented Architectures Centralization of specific services Workload gets moved to server Cons Single-Point-Of-Failure Communication overhead Client rely upon network and servers
34
Adapter
Wrap around a class to make it compatible to another interface. Working with multiple different frameworks or libraries. make incompatible classes work together reuse the functionality of a class in your own context Class may be sealed (inheritance is not possible) **Class or Object adapter** **an Adapter class which wraps around the Adaptee**
35
Adapter
Wrap around a class to make it compatible to another interface. Working with multiple different frameworks or libraries. make incompatible classes work together reuse the functionality of a class in your own context Class may be sealed (inheritance is not possible) **Class or Object adapter** **an Adapter class which wraps around the Adaptee**
36
Class Adapter cs Object Adapter
**Class Adapter** override mechanisms based on inheritance it is on a different branch of subclasses **Object Adapter** breaks inheritance hierarchy Explicit implementation approach
37
Facade
Provider a higher-level interface to a system used by client Working with a complex structure having many functions use functions of different programming paradigms in a more intuitive way Details/complexities should be hidden away
38
Facade Pros/Cons
Pros: Easier to use interface maintainability, easier to learn Cons: additional abstaction layer potentially loose benefits of underlying paradigm
39
Factory Method
Delegate the creation of objects to someone else. class is not known until runtime does not matter which object, just that there is same functionality Define an interface of **capabilities** your objects must implement Define some method or class to **create** the actual object somewhere else Let the actual object implement the needed interface
40
Factory Method Pros/Cons
**Pros** Isolates Framework and Application code Fewer Dependecies Decoupling of Implementation and Usage Hides constructors **Cons** Needs an interface/abstraction
41
Abstract Factory
Create whole families of related objects create only matching objects Choose object family (Factory) at runtime Interface for Factory and for the Product
42
Abstract Factory Pros/Cons
Pros exchanging product families easy consistency among products Cons Supporting new kinds of products
43
Builder
Split up creation into multiple steps Creation of complex objects Manage many different construction options Split creation from assembling define Interfaces for individual parts
44
Builder Pros/Cons
**Pros** many combinations of parts isolates code for construction and representation finer control of construction **Cons** Construction is not a simple “new” anymore correct configuration might be tricky
45
Prototype
Create objects by cloning from templates Creation of objects whose classes and properties are not known until run-time dynamically implement and use objects without knowing its properties Declare and implement cloning interface
46
Prototype Pros/Cons
**Pros** Dynamic objects can be created at runtime No complex inheritance hierarchy Long taking initialisation are done only once **Cons** No type safety! No compile time errors
47
Memento
Store & Load the internal state of an object with a class Combines very well with the command pattern Snapshots are possible
48
State
Change object behaviour depending on a situation Behaviour should change at runtime with state change Context(manager) which knows the states general Interface for all States define transitions between states
49
State Pros/Cons
**Pros** State specific behaviour is encapsulated within the state objects New States and transitions easily defined State Object can be shared (-\> Flyweight) **Cons** More classes special transitions are difficult
50
Flyweight
Share global state and vary differences only when needed.
51
Visitor
Add behaviour on aggregates of different objects perform operations on elements of an aggregate Avoid polluting classes with unrelated operations Implement the functionality for each different object type in an visitor
52
Visitor Pros/Cons
**Pros** Makes adding new functionality easy Account for different object types Can accumulate state **Cons** Adding new types is expensive Visitor may need access to private members
53
Strategy
Substitute behaviour later related classes which differ only in their behaviour, which is exchangeable at runtime different variants for an algorithm encapsulated algorithms to make them interchangeable split up behavior and decision logic
54
Strategy Pros/Cons
**Pros** Elimination of Subclasses just for different behavior Behaviour of one class can be reused for others **Cons** Access to private fields? Every behavior is a new object → high number of objects
55
Command
Encapsulate a request. Decouple invocation from execution. invoke an operation, regardless of its concrete implementation and executing context request should be undoable interface for commands (execute(name))
56
Command Pros/Cons
**Pros** ``` request does not depend upon the creating class anymore ``` request can be executed in isolation Undo/Redo-Operations become possible Switching the receiver at runtime possible **Cons** Increased number of objects References to all needed parameters must be stored
57
Composite
Handle different granularities of objects uniformly Hierarchies of objects with different granularities Apply/Reroute a method call to all objects common Interface for all granularities to manage children and call methods Composites forward call to children, leaves execute calls
58
Composite Pros/Cons
**Pros** Simple handling for client Adding new kinds of composites is EZ **Cons** Client doesn’t recognize complexity of calls high call hierarchy
59
Template-Method
# Define methods and let children implement the behaviour abstract algorithm skeleton for subclassing variability is added through subclassing
60
Mediator
Mediate communication between multiple objects reduce chaotic dependencies between objects objects collaborate only via a mediator object
61
Microkernel
Route requests to the responsible components, to the right target
62
Messages
Encapsulate information in a standardized way Message contains data and metadata (header) sender packs together the message and sends it to the receiver in explicitly defined protocol no stream, enclosed packet
63
Messages Cons
- Computation overhead for serialization and deserialization - Communication overhead due to protocol - Version Chaos / Change-Management - Data-Format must be exactly defined
64
Message Endpoint
Provide functionality to send and receive messages Endpoint converts into/from a message and can be reused Decoupling of external protocol and internal communication Drawbacks: changes in protocol has to be communicated, perfomance overhead, single POF
65
Request-Response
Answer every request with a response message **Pros** Every request gets answered, two decoupled events Timeouts can be detected Windowing and Buffered Responses possible **Cons** No data streams possible async communcation hard to debug Broadcast/Multicast not possible
66
Message Translator
# Translate between different message formats **Pros** Sender and Receiver don‘t have to know the same protocols/message format Translator can be reused and parallelized **Cons** Translator needs to know both protocols! Performance Overhead for additional translation Protocols might be imcompatible
67
Message Router / Message Queues
Transmit messages to the right receiver **Pros** Sender and Receiver are decoupled Dynamic rerouting is possible Message Queues allow: Retransmissions, Guaranteed Delivery Adaptive Transmission-Rate Multicast / Broadcast **Cons** Bottleneck / Single Point of Failure Man-In-The-Middle Attacks Loops and Broadcasting misuse
68
Message Bus
Provide a common communication platform which can be used to send and receive messages **Pros** Unified communication platform & protocol Communication can be controlled **Cons** Bottleneck / Single Point of Failure Security Issues Forced communication protocol
69
Requestor
Send generic requests and arguments
70
Request Handler
Listening, Receiving, Sending, and Handling of Message-Based Communication
71
Observer
Inform registered observers about changes data is distributed over multiple related objects object changes, others should be held consistent manage observers for a subject notify all observers that a change happened
72
Observer Pros/Cons
**Pros** Decoupled and reusable subjects and observers No need for polling **Cons** unexpected, frequent updates might happen
73
Locks
avoid conflicts when simultaneous access to resources Parallel access to shared resources who writes first? acquire lock before accessing a resource release the lock after resource is not needed anymore
74
Locks Pros/Cons
**Pros** access to resources is mutually exclusive **Cons** overhead & waiting times deadlocks, race-conditions
75
Scoped Locking
Use language scope semantics for acquiring and releasing locks avoid forgetting to release the lock critical section of code should be protected rely on stack-unwinding to call the destructor
76
Double Checked Locking
Check twice to ensure conditions
77
Monitor
Synchronize method calls to an object Multiple threads accessing an object concurrently without manual synchronization Method calls should be synchronized object state should be stable general lock for one object instance sacquire lock before method call, Release after method is finished
78
Monitor Pros/Cons
**Pros** Simplification of concurrency control Simplification of scheduling method execution **Cons** limited Scalability Inheritance/Extension is dangerous
79
Future
Supply a placeholder for future results Asynchronous method calls No waiting for result
80
Active-Object
Encapsulate method invocation and execute asynchronously execute commands in a different context than the client clients invoke remote operation and retrieve results later proxy with encapsulates all method calls in commands Scheduler/CommandProcessor to execute the commands in a separate thread(pool) possibility to retrieve or wait on the results
81
Active-Object Pros/Cons
**Pros** Simplifies sychronization complexity Command executed in different thread than client thread Typesafety due do usage of classes/objects **Cons** performance overhead hard to debug
82
Thread-Specific Storage
Store separate data instances for each thread
83
Async / Await
Execute functions cooperatively in an event loop Executing multiple functions waiting for I/O resources Compile the functions as state machines, with transitions at the “await” statement advancing them based on a “ready”-condition
84
Async / Await Pros/Cons
**Pros** No need to use multiple threads. No need to synchronise. No unnecessary waiting times due to blocking functions **Cons** syntax and Compiler support needed Relies on cooperativeness CPU-bound functions are still blocking
85
Chain of Responsibility
Forward a call until an object can handle it chain of handlers objects which can handle different tasks tasks and the actual Handlers are not known at compile-time
86
Counted Pointer / Smart Pointer / Shared Pointer / Auto Pointer
Count references and call destructor when no one is using the object anymore
87
Interpreter / Abstract Syntax Tree
Read expressions one after another and build a tree of expressions
88
Reactor
event handling pattern synchronious, serially Main traditional and competitive Applications designs dispatch synchronously and serially service requests that are received simultaneously from one or more clients
89
Proactor
event handling pattern async, thread-based Main traditional and competitive Applications designs dispatch synchronously and serially service requests in an efficient asynchronous way
90
MVC vs. MVP vs. MVVM