1/91
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
What is a Design Pattern?
Design patterns are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context. They are common solutions to recurring design problems faced by developers
What are the two main usages of design patterns?
First: Design Reuse - reusing existing design patterns to avoid reinventing the wheel when facing a design problem. Second: Vocabulary - providing a shared vocabulary for discussions, documentation, and communication among developers
What are the three categories of design patterns according to the Gang of Four?
Creational patterns provide various object creation mechanisms which increase flexibility and reuse of existing code. Structural patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient. Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects
What are the three key elements used to explain a design pattern?
Context describes the situation or environment where the pattern applies, Problem identifies the specific design challenge that needs to be solved, Solution provides the approach or structure that resolves the problem
What is the Factory pattern?
A creational design pattern where we create objects without exposing the creation logic to the client and refer to newly created objects using a common interface. It provides a single point of change if object creation needs to be updated
Give the code for a basic Factory pattern implementation
interface Product with operation method, class ConcreteProductA implements Product, class ConcreteProductB implements Product, class ProductFactory with static method createProduct taking String type parameter that returns new ConcreteProductA or ConcreteProductB based on type
What problem does the Factory pattern solve?
Applications may need to switch implementations such as from TCP to UDP channels. The Factory pattern allows designing the system to support such changes and parameterize the object type without modifying client code, avoiding tight coupling with the new keyword
When should you use the Factory Method pattern?
When object creation logic is complex or varies based on conditions, when the system needs to be open for extension but closed for modification following OCP, when new product types may be added in the future, when you want to decouple client code from concrete implementations
What is the Singleton design pattern?
A creational pattern that ensures a class has only one instance and provides a global access point to it. It uses a private constructor to prevent external instantiation and a static getInstance method that returns the single instance
Give the code structure for implementing a Singleton pattern
class Singleton with private static Singleton instance variable, private constructor to prevent external instantiation, public static getInstance method that checks if instance is null and creates it if needed then returns instance, public methods for business logic
What problem does the Singleton pattern solve?
When all operations must use the same instance such as logging to the same file or sharing a single database connection. The Singleton ensures that all methods use the same instance instead of creating separate instances each time
List real-world applications of the Singleton pattern
Logging Systems for consistent logging across an application, Configuration Managers for centralized access to settings, Database Connections for managing a single point of database access, Thread Pools for efficiently managing threads, Cache Managers, Print Spoolers for single printer queue, Runtime Environments like java.lang.Runtime
What is the Proxy design pattern?
A structural pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object
Give the code structure for the Proxy pattern
interface Subject with request method, class RealSubject implements Subject with actual operation, class ProxySubject implements Subject with private RealSubject member and cache, ProxySubject request method does preprocessing like checking cache then delegates to realSubject.request then does postprocessing like caching result
What problem does the Proxy pattern solve for caching?
To improve performance by using a cache, if data is in the cache return it immediately otherwise perform the operation. However we want to avoid modifying the base class because it is already well tested and maintained by another developer. The Proxy adds caching logic without changing the original class
How does the Proxy pattern maintain the interface contract?
The Proxy class implements the same interface as the RealSubject. Clients interact with the proxy through the interface, the proxy forwards requests to the base object and may add extra logic like caching, logging, or access control before or after delegation
What is the Adapter design pattern?
A structural pattern that allows objects with incompatible interfaces to collaborate. The adapter acts as the middleman by receiving requests from the client and converting them into requests that make sense for the vendor classes with different interfaces
Give the code structure for the Adapter pattern
interface TargetInterface with operation method that client expects, class AdapteeClass with specificOperation method that has different signature, class Adapter implements TargetInterface with private AdapteeClass member, Adapter operation method calls adaptee.specificOperation to translate the interface
What problem does the Adapter pattern solve?
The system uses a single interface to abstract vendor-specific implementations such as a Projector interface, but vendor-provided drivers cannot be modified to implement the interface because they are provided by manufacturers. The Adapter translates between the expected interface and the actual vendor implementation
When should you use the Adapter design pattern?
When you need to enable communication between incompatible systems, when you want to reuse existing code or libraries without rewriting them, when you need to simplify integration of new components while keeping the system flexible
What is the Facade design pattern?
A structural pattern that simplifies interactions with complex subsystems. It provides a unified easy-to-use interface while hiding internal details, reducing complexity for clients and promoting cleaner more maintainable code
What problem does the Facade pattern solve?
Module M is used by multiple other modules as context, but M's interface is complex and clients find it difficult to use as the problem. The Facade provides a simpler interface for M that hides the complexity of coordinating multiple subsystem classes
Give an example of how Facade simplifies client code
Without Facade the client must create Scanner, Parser, AST, CodeGen objects and call them in correct sequence like parser.parse then codegen.generate. With Facade the client only creates Interpreter object and calls interpreter.run with the code, the Facade handles all subsystem coordination internally
What is the Decorator design pattern?
A structural pattern that allows adding functionality to a class through composition rather than inheritance. Decorators wrap around objects to add new features without creating an excessive number of subclasses, avoiding exponential growth of class combinations
What problem does the Decorator pattern solve?
Basic implementations are not sufficient and we need to add extra functionalities like compression, buffering, logging. Creating subclasses for all combinations leads to exponential growth, such as 4 features times 2 protocols equals 32 plus subclasses needed. This is rigid, inflexible, and violates the Open Closed Principle
Give the code structure for the Decorator pattern
interface Component with operation method, class ConcreteComponent implements Component, abstract class Decorator implements Component with protected Component wrappedComponent member and constructor taking Component, Decorator operation calls wrappedComponent.operation, concrete decorators extend Decorator and add behavior before or after calling super.operation
How does the Decorator pattern enable flexible composition?
Like nested gift boxes, Decorators wrap around objects such as TCPChannel or UDPChannel to add new features. You can stack multiple decorators such as Component c equals new ConcreteComponent, c equals new ConcreteDecorator1 of c, c equals new ConcreteDecorator2 of c, each adding its own behavior while maintaining the interface
Compare Decorator pattern versus using inheritance for adding features
Decorator uses composition allowing dynamic runtime combination of features and avoiding class explosion. Inheritance creates rigid compile-time hierarchies requiring separate subclasses for each combination leading to exponential growth. Decorator follows Open Closed Principle, inheritance violates it when new features are added
What is the Strategy design pattern?
A behavioral pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable. It allows parameterizing the algorithms used by a class
What problem does the Strategy pattern solve?
A class has hardcoded algorithm such as Quicksort with no flexibility in algorithm choice and clients have different performance needs. The class is closed for extension and cannot easily support other algorithms like ShellSort or HeapSort. Strategy allows changing algorithms at runtime
Give the code structure for the Strategy pattern
interface Strategy with algorithm method, multiple ConcreteStrategy classes implement Strategy with different algorithms, class Context with private Strategy member and default strategy in constructor, setStrategy method to change strategy, executeStrategy method calls strategy.algorithm
How do you implement the Strategy pattern in two steps?
Step 1: Define a Strategy hierarchy where each strategy corresponds to a specific algorithm, create interface Strategy and concrete implementations like ConcreteStrategy1, ConcreteStrategy2, ConcreteStrategy3. Step 2: Modify the Context class to use a Strategy, add private Strategy field, provide setStrategy method, delegate algorithm execution to the strategy object
What is the Observer design pattern?
A behavioral pattern that defines a one-to-many dependency between objects where when one object called the subject changes state, all its dependents called observers are notified and updated automatically
Give the code structure for the Observer pattern
interface Observer with update method, abstract class Subject with private List of observers, addObserver and removeObserver methods, notifyObservers method that loops through observers calling update on each, ConcreteSubject extends Subject with state and setState that calls notifyObservers, ConcreteObserver implements Observer with reference to subject and update method that gets state from subject
What problem does the Observer pattern solve?
Multiple display types like digital analog web mobile thermometers must be updated when temperature changes. We want to avoid coupling the domain class Temperature directly to UI Thermometer classes to keep domain independent from UI and allow new thermometer types to be added easily
How does the Observer pattern maintain loose coupling?
The Subject maintains a list of Observer interfaces and calls their update methods but remains unaware of the observers concrete types. Observers register themselves with the subject using addObserver. When subject state changes it calls notifyObservers which executes update on each observer without knowing their specific implementations
List real-world applications of the Observer pattern
Social Media Notifications where users get updates when someone they follow posts new content, Stock Market Apps where investors receive real-time updates when stock prices change, Event Listeners in GUIs where UI components observe user actions like clicks, Weather Monitoring Systems where multiple displays update when central weather data changes
What is the Template Method design pattern?
A behavioral pattern that defines the skeleton of an algorithm in a base class while leaving certain steps as abstract methods to subclasses. Subclasses customize specific steps but preserve the overall algorithm structure
Give the code structure for the Template Method pattern
abstract class AbstractClass with public final templateMethod that calls step1, step2, step3, step4 in sequence, some steps are private concrete methods with common implementation, some steps are protected abstract methods, ConcreteClass1 and ConcreteClass2 extend AbstractClass and implement the abstract steps with their specific logic
What problem does the Template Method pattern solve?
An algorithm follows similar steps for different types such as salary calculation for public and corporate employees but with different details. Goal is to define the overall workflow in the parent class while subclasses implement the specific details of each step without changing the algorithm structure
Why is the template method declared as final?
The template method is declared final to prevent subclasses from overriding the algorithm structure. This ensures the sequence of steps remains consistent while allowing subclasses to customize only the specific step implementations through the abstract methods
When should you avoid using design patterns?
Design patterns are tools for enabling changes. If a system is unlikely to change, applying design patterns is unnecessary and leads to overengineering. Design patterns increase complexity by requiring additional classes and more code to support future flexibility
What is the trade-off of using design patterns?
Using design patterns increases complexity in order to support future changes. They often require creating additional classes, for example Strategy pattern needs 1 context class plus 1 abstract class plus 2 or more concrete strategy classes versus just 1 class without the pattern
What is Patternitis?
A possible example of overusing design patterns and adding unnecessary complexity. It occurs when developers apply patterns where they are not needed, making the code more complicated without providing real benefits for flexibility or maintainability
Compare Factory pattern versus direct instantiation with new keyword
Factory encapsulates object creation in one place allowing easy changes to creation logic and supporting OCP, client uses interface reference. Direct instantiation with new glues classes together creating tight coupling, makes switching implementations difficult, requires modifying client code when changes are needed
What are the benefits of programming to an interface?
Allows polymorphism where client declares variables using interface type, enables easy swapping of implementations without changing client code, improves testability by allowing mock objects, reduces coupling between components, follows dependency inversion principle
How does dependency injection relate to design patterns?
Dependency injection removes the responsibility of object creation from the client. Instead of client creating instances with new, dependencies are injected through constructors or setters. This works well with Factory, Proxy, Adapter, Strategy patterns by allowing injection of different implementations through interface references
Explain the relationship between Open Closed Principle and design patterns
Open Closed Principle states classes should be open for extension but closed for modification. Design patterns support OCP by allowing new behavior through subclassing, composition, or strategy injection without modifying existing code. Factory allows new products, Strategy allows new algorithms, Decorator allows new features, all without changing existing classes
What is the difference between Proxy and Decorator patterns?
Proxy controls access to an object and typically manages one wrapped object for purposes like caching, lazy initialization, access control. Decorator adds new functionality and can stack multiple decorators to combine features. Both implement the same interface as the wrapped object but have different intents
What is the difference between Adapter and Facade patterns?
Adapter makes two incompatible interfaces work together, wrapping one adaptee to match a target interface, typically one-to-one relationship. Facade provides a simplified interface to a complex subsystem with multiple classes, hides complexity, typically one-to-many relationship. Adapter translates, Facade simplifies
What is the difference between Strategy and Template Method patterns?
Strategy uses composition where algorithms are separate objects that can be swapped at runtime, favors composition over inheritance, more flexible. Template Method uses inheritance where algorithm structure is in parent class and subclasses fill in specific steps, steps cannot be changed at runtime, enforces consistent algorithm structure
Compare Singleton pattern with static classes
Singleton allows lazy initialization and can implement interfaces enabling polymorphism and dependency injection, can be passed as parameter, supports inheritance. Static classes cannot implement interfaces, cannot be passed as objects, cannot be lazily initialized, less flexible for testing and extension
What makes a good design pattern implementation?
Clear separation of concerns, follows SOLID principles especially OCP and DIP, uses interfaces for abstraction, enables easy testing through dependency injection, balances flexibility with simplicity, avoids overengineering, has single responsibility, properly encapsulates what varies
How do you decide between using composition or inheritance?
Use composition when you need runtime flexibility to change behavior, when you want to combine multiple features, when relationship is has-a. Use inheritance when behavior is intrinsic to the object type, when relationship is is-a, when you need to enforce consistent structure like Template Method. Favor composition over inheritance for flexibility
What is the key principle behind the Factory pattern regarding object creation?
The Factory pattern eliminates the new keyword from client code because whenever there is new it creates glue between classes. By encapsulating object creation in a factory method, it provides a single point of change if the object type must be updated such as switching from TCP to UDP
Explain how the Proxy pattern enables adding functionality without modifying existing code
The Proxy implements the same interface as the RealSubject and wraps it. The proxy can add preprocessing like checking cache or logging before delegating to the real object, and postprocessing like storing results after delegation. The RealSubject remains unchanged and unaware of the proxy
What are the key components of the Singleton pattern implementation?
First: private static instance variable to hold the single instance. Second: private constructor to prevent external instantiation using new. Third: public static getInstance method that checks if instance is null, creates it if needed, and returns the instance. Fourth: business logic methods that operate on the single instance
How does the Adapter pattern follow the principle of composition over inheritance?
The Adapter uses composition by holding a reference to the Adaptee object rather than inheriting from it. The Adapter implements the target interface and delegates calls to the adaptee's methods, translating the interface without modifying the adaptee or creating tight inheritance coupling
Describe the structure of decorators as nested wrappers
Decorators work like nested gift boxes wrapping around objects. Each decorator implements the component interface and holds a reference to another component. You can stack decorators such as BufferChannel wrapping ZipChannel wrapping TCPChannel, each layer adding its behavior before or after delegating to the inner component
What is the role of the abstract Decorator class in the Decorator pattern?
The abstract Decorator class implements the Component interface and holds a protected Component reference. It provides default implementation that delegates to the wrapped component. Concrete decorators extend this base class and override methods to add their specific behavior before or after calling super to maintain the delegation chain
How does the Strategy pattern support the Open Closed Principle?
The Strategy pattern allows adding new algorithms by creating new ConcreteStrategy classes that implement the Strategy interface without modifying the Context class or existing strategies. The Context is open for extension through new strategies but closed for modification since its core logic remains unchanged
Explain the flow of notification in the Observer pattern
First: Observer objects register with the Subject using addObserver. Second: Subject maintains a list of all registered observers. Third: When subject state changes, it calls notifyObservers. Fourth: notifyObservers loops through the observer list calling update on each. Fifth: Each observer's update method retrieves the new state from subject and reacts accordingly
What is the purpose of making the template method final in Template Method pattern?
Declaring the template method as final prevents subclasses from overriding the algorithm structure and sequence of steps. This ensures the workflow remains consistent across all subclasses while still allowing them to customize the implementation of individual abstract steps, maintaining the algorithm's integrity
How does the Factory pattern support parameterization of object types?
The Factory method takes a parameter such as a string type like TCP or UDP and uses conditional logic to decide which concrete class to instantiate. This allows the client to specify what type of object it needs without knowing the concrete class names or instantiation logic, achieving loose coupling
What is the relationship between design patterns and software maintainability?
Design patterns improve maintainability by providing proven solutions that make code easier to understand through shared vocabulary, easier to modify through loose coupling and proper abstraction, easier to extend through OCP compliance, and easier to test through dependency injection and interface-based design
Describe how caching is implemented in the Proxy pattern example
The Proxy maintains a private Map cache to store results. In the request method, it first checks if the requested data exists in the cache using containsKey. If found it returns the cached result immediately. If not found it delegates to the realSubject to perform the actual operation, then stores the result in cache before returning it
What are the differences between behavioral, structural, and creational patterns?
Creational patterns focus on object creation mechanisms to increase flexibility and code reuse, examples include Factory and Singleton. Structural patterns focus on assembling objects and classes into larger structures while keeping them flexible, examples include Proxy, Adapter, Facade, Decorator. Behavioral patterns focus on algorithms and responsibility assignment between objects, examples include Strategy, Observer, Template Method
How do design patterns provide a shared vocabulary for developers?
Design patterns give names to common solutions like Singleton, Factory, Observer. When developers say a class is a Singleton, others immediately understand it has one instance and global access. When documentation mentions Factory pattern, developers know it encapsulates object creation. This shared language improves communication, documentation clarity, and code understanding
Explain the principle of programming to an interface not an implementation
Declare variables using interface types like BookSearch searcher rather than concrete types like BookSearchProxy searcher. This allows assigning any implementation to the variable, makes code flexible for swapping implementations, enables dependency injection, improves testability with mocks, and reduces coupling between components
What is the benefit of using interfaces in the Proxy pattern?
Both Proxy and RealSubject implement the same interface allowing them to be used interchangeably. The client holds an interface reference and doesn't know if it's communicating with the real object or proxy. This enables transparent addition of caching, logging, access control without client code changes
How does the Adapter pattern enable reuse of existing code?
The Adapter allows using existing classes with incompatible interfaces without modifying them. Vendor-provided classes like projector drivers cannot be changed but the Adapter wraps them and translates their interface to match what the client expects, enabling integration and reuse of the existing functionality
What is the significance of the protected access modifier in Decorator pattern?
The Decorator base class uses protected Component wrappedComponent so that concrete decorators can access the wrapped component directly if needed. This allows decorators to call methods on the wrapped object before and after adding their own behavior while maintaining encapsulation from external classes
Describe the two-step process for implementing the Strategy pattern
Step One: Define a Strategy hierarchy by creating an interface Strategy with an algorithm method and implementing multiple ConcreteStrategy classes each with different algorithm implementations. Step Two: Modify the Context class by adding a private Strategy field, providing a setStrategy method to change strategies at runtime, and having executeStrategy delegate to strategy.algorithm
What is the role of the Context class in the Strategy pattern?
The Context class maintains a reference to a Strategy object, provides a method to change the strategy at runtime through setStrategy, and delegates algorithm execution to the current strategy. It acts as the client-facing interface while hiding the strategy implementation details and enabling algorithm interchangeability
How does the Observer pattern achieve loose coupling between Subject and Observers?
The Subject only knows about the Observer interface not concrete observer types. Observers register themselves without Subject knowing their implementation. Subject notifies all observers through the interface update method. Observers pull state from Subject when notified. This allows adding new observer types without modifying Subject
Explain why multiple inheritance would be problematic for the Decorator pattern problem
With 4 features like compression, buffering, logging, encryption and 2 base protocols like TCP and UDP, you would need 2 to the power of 4 times 2 equals 32 plus subclasses for all combinations. Adding a fifth feature doubles the subclasses needed. This exponential growth is unmanageable, violates OCP, and creates rigid inflexible code
What is the difference between delegation and inheritance in design patterns?
Delegation uses composition where one object holds a reference to another and forwards calls to it, allowing runtime flexibility and composition of behaviors as in Decorator and Strategy. Inheritance creates compile-time is-a relationships where subclass inherits parent behavior, less flexible but useful for enforcing structure as in Template Method
How does the Template Method pattern balance flexibility and control?
Template Method provides control by defining the algorithm skeleton in a final method that cannot be overridden, ensuring consistent workflow. It provides flexibility by declaring certain steps as abstract methods that subclasses must implement, allowing customization of specific behaviors while maintaining the overall structure
What problem arises from tight coupling in the Temperature and Thermometer example?
Direct coupling means Temperature class would need to know about all concrete Thermometer types like DigitalThermometer, AnalogThermometer, WebThermometer. This violates separation of concerns by coupling domain logic to UI classes, makes adding new thermometer types require modifying Temperature class, creates maintenance burden and violates OCP
Describe how the Factory pattern would be used in a payment gateway system
Create a PaymentProcessor interface with process method. Implement concrete processors like StripeProcessor and PayPalProcessor. Create PaymentProcessorFactory with createProcessor method taking string type parameter. Based on user selection the factory returns the correct payment processor instance. Client code uses PaymentProcessor interface reference without knowing concrete implementation
What are the advantages of using abstract methods in Template Method pattern?
Abstract methods force subclasses to provide implementations for variable steps ensuring all necessary behaviors are defined. They document which parts of the algorithm need customization. They enable polymorphism allowing the template method to call subclass-specific implementations. They maintain the algorithm structure while allowing behavioral variations
How do you implement lazy initialization in the Singleton pattern?
In getInstance method, check if the static instance variable is null. If null create new instance and assign to instance variable. If not null skip creation. Return the instance. This delays object creation until first access improving startup performance and avoiding unnecessary resource allocation if the singleton is never used
What is the benefit of using a factory over direct instantiation in testing?
Factories allow injecting mock or stub objects for testing by modifying the factory method to return test doubles. Direct instantiation with new creates hard dependencies on concrete classes making it difficult to substitute test implementations. Factories enable dependency injection and improve testability by centralizing object creation
Explain how the Facade pattern improves code maintainability
Facade hides subsystem complexity behind a simple interface reducing the learning curve for clients. Changes to subsystem structure only require updating the Facade not all clients. It reduces dependencies between client code and subsystem classes. It provides a clear entry point for using complex functionality making code easier to understand and maintain
What is the relationship between design patterns and SOLID principles?
Design patterns embody SOLID principles: Factory supports OCP by allowing new products without modifying factory users, Decorator supports OCP by adding features without changing existing code, Strategy supports OCP and DIP by depending on abstractions, Proxy and Adapter support SRP by separating concerns, patterns use interfaces following DIP
How does the Decorator pattern differ from simply adding methods to a class?
Adding methods to a class modifies the class directly requiring access to source code and affecting all instances. Decorator uses composition to wrap objects dynamically at runtime, allows stacking multiple decorators for combinations, doesn't require modifying original class, follows OCP, enables selecting features per instance not per class
What is the purpose of the notifyObservers method in Observer pattern?
notifyObservers encapsulates the iteration logic for notifying all registered observers. It loops through the observer list calling update on each observer. This centralization ensures all observers are notified consistently when subject state changes and allows subject to manage the notification mechanism without observers needing to poll
Describe the role of interfaces in achieving polymorphism in design patterns
Interfaces define contracts that multiple classes can implement allowing them to be used interchangeably through interface references. Strategy interface allows swapping algorithms, Component interface allows treating decorated and undecorated objects uniformly, Observer interface allows subject to notify different observer types, enabling flexible extensible designs
How would you combine Factory and Singleton patterns?
Make the Factory class a Singleton to ensure only one factory instance exists. The factory's getInstance method returns the single factory instance. The factory's create methods instantiate products. This is useful when factory maintains state like caching created objects or needs centralized configuration for object creation
What is the significance of the Gang of Four book published in 1994?
The Gang of Four book presented a catalog of 23 design patterns and established the concept of design patterns in software engineering. It defined design patterns as descriptions of communicating objects and classes customized to solve general design problems. It created a shared vocabulary and formalized solutions to recurring problems that has influenced software design for decades
Explain how design patterns facilitate code reviews and team collaboration
Design patterns provide a common language allowing developers to communicate complex designs concisely by saying use Observer pattern instead of explaining the entire notification mechanism. They establish shared understanding of proven solutions reducing misunderstandings. Pattern names in code serve as documentation making architecture decisions clear during reviews and onboarding
What is the trade-off between flexibility and simplicity in design patterns?
Design patterns increase flexibility by supporting future changes through abstraction, composition, and loose coupling. However they increase complexity by adding more classes, interfaces, and indirection. The trade-off requires judging whether the flexibility is worth the added complexity based on likelihood of change and project requirement