OO design patterns Flashcards
How can you de-couple creating an instance of a class (since it’s dependent on a concreate class)?
By creating an abstract factory class
What are object patterns?
Patterns produced by experienced developers, that when followed produce code with less bugs/issues.
What is encapsulation?
Wrapping data and it’s methods into a unit by restricting direct access to an objects internal state.
- only allowing interaction through well defined interfaces.
What is inheritance?
Reusing code from superclasses. A subclass uses the functionality from a superclass and is able to extend it for modification.
How can you ensure loose coupling?
make every public method final. If something is public there’s no reason it should be overridden, unless you’ve allowed this when defining the class.
What are the OO benefits (achieved by following SOLID)
- lower coupling
- good cohesion (single responsibility)
- code reusability
- code is easier to understand, test and maintain
What are the two steps for OO development and explain them?
- OO Analysis: Before programming starts create a list of classes
- OO design: identify data/methods in each class and relationships between classes. Can be done whilst coding.
What is the role of documentation and list some examples:
- makes it easier to communicate ideas
- use it to control what’s in requirements
- helps to understand code
- UML diagrams, requirements/specification, database diagrams, user guides, use cases, actor models
What are patterns vs components?
- patterns: general description of approaches to a problem
- components are reusable code which solves the approach
List a number of OO design patterns:
- Model View Controller
- Command Pattern
- Wrapper classes
- Memento
- flyweight
- Chain of Responsibility
- Singleton (and multiton)
- Double Lock Checking
- Factory Patterns
- abstract factor
- Builder Pattern
Describe the MVC OO design pattern:
- An architectural pattern
- separates concerns/code into 3 components
- model (represents data and logic of application, manages state of application and handles core functionality)
- view (handles the app’s UI, displays data to the user and sends user inputs to the controller)
- controller (intermediary between model and view. Processes user inputs, interacts with model and updates view accordinly)
Describe what each of the Model, View and Controller components would be implemented as:
Model: classes and objects
View: GUI framework / web templates
Controller: classes and methods
Describe in detail what the model component in the MVC does:
- handles persistence: communicates with DB
- handles logic
- handles applications internal state
- validates data
Describe in detail what the view component in the MVC does:
- Renders UI on screen
- presents information to the user
Describe in detail what the controller component in the MVC does:
- Processes user inputs
- passes events to the model
- instructs the view to render
What are the benefits of the MVC OO design pattern?
- Clear separation of concerns
- single responsibility
- easier to port to any platform/change UI/ have multiple UIs
- concurrent development
Describe the command pattern
an object is used to encapsulate all information needed to perform an action or trigger an event at a later time
Describe the structure of a command pattern:
- Interface or abstract class (describes contract for executing a command, includes execute() method.
- concrete command class (method that defines execute() method)
- receiver class (performs the actual work when command is executed)
What are the key benefits of the Command Pattern?
- Open/Closed Principle: Adding new commands doesn’t require changes to existing code, just extension.
- lower coupling: decouples classes that invokes the operation from the object that knows how to execute the operation
Describe the factory class object pattern:
- constructs instances of a class, used when object type is not known at compile time but will be decided on at runtime
Give an example of a scenario when you’d use a factory class pattern:
For handling different image file types:
How to handle the string when the input image file could be JPG, PNG, etc…
- have abstract class Image()
- have classes that extend Image, ImagePNG, ImageJPG
- have factory class or Image class use a method getInstance(), that has logic in to create specific object with correct subclass
public static Image getInstance(String fileName){
if (fileName.endsWith(“.png”)) {
return( (Image)new ImagePNG(fileName));
}
if (fileName.endsWith(“.jpg”)) {
return( (Image)new ImageJPG(fileName));
What are the benefits of using the factory class object pattern
- Supports open closed principle, add subclass if another object type is needed
- encapsulation (of logic required to create objects)
- code reusability
Describe a singleton (class) design pattern:
- there is only at most one instance of a class throughout the lifetime of an application
- access to the singleton is provided through a static method (getInstance) which checks if the one instance has already been created, if it hasn’t it creates it, if it has it returns the existing one.
What is lazy initialisation?
The instance of a singleton class is only created when the object is needed (not when the application is loaded up.
Why would the synchronised keyword by used for a singleton class:
It means that multiple threads can use the same one instance of the class, but only one thread is allowed inside the code at once.
Describe wrapper classes:
give an example:
- encapsulates data types so they can be treated as objects with a standard interface.
- e.g. when you want to connect to different databases
What are the benefits of wrapper classes?
- Easier to swap modules
- easier to implement standard functions
- allows data types to access object functionalities like object based APIs
What is an abstract factory class?
- a design pattern, provides an interface for creating groups of related or dependent objects without specifying their concreate classes
When is an abstract factory class used?
- When you have a set of related object types to create but the actual class to create is decided at runtime
How does an implementation of a factory class differ from an implementation of an abstract factory class?
The Factory pattern usually has one Factory class and one interface for the products, while the Abstract Factory pattern has one Abstract Factory interface, multiple concrete Factory classes, and multiple interfaces for the products
Describe the builder class:
- construct complex objects by separating the abstract definition of the object from it’s representation
- implements single responsibility
When are builder classes specifically useful?
- When an object has multiple optional parameters
- when an object is too complex to be constructed in a single constructor call
Describe an example of a builder pattern for building SQL statements:
- interface with appropriate elements (table names, columns, indexes)
- abstract class (used to construct SQL statements with concreate methods)
- concreate definition (selectBuilder, createBuilder, deleteBuilder) used to generate anything that has a particular format that ends up as a string
What are the benefits of using the builder pattern?
- reduces syntax errors
- Open closed principle, extra functionality can be added easily.
What is a multiton?
What is the advantage of using it?
- creates a limited number of instances of a class which are each identified by a key.
- allows control of object creation
- efficiently managed resources across an application
What is a Flyweight OO pattern?
- shares memory between objects with similar properties, which minimises memory usage
- useful for apps with many objects that have a shared state.
What is a flyweight factory?
- Manages flyweight objects
- provides a way to create or retrieve existing shared objects
- when a new object is created, the factory checks if an object with the same state already exists
- it returns the existing object or creates a new one
Give an example of a flyweight pattern being used?
- if some text is using a font and another piece of text wants to use a font, it checks if the font they want to use is already loaded into memory before it loads the font up
Describe the chain of responsibility?
- A number of classes work together to handle a message (call)
- If the class doesn’t want to handle the message, it passes the messages down to next class in the chain
- a class can process a call/object and pass it to another class which will also process it
Give an example of a chain of responsibility:
- multiple instances of the alien class exist in a space invaders game
- the player shoots a bullet and hits an alien
- the alien objects are passed through the chain of responsibility to check which alien has been hit
Describe the memento pattern:
Give examples:
- captures an object’s internal state without violating its encapsulation.
- Provides ability to restore an object to a previously stored saved state
- Useful in scenarios like undo/redo operations or rollback.
- MS word (undo, redo), bank transactions, version control
What are the 3 parts the memento pattern consists of?
- Originator: object whose state is saved and restored. Creates memento object.
- memento: holds originators internal saved state. Doesn’t allow any other class but the originator to alter it’s state.
- care taker: keeps track of mementos. Requests a memento from the originator when it wants to save the state and passes it back to the originator to restore it’s state.
What are the benefits of using a memento oo design pattern?
Encapsulation: allows for saving an objects state and rolling back without exposing the internal details of the originator
Describe double checked locking:
- used in multi-threaded programming to guarantee that a resource is initialised once.
- minimises use of synchronous keyword as Double-lock checking checks that the lock is needed/the resource hasn’t been initialised BEFORE applying the synchronous key word.
- when the lock is acquired again it checks that the resource hasn’t been initialised before proceeding
What are the advantages of using double checked locking?
- It reduces the overhead of acquiring a lock
- makes sure only one lock is created but used by multiple threads
- helps to keep access to certain code exclusive
When should you use inheritance?
Give an example of a superclass and subclass:
- Only when there’s a ‘is a’ relationship
- A pigeon (subclass) ‘is a’ Bird (superclass)
- If it doesn’t have this relationship use composition
Why should you not use inheritance if the two objects don’t have an ‘is a’ relationship?
- because inheritance creates a coupling between the two classes.
- A change to the superclass, may break the subclass.
Give an example of a hierarchy with good inheritance and a hierarchy with bad inheritance:
Good: Person –> staff member –> doctor
Bad: encryption algorithm –> person
- This has been done so the Person can use the encryption functions in the Encryption helper class, however this style is poor and has poor design!
Describe good practices when implementing the open closed principle:
- all attributes should be private and accessed via getters and setters
- public class methods should have final in the constructor
- use protected methods for methods that get overridden
When should you use composition, give an example:
Use composition when the two things have a ‘has a’ relationship, where one class contains an object of another class as a part of its own structure.
- It models the idea that one object is made up of other objects, giving it certain functionalities.
- a car ‘has a’ engine
What does a composition relationship between two objects/classes look like:
Have a private instance of another class inside a class.
What are the differences between inheritance and composition:
Composition: Loose coupling; the composed objects can exist independently, making the system more flexible. You can change the components without affecting the whole system.
Inheritance: Tighter coupling; the subclass is dependent on the parent class, making it harder to change one without affecting the other.
What are mixins?
- allows you to mix in behavior of multiple classes to existing classes without using inheritance
- used to share common methods or properties across unrelated classes.
How do mixins allow class behaviour to be used without inheritance?
- A mixin provides methods and attributes that can be added to any class without forming a parent-child relationship.
Give example code for a mixin:
class LoggerMixin:
def log(self, message):
print(f”Logging: {message}”)
class Database:
def save(self, data):
print(f”Saving {data} to the database”)
Combining functionality with a mixin:
class UserDatabase(Database, LoggerMixin):
def create_user(self, username):
self.save(username)
self.log(f”User {username} created”)
What are the advantages of using mixins?
- higher code reusability
- Avoid Deep Inheritance structures
- Modularity: can split functionality into mixins and combine them in different ways.
What is the advantage of using interfaces?
- You have more control, as you can control which methods are accessed through defining an interface
What does putting the final keyword in front of an _____ do:
- attribute
- method
- class
- final attribute defines: A constant such as final static int: PI=3.14159
- final class: Cannot be subclassed (extended from/no inheritance).
- final method: Cannot be overridden
When should you use protected methods:
When you have methods that can/should be overridden
What are the advantages of using the protected keyword?
- allows for encapsulation to be maintained
- Promotes code reusability via inheritance:
- it facilitates polymorphism
When are private methods used?
When you want a method to be invisible to the ‘outside world’.
- They can’t be overridden
What is an abstract class?
- A class that cannot be directly instantiated. Serves as a blueprint for other classes.
- Designed to be inherited from by other classes, contains one or more abstract methods (methods that are declared but contain no implementation)
What’s the advantage of abstract classes?
- They define a common interface which provides shared functionality for derived classes, while enforcing that certain methods must be implemented by the subclasses.
- implements the open closed principle
- supports code reusability
What is a facade interface?
A ‘facade’ class acts as the public interface for set of classes that interact with each other
What are the advantages of using a facade interface?
- It provides a simplified interface to a complex system of classes/libraries.
- Shields client from complexities of underlying code by offering an easier way to interact with it.
- Reduces coupling