Chapter 2: Design Patterns + Principles Flashcards
Functional Interface
Marked with @FunctionalInterface. Should contain 1 abstract method only. You can however have other static or default methods. Also make sure it is an interface, not an abstract class.
Extending a functional interface
If you extend a functional interface and don’t declare any new methods, then it will also be a functional interface.
Lambda rules
- If 1 parameter mentions data type, they all must do.
- In your Lambda body, you can’t re-declare a variable name
- If you’re not returning anything need {} on RHS (can’t just be blank)
Polymorphism
You can pass an instance of a class to anything which expects an instance of its super class or interface it implements (Note: all objects are accessed by reference, so you never have direct access to the object in memory)
Casting rules in polymorphism
- Casting to a super class doesn’t require an explicit cast
- Casting to a subclass does require an explicit cast
- Compile won’t allow casts to unrelated types
- Can get ClassCastException if the object is not of the specified type
Encapsulation
- Use getters and setters and add constraints on them to ensure objects are created/modified correctly
- Allows you to maintain certain invariants about the data
Is-a relationship
Known as the inheritance test. Class A extends B, so A is-a B. But be careful of any super classes as well in case the inheritance doesn’t make sense.
Has-a relationship
Object composition test. Used when an object has another object, which is included as a member of the object class.
Singleton Pattern
- Creates a single object in memory
- Private static variable with name instance
- Access via public static getInstance()
- All other constructors are marked as private which means it is effectively final
Singleton lazy initialisation
- Delays instantiation until the first .getInstance() call.
- Means it takes less time to load up the application
- But may not be thread-safe
- Can use synchronized keyword to ensure that difference objects aren’t created in memory.
- Can use the volatile keyword and add a synchronized block to check if object is null
- Volatile keyword in Java - it will write it to main memory, not just to CPU cache.
Immutable Objects
- Constructor to set everything
- Instance variables private + final
- No setters
- Don’t allow mutable objects to be accessed directly
- Prevent methods from being overridden
- Need to ensure that when someone is passing you a mutable object to a constructor that you create a copy of it, otherwise the caller might still have a reference to the same object and can change something later on.
Builder
Should be in the same package or as a static inner class. If it’s in the same file as an inner class, then the constructor can be final, forcing you to use the Builder.