Podcast
Questions and Answers
Which design pattern ensures a class has only one instance and provides a global access point to it?
Which design pattern ensures a class has only one instance and provides a global access point to it?
- Singleton (correct)
- Factory Method
- Builder
- Abstract Factory
What is the primary purpose of creational design patterns?
What is the primary purpose of creational design patterns?
- To compose objects into tree structures
- To define communication between objects
- To define an interface for creating related objects
- To provide object creation mechanisms that increase flexibility and reuse (correct)
Which design pattern would you use if you want to create different types of objects in a superclass?
Which design pattern would you use if you want to create different types of objects in a superclass?
- Builder
- Factory Method (correct)
- Singleton
- Abstract Factory
What benefit does the Prototype pattern offer when creating new objects?
What benefit does the Prototype pattern offer when creating new objects?
In what situation would the Abstract Factory pattern be most applicable?
In what situation would the Abstract Factory pattern be most applicable?
When is it most appropriate to use the Builder pattern?
When is it most appropriate to use the Builder pattern?
What is the intent of the Adapter pattern?
What is the intent of the Adapter pattern?
How does the Bridge pattern address the issue of tightly coupled class hierarchies?
How does the Bridge pattern address the issue of tightly coupled class hierarchies?
In the Composite pattern, what is the key difference between the 'Component' and 'Composite' elements?
In the Composite pattern, what is the key difference between the 'Component' and 'Composite' elements?
What is the main goal of the Decorator pattern?
What is the main goal of the Decorator pattern?
What problem does the Facade pattern solve?
What problem does the Facade pattern solve?
What is the main purpose of the Flyweight pattern?
What is the main purpose of the Flyweight pattern?
What is the primary purpose of the Proxy pattern?
What is the primary purpose of the Proxy pattern?
Which problem does the Iterator pattern primarily address?
Which problem does the Iterator pattern primarily address?
What is the core purpose of the Observer pattern?
What is the core purpose of the Observer pattern?
Flashcards
Design Patterns
Design Patterns
Reusable solutions to commonly occurring problems in software design.
Features of Design Patterns
Features of Design Patterns
Name, problem, solution, and consequences are described.
Creational Patterns
Creational Patterns
Patterns dealing with object creation mechanisms.
Structural Patterns
Structural Patterns
Signup and view all the flashcards
Behavioral Patterns
Behavioral Patterns
Signup and view all the flashcards
Singleton Pattern
Singleton Pattern
Signup and view all the flashcards
Factory Method Pattern
Factory Method Pattern
Signup and view all the flashcards
Prototype Pattern
Prototype Pattern
Signup and view all the flashcards
Abstract Factory Pattern
Abstract Factory Pattern
Signup and view all the flashcards
Builder Pattern
Builder Pattern
Signup and view all the flashcards
Adapter Pattern
Adapter Pattern
Signup and view all the flashcards
Bridge Pattern
Bridge Pattern
Signup and view all the flashcards
Composite Pattern
Composite Pattern
Signup and view all the flashcards
Decorator Pattern
Decorator Pattern
Signup and view all the flashcards
Facade Pattern
Facade Pattern
Signup and view all the flashcards
Study Notes
- Design patterns provide reusable solutions to common software design problems
- They started as industry best practices applied multiple times to similar problems
- Design patterns serve as customizable templates or blueprints for developers
- They are not specific pieces of code, but general concepts for solving problems
- Used to design the architecture of an entire software system
Design Pattern Discovery
- Design patterns emerge in the software industry through repeated use of solutions
- A solution is named and described in detail after being used in various projects
Essential Features of Design Patterns
- Pattern Name: Describes the design problem, solution, and consequences
- Problem: Explains when and why to use the pattern and its context
- Solution: Details the design elements, relationships, responsibilities, and collaborations
- Consequences: Covers the results and trade-offs of applying the pattern, including flexibility, extensibility, portability, and time and space considerations
Categories of Design Patterns
- Design patterns vary in complexity, detail, and applicability scope
- Developers can implement design patterns in any language
- Object-oriented design patterns fall into three categories: creational, structural, and behavioral
Creational Patterns
- Creational patterns focus on object creation mechanisms
- They increase flexibility and reuse of existing code
- Examples of creational patterns include Singleton, Factory Method, Prototype, Abstract Factory, and Builder
Structural Patterns
- Structural patterns describe how objects are composed into larger groups
- They explain how to assemble objects and classes into larger structures
- Structural patterns keep structures flexible and efficient
Behavioral Patterns
- Behavioral patterns describe how responsibilities are distributed among objects
- They also describe how communication happens between objects
Creational Patterns Details
- Creational design patterns are about class instantiation
- They deal with object creation mechanisms suitable to certain situations
- They solve problems by controlling object creation to avoid design complexities
- There are five creational patterns
Singleton Pattern
- Ensures that a class has only one instance and provides a global access point to it
Singleton Problem
- Solves two problems simultaneously, violating the Single Responsibility Principle
- Ensures a class has only one instance to control access to a shared resource such as a database or a file
- Provides a global access point, similar to global variables but safer since the instance cannot be overwritten
Singleton Solution
- The Singleton pattern implementation has two steps
- Make the default constructor private to prevent other objects from using the new operator with a Singleton class
- Create a static creation method that acts as a constructor, this method will call the private constructor to create an object and saves it in a static field
Factory Method Pattern
- Provides an interface for creating objects in a superclass
- Allows subclasses to alter the type of objects that will be created
Factory Method Problem
- The first version of the app can only handle transportation by trucks, so the bulk of the code lives inside the Truck class
- He receives dozens of requests from sea transportation companies to incorporate sea logistics into the app
- Most code is coupled to the Truck class, adding Ships would requires changes to the entire codebase
- If he decides to add another type of transportation to the app later, he will probably need to make all of these changes again
Factory Method Solution
- Replace direct object construction using the
new
operator with calls to a special factory method - Objects are still created via the
new
operator, but it's being called from within the factory method - Objects returned by this factory method are often referred to as "products"
Prototype Pattern
- Lets a developer copy existing objects without making their code dependent on their classes
Prototype Problem
- When a developer wants to create an exact copy of an object, s/he has to create a new object of the same class
- Then, s/he has to go through all the fields of the original object and copy their values over to the new object
- The problem here is not all objects can be copied that way because some of the objects' field may be private and may not be visible from outside of the object itself
- Another problem to this approach is that since s/he has to know the object's class to create a duplicate, his/her code becomes dependent on the class
Prototype Solution
- Delegates the cloning process to the actual objects being cloned
- Declares a common interface for all objects that support cloning
- Allows a developer to clone an object without coupling the code to the class of that object
- Usually, such an interface contains just a single clone() method
Abstract Factory Pattern
- Allows developers to produce families of related objects without specifying their concrete classes
- A family of objects that are usually used together
- Set of objects that are dependent on each other in some way
Abstract Factory Problem
- He needs a way to create individual furniture objects so that they match the other objects of the same family
- The developer also doesn't want to change the existing code when adding new products or families of products to the program
- Furniture vendors update their catalogs very often, and he wouldn't want to change the core code each time it happens
Abstract Factory Solution
- Explicitly declare interfaces for each distinct product of the product family
- Declare an Abstract Factory interface with a list of creation methods for all products that are part of the product family
- For each variant of a product family, create a separate factory class based on the Abstract Factory interface
- The client code has to work with both factories and products through their respective abstract interfaces
Builder Pattern
- Allows developers to construct complex objects step by step
- Allows developers to produce different types and representations of an object using the same construction code
Builder Problem
- The initialization of an object will usually contain lots of parameters or will scatter all over the client code
- The simplest solution he might implement is to extend the base House class and create a set of subclasses to cover the additional parameters
- But the problem of this approach will create a considerable number of subclasses, so any additional new parameter will require growing this hierarchy even more
Builder Solution
- Must extract the object construction code out of its own class and move it to separate objects called builders
- Organizes object construction into a set of steps or methods such as buildWalls(),buildDoor(), buildWindows(), etc
- The construction steps might require different implementation when the program needs to build various representations of the product
Structural Patterns Details
- Deal with the arrangement and relationship between the classes in the software system
- All about grouping classes together and providing ways for objects to coordinate to get work done
- Can also control and grant access to an object
- Can add new functionalities to existing objects
- There are seven (7) design patterns in this category
Adapter Pattern
- Allows objects with incompatible interfaces to collaborate
- Converts the interface of a class into another interface as expected by the client application
Adapter Problem
- The software downloads the stock data from multiple sources in XML format and then displays the charts and diagrams for the user
- But the problem is that this third-party library only works with data in JSON format
- He might also not have access to the third-party library's source code, making this approach impossible
Adapter Solution
- A developer can create a special object called
adapter
that converts the interface of one (1) object so that another object can understand it - An adapter wraps one of the objects to hide the complexity of conversion happening behind the scenes
- Example, developers can wrap an object that operates in meters and kilometers with an adapter that converts all of the data to imperial units such as feet and miles
Bridge Pattern
- Allows the developers to split a large class or a set of closely related classes into two (2) separate hierarchies
- Abstraction and implementations that can be developed independently of each other
Bridge Problem
- When the developer wants to extend this class hierarchy to incorporate colors, he will create Red and Blue shape subclasses
- However, the program already has two (2) subclasses, so the developer needs to create four (4) class combinations
- Adding new shape types and colors to the hierarchy will grow it exponentially, so adding new types would require creating several subclasses for each type
Bridge Solution
- Solves this problem by switching from inheritance to the object composition
- The developer must extract one (1) of the dimensions into a separate class hierarchy so that the original classes will reference an object of the new hierarchy instead of having all of its states and behaviors within a single class
- class then gets a reference field pointing to one (1) of the color objects
- That reference will act as a bridge between the Shape and Color classes
- This design architecture allows the adding of new colors without changing the shape hierarchy, and vice versa
Composite Pattern
- Allows developers to compose objects into tree structures and then work with these structures treating them as individual objects
Composite Problem
- Contains several Products as well as a number of smaller Boxes
- These Boxes can also hold some Products or even smaller Boxes, and so on
- To determine the total price of such an order, the developer will need to unwrap all the boxes and calculate the total price, this approach can be hard or even impossible
Composite Solution
- Must work with Products and Boxes through a common interface which declares a method for calculating the total price
- By simply making a product to return its price, for a box, it will go over each item the box contains, ask its price, and then returns the total for this box
- If a box contains smaller boxes, those boxes will also start going over their contents and so on, until the prices of all inner components are calculated. A box could even add some extra cost to the final price, such as packaging cost
Decorator Pattern
- Allows developers to attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors
Decorator Problem
- Some of the clients wanted to receive an SMS notification, while the others through social media
- Requires the developer needs to extend the Notifier class and put additional notification methods into new subclasses
- Creating special subclasses which combine several notification methods within a single class will make the code bigger, not only the library code but the client code as well
Decorator Solution
- A wrapper contains the same set of methods as the target and delegates it to all requests it receives
- Implements the same interface as the wrapped object then makes the wrapper's reference accept any object that follows that interface
- This will cover an object in multiple wrappers, adding the combined behavior of all the wrappers to it
Facade Pattern
- Provides a simplified interface to a library, a framework, or any other complex set of classes
Facade Problem
- He will simply need to initialize all of those objects, keep track of dependencies, execute methods in the correct order, and so on
- As a result, the business logic of his classes would become tightly coupled to the implementation details of third-party classes, making it hard to comprehend and maintain
Facade Solution
- A facade is a class that provides a simple interface to a complex subsystem which contains lots of moving parts
- However, it includes only those features that clients really care about
- Using a facade is convenient when the program needs to integrate with a library that has dozens of features, but the program only needs its few functionalities
Flyweight Pattern
- Allows developers to fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each other
Flyweight Problem
- Each particle, such as the bullet, is represented by a separate object containing plenty of data
- When the program creates multiple particles, some of these particles may not fit into the remaining memory-hence the crash
Flyweight Solution
- Creating an object that is divided into two (2) parts
- The state-dependent part and the state-independent part
- In the given problem, the particle system objects shared some fields, such as color and sprit, these are state-independents and their values remain constant
- The state-independent is stored in the Flyweight object
Proxy Pattern
- Allows developers to provide a substitute or placeholder for another object
- A proxy controls access to the original object
- Allows developers to perform something before or after the requests gets through to the original object
Proxy Problem
- Developers want to control access to an object
- The developer can do this by creating the object only when it's actually needed
- However, this will cause a lot of code duplication
Proxy Solution
- Creating a new proxy class with the same interface as an original service object
- Updating the application so that it passes the proxy object to all of the original object's clients
- Upon receiving a request from a client, the proxy creates a real service object and delegates all the work to it
Behavioral Patterns Details
- Concerned with how classes and objects behave in a system software and how objects communicate with each other
- Some of the aspects of these patterns are to assign behavioral responsibilities to classes
Iterator Pattern
- Allows developers to traverse elements of a collection without exposing its underlying representation, such as list, stack, and tree
- This pattern is used for sequentially iterating and accessing items from a collection of items
Iterator Problem
- Adding several search algorithms to the collection gradually blurs its primary responsibility, which is efficient data storage
- Since collections provide different ways of accessing their elements, developers need to couple their code to the specific collection classes
Iterator Solution
- Extract the search behavior of a collection into a separate object called an iterator
- An iterator object encapsulates all of the traversal details, such as the current position and how many elements are left till the end
- Because of this, several iterators can go through the same collectionindependently of each otherat the same time
Observer Pattern
- Allows developers to define a subscription mechanism to notify multiple objects about any events that happen to the object they are observing
- Means that when an object changes state, all of its dependents are notified and updated automatically
Observer Problem
- The store can send lots of e-mails to all customers each time a new product becomes available to save time for some customers, but it's going to upset others who aren't interested in new products
Observer Solution
- Adding a subscription mechanism to the publisher class so individual objects can subscribe to or unsubscribe from a stream of events coming from that publisher
- Consists of an array of field for storing a list of references to subscriber objects and several public methods which allow adding subscribers to and removing them from the list
Strategy Pattern
- Allows developers to define a family of algorithms, put each of them into a separate class, and make their objects interchangeable
Strategy Problem
- The main class of the navigator doubled in size every time a new routing algorithm is added
- This makes the application hard to maintain; any changes to the algorithms affect the whole class, increasing the chance of an error to occur in already-working code
Strategy Solution
- Must have a field of storing a reference to one of the strategies
- The class the works with this the stores algorithms, must delegates the work to a linked strategy object instead of executing it on its own
- Make the client select an appropriate algorithm by passing it to the context
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.