Design Patterns Flashcards
What is cohesion
- Cohesion is the degree to which methods inside a
module belong together (intra-module complexity) - A module can be a class (e.g., in Java), a function
(e.g., in C), or higher-level software component
(e.g., package, maven module) - High Cohesion: classes (or modules) should be
independent as far as possible - High cohesion simplifies modification (all relevant
code in one place
What is coupling
- Coupling is the degree to which one class (or
module) relies on (calls or uses methods of)
another class (inter-module complexity) - Low Coupling: a module should implement one
single, clear, well-defined task - High Coupling leads to lower maintainability: a
change in one unit affects other units implicitly - Duplicated code often is an indication that a
better solution (in the design and implementation)
is possible
Types of Design patterns
Behavioral : Realization of common communication patterns
Structural: Organization of your
classes/objects to form larger structures
Creational: Create objects in a
controlled way, based on some requirements
Which design patterns enter in each Behaivoral category?
Iterator
Strategy
Chain of Responsibility
Observer
Design Patterns in Structural
Adapter
Facade
Proxy
Decorator
Composite
Design patterns in creational?
Factory Method
Abstract Factory
Builder
Singleton
What are SOLID principles?
The five design principles intended to make object-
oriented designs more understandable, flexible,
and maintainable
Single responsibility principle: Every class should have
only one responsibility
Open-close principle: “Software entities … should be open for extension, but closed for modification”
Liskov Substitute Principle : It states that objects of a superclass should be replaceable with objects of their subclasses without affecting the correctness of the program
Interface segregation principle: “it’s better to have many specific, smaller interfaces rather than one large, monolithic interface.
Dependency inversion principle: “Depend upon abstractions, not concretes”
Iterator pattern
Iterator Pattern
* Intent
– Traverse elements of a collection without exposing
underlying representation (list, stack, tree, …)
* When
– Iteration over your collection is necessary
– One or multiple iteration methods possible
Iterator Pattern
* Problem
– Collections are common
– Different internal representations
– Usually we need a way to iterate over each element
– Some collections may support multiple different
iteration orders
- Pros
– SRP All traversal algorithms into separated classes
– OCP Possible to add new collections and iterators
and pass them to existing code
– Parallel iteration is possible because each iterator
has its own state
– You can delay an iteration and continue when
needed - Cons
– Overkill if your app only works with simple
collections
– Can be less efficient than going through elements
directly for some specialized collections
Ce e Strategy Pattern
Intent
– Define a family of algorithms
– Every concrete implementation in a separate class
– All their objects are interchangeable
– Algorithm can now vary independent from clients
* When
– Many related classes differing only in behaviour
– Need for different variants of an algorithm
– Class defines behaviours that appear as multiple
conditional statements in its operations
- Pros
– Run-time changing of behaviour within family of
algorithms.
– Uses interfaces as an alternative to sub-classing.
– Eliminates conditional statements. - Cons
– Context must be aware of the strategy
– Potential communication overhead between
Strategy and Context
– Increases number of objects
What is Chain of Responsability Pattern
- Intent (A)
– Pass requests along a chain of handlers
– If any handler fails/rejects the request, propagation is
stopped - When
– More than one object needs to handle a request in
sequence.
– You want to issue a request to one of several objects,
without specifying the receiver explicitly
se mai poate cand decizi daca sa il procesesi tu sau sa il dai mai departe ex javascript event handler/ java exception
What is observer pattern
The Observer pattern is used when you want an object (the subject) to notify other objects (observers) about changes to its state. The key purpose is to establish a one-to-many dependency where the observers can react to state changes in the subject without tight coupling.
- You run a store which sells phones
- A new iPhone has come out, it will soon be available in your store
- Customers come and check multiple times per day!
- You could send out an email to your customers when it is available, but this would annoy all Android users
- Pros
– OCP: You can introduce new subscriber classes without having to change the publisher code (and vice versa)
– You can establish relations between objects at runtime - Cons
– Subscribers are notified in random order
Adapter pattern-> Structural
- Intent
– Allow objects with incompatible interfaces to
collaborate - When
– You want to use an existing class which has an incompatible interface.
– You want to create a reusable class that cooperates with unrelated or unforeseen classes (classes that don’t necessarily have compatible interfaces). - Pros
– Client doesn’t know implementation details of the
interface and/or how the data/code is adapted.
– Helps reducing code duplication - Cons
– Adapter won’t work when we want to adapt a
class and all its subclasses.
– One additional class.
Facade Pattern
Intent
– Provide a simplified interface to a library, framework or
other complex set of classes
* When
– You want to provide a simple interface to a complex
subsystem.
– There are many dependencies between clients and the
implementation classes of an abstraction. Introduce a
facade to decouple the subsystem from clients and other
subsystems.
– You want to layer your subsystems. Facades can be entry
points to each subsystem level.
Structural Patterns
Pros
– Helps isolating clients from subsystems
– Supports the open-closed principle
* Cons
– Facades can become god-classes where they
are coupled to all classes of the application.
Proxy pattern-> Structural
- Intent
– Provide a substitute or placeholder for another object
– Control access to the original object, allowing you to perform
something before or after the request gets through to the original - When
– (Remote Proxy) Local object represents a remote object
– (Virtual Proxy) Lazily load the real object on demand, only provide skeleton representation by default
– (Protection Proxy) Control access to a resource based on access rights
– (Caching Proxy) Cache results of client requests that are large and expensive to generate. The proxy also manages the lifecycle.
How the Proxy Works
The client interacts with the proxy object rather than the real object. The proxy implements the same interface as the real object. The proxy forwards requests to the real object after performing some pre-processing (like access control, logging, or caching).
Proxy Pattern Structure
Subject: The common interface that both the real object and the proxy implement. RealSubject: The actual object that does the real work (the object the proxy is controlling access to). Proxy: The object that controls access to the real object and may add additional behavior.
Proxy vs. Adapter
* The proxy provides the same interface of the wrapped object.
* The adapter provides a different interface to the wrapped
object.
Proxy vs. Decorator
* The proxy provides the same interface of the wrapped object.
* The decorator provides an enhanced interface.
Proxy vs. Facade
* The proxy provides the same interface of the wrapped object.
* The facade provides a simplified interface to the other objects
- Pros
– Control proxied object without clients knowing about it
– You can manage the lifecycle of the proxied object
when clients don’t care about it
– The proxy works even if the proxied object is not ready
or unavailable
– OCP: You can introduce new proxies without changing
the proxied object or clients - Cons
– Code may be more complex since you need new
classes
– Additional latency on response due to wrapping
Decorator Structural
- Intent
– Attach new behaviors by objects by wrapping them in special
wrapper objects - When
– You want to add responsibilities to individual objects dynamically and transparently, that is, without
affecting other objects.
– You have responsibilities that can be withdrawn.
– Extension by subclassing is impractical. - Pros
– Allows behaviour modification at runtime
– Decorators provide a better solution to
permutation issues (e.g., all combinations of
armours and weapons)
– It supports the open-close principle - Cons
– Decorators can result in too many small
objects if overused.