Advanced Design Patterns Flashcards
1
Q
Describe Decorator Pattern and all that juicy stuff!
A
- Objects with incompatible interfaces to collaborate
- When two objects have incompatible interfaces. One operates in a certain way, the other in another way, for example, km vs miles. Wraps one of the objects with an adapter that converts to the other object.
- Define an interface that describes a protocol (a condition) that other classes must follow to be able to collaborate with the client code ( the code that will use the adapted object). Then one must create an adapter class that implements the client interface while wrapping the service object. The adapter receives calls from the client, via the adapter interface, and translates them into calls to the wrapped service object in a format it can understand
- Adherence to SRP and OCP.
2
Q
Chain of responsibility
A
- Let’s you pass requests (to do a certain thing) along a chain of handlers. These handlers can do one of two things:
Perform checks to pass along a request until it reaches a singular handler responsible for that specific request. Alt. the request can be handled successively by each handler, with data being passed on from one handler to another - Several cases when usable:
- One wants to decouple a request’s sender and receiver
- When multiple objects are candidates for handling a request and one wants the program to determine the “correct” one at runtime
- When one doesn’t want to specify the handlers explicitly the code
- When one wants to issue a request to one of several objects without specifying the receiver explicitly
- Requires a “client” to send a request, a base handler(for example an interface) which receives and dispatches the request, and the “concrete handlers”(classes that contain the different ways to handle a request) which are chained together sequentially
- Allows for decoupling of classes(SRP), adherence to OCP(new handlers can be introduced without breaking code)