Design Patterns Flashcards
What is a design pattern?
Common architectural approaches to solving specific problems. Reusable solutions to similar coding problems.
What is the single responsibility principle?
Each class should have only one reason to change. It should be responsible for doing one thing. If we want more functionality, we can compose classes together by making classes interact and depend on each other.
Open-Closed principle
Class should be open for extension but not modification. If we have a code that was shipped to the customer, we don’t want to change that code. We can extend the class by creating a new one and adding on top of that behaviour instead of changing implementation.
Liskov substitution principle
Child should be used in the same manner as the parent but it doesn’t need to produce the same output for the same input. We should be able to substitute base type for subtype and for all methods on base to work (e.g. be implemented). The Penguin, Bird and flying example. If we store the subtype in a variable of type base type (by casting for example), it should still work. We can access correct members by overriding the base members.
Interface segregation principle
Don’t put too much into an interface, instead implement separate interfaces. Any inheriting class will have to implement all methods of the interface and they might not need to use those methods so what do you put in them? If you have to put in NotSupportedException, you’re doing something wrong. Supports separation concerns.
Dependency injection principle
High level code should not know the low level implementation. Use abstractions. That way we can change the internals of how something works but not having to change the interface.
Why would one use a command?
To create an object that represents operation/action. Contains everything to do the action. Encapsulates the action into separate object. Need to define instructions for processing the command, can also define instructions how to undo command.
Uses of command
GUI commands, multi-level undo/redo, macro recording. Query can fall under it as well if we need to persist it and perform some action on it.
What are composite commands?
Command that are composed of more objects -> e.g. a group of commands. public class CompositeCommand : List, ICommand - can operate on the whole collection.
What is the bridge pattern?
It is used for abstraction to avoid entity explosion for multiple criteria. Decouples interface from implementation. Bridging two objects.