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.
Composite Pattern- Structural
- Intent
– Composes objects into tree structures
– Work with these structures as if they were individual objects - When
– You want to represent part-whole hierarchies of objects.
– You want clients to be able to ignore the difference between compositions of objects and individual objects.
Clients will treat all objects in the composite structure
uniformly. - Pros
– It defines class hierarchies consisting of primitive
objects and composite objects. Primitive objects can
be composed into more complex objects, which in turn
can be composed, and so on recursively.
– It makes the client simple.
– It makes it easier to add new kinds of components.
– OCP: You can add new element types without breaking
existing code, which now works with object trees. - Cons
– Difficult to provide a common interface for classes
whose functionality differs too much, can cause
complexity
Factory pattern - Creational
- Intent
– Provide an interface for creating objects in a superclass
– Allows subclasses to alter the type of objects that will be
created - When
– A class can’t anticipate the class of objects it must
create.
– A class wants its subclasses to specify the objects it
creates.
– Classes delegate responsibility to one of several helper
subclasses, and you want to localize the knowledge of
which helper subclass is the delegate
We want to develop a system that needs to converts (serialize) a Song into its a string representation using a specific string format (XML and JSON).
We also want to de-serialize JSON and XML strings back to instances of the Song class.
We want to allow multiple formats (XML and JSON) but we also want to design the code such that we can add more formats in the future.
- Pros
– Avoid tight coupling between creator and
concrete products
– SRP: You can move product creation code into
one place in the program
– OCP: You can add new types of products into the
program without breaking existing client code - Cons
– More complex code due to subclasses necessary
to implement the pattern
Abstract Factory Pattern
Intent
– Allows you to produce families of related objects without
specifying their concrete classes.
* When
– A system should be independent of how its products are
created, composed, and represented.
– A system should be configured with one of multiple families of
products.
– A family of related product objects is designed to be used
together, and you need to enforce this constraint.
– You want to provide a class library of products, and you want to
reveal just their interfaces, not their implementations
Pros
– Factory produces compatible products
– Avoids tight coupling between concrete products
and client code
– SRP: You can extract product creation code to
one place
– OCP: You can introduce new variants of products
without breaking existing code
* Cons
– Code complexity, since a lot of interfaces and
classes are needed.
Factory Method:
Focuses on creating a single object (or a single product). The decision of which class to instantiate is typically pushed to subclasses through overriding the factory method.
Abstract Factory:
Focuses on creating families of related objects (or related products). It provides methods to create objects in a group that are designed to work together (like different types of buttons, text fields, or windows in a GUI toolkit).
Builder
Intent
– Construct complex objects step by step
– Produce different types and representations of objects
using the same construction code
* When
– The algorithm for creating a complex object should be
independent of the parts that make up the object and
how they’re assembled.
– The construction process must allow different
representations for the object that is constructed.
We want to design a system that allows us to create different car
models. We have different car models, such as sport car, city car, and
SUV. Each car model has its own basic feature, such as the number of
seats, type of engine, and type of transmission.
However, more features can be added or upgrading existing features
based on the contract agreement (and the price) with the customer.
The Builder Pattern separates the construction of a complex
object from its representation so that the same construction
process can create different representations. A product is
built step-by-step.
- Pros
– Construct objects step-by-step, defer some
steps or run steps recursively
– Reuse the same construction code for various
representations of products
– SRP: isolate complex construction code from
the business logic of the product - Cons
– Code complexity increases as builders require
multiple new classes
Singleton Pattern
- Intent
– Ensure that a class has only one instance
– Provide global access to that class - When
– You can’t use static (e.g.
inheritance/interfaces)
– There must be only one
instance of a class - Pros
– Single instance
– Globally accessible
– Single instantiation - Cons
– Can mask bad design, for instance components that know too much about each other
– Requires special treatment in a multithreaded environment to avoid multitons
– Difficult to unit test clients of singletons
– You cannot subclass from singletons