University of Florida Evaluate a Range of Design Patterns Discussion

Description

Critically evaluate a range of design patterns with relevant examples with creational, structural and behavioural pattern types

1 attachmentsSlide 1 of 1attachment_1attachment_1

Unformatted Attachment Preview

Design Patterns:
The design pattern identifies the participating classes and instances, their roles and
collaborations, and the distribution of responsibilities.
Each design pattern focuses on a particular object-oriented design problem or issue.
It describes when it applies, whether it can be applied in view of other design constraints, and the
consequences and trade-offs of its use.
Creational Design Patterns:
In software engineering, creational design patterns are design patterns that deal with object
creation mechanisms, trying to create objects in a manner suitable to the situation. The basic
form of object creation could result in design problems or added complexity to the design.
Creational design patterns solve this problem by somehow controlling this object creation.
Creational design patterns are composed of two dominant ideas.
1. One is encapsulating knowledge about which concrete classes the system use.
2. Another is hiding how instances of these concrete classes are created and combined.
Creational design patterns are further categorized into Object-creational patterns and Classcreational patterns, where Object-creational patterns deal with Object creation and Classcreational patterns deal with Class-instantiation. In greater details, Object-creational patterns
defer part of its object creation to another object, while Class-creational patterns defer its
objection creation to subclasses.
Five well-known design patterns that are parts of creational patterns are listed as follows:
1. Abstract factory pattern:
Abstract Factory is a creational design pattern that lets you produce families of related objects
without specifying their concrete classes. Which provides an interface for creating related or
dependent objects without specifying the objects’ concrete classes
Example:
Imagine that you’re creating a furniture shop simulator. Your code consists of classes that
represent:
1. A family of related products, say: Chair + Sofa + CoffeeTable.
2. Several variants of this family. For example, products Chair + Sofa + CoffeeTable are
available in these variants: Modern, Victorian, ArtDeco.
You need a way to create individual furniture objects so that they match other objects of the
same family. Customers get quite mad when they receive non-matching furniture.
Also, you don’t want to change existing code when adding new products or families of products
to the program. Furniture vendors update their catalogs very often, and you wouldn’t want to
change the core code each time it happens.
The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each
distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all
variants of products follow those interfaces. For example, all chair variants can implement
the Chair interface; all coffee table variants can implement the CoffeeTable interface, and so on.
2. Factory method pattern:
Factory Method is a creational design pattern that provides an interface for creating objects in a
superclass, but allows subclasses to alter the type of objects that will be created. which allows a
class to defer instantiation to sub classes?
Example:
Imagine that you’re creating a logistics management application. The first version of your app
can only handle transportation by trucks, so the bulk of your code lives inside the Truck class.
After a while, your app becomes pretty popular. Each day you receive dozens of requests from
sea transportation companies to incorporate sea logistics into the app.
The Factory Method pattern suggests that you replace direct object construction calls (using
the new operator) with calls to a special factory method. Don’t worry: the objects are still created
via the new operator, but it’s being called from within the factory method. Objects returned by a
factory method are often referred to as products.
3. Builder pattern:
Builder is a creational design pattern that lets you construct complex objects step by step. The
pattern allows you to produce different types and representations of an object using the same
construction code. which separates the construction of a complex object from its representation
so that the same construction process can create different representation.
Example:
Imagine a complex object that requires laborious, step-by-step initialization of many fields and
nested objects. Such initialization code is usually buried inside a monstrous constructor with lots
of parameters. Or even worse: scattered all over the client code.
In most cases most of the parameters will be unused, making the constructor calls pretty ugly.
For instance, only a fraction of houses have swimming pools, so the parameters related to
swimming pools will be useless nine times out of ten.
The Builder pattern suggests that you extract the object construction code out of its own class
and move it to separate objects called builders.
4. Prototype pattern:
Prototype is a creational design pattern that lets you copy existing objects without making your
code dependent on their classes. which specifies the kind of object to create using a prototypical
instance, and creates new objects by cloning this prototype.
Example:
Say you have an object, and you want to create an exact copy of it. How would you do it? First,
you have to create a new object of the same class. Then you have to go through all the fields of
the original object and copy their values over to the new object.
Nice! But there’s a catch. Not all objects can be copied that way because some of the object’s
fields may be private and not visible from outside of the object itself.
The Prototype pattern delegates the cloning process to the actual objects that are being cloned.
The pattern declares a common interface for all objects that support cloning. This interface lets
you clone an object without coupling your code to the class of that object. Usually, such an
interface contains just a single clone method.
5. Singleton pattern:
Singleton is a creational design pattern that lets you ensure that a class has only one instance,
while providing a global access point to this instance. which ensures that a class only has one
instance, and provides a global point of access to it.
Example:
The Singleton pattern solves two problems at the same time, violating the Single Responsibility
Principle:
1. Ensure that a class has just a single instance. Why would anyone want to control how
many instances a class has? The most common reason for this is to control access to some
shared resource—for example, a database or a file.
2. Provide a global access point to that instance. Remember those global variables that
you (all right, me) used to store some essential objects? While they’re very handy, they’re
also very unsafe since any code can potentially overwrite the contents of those variables
and crash the app.
Structural Design Patterns:
In software engineering, structural design patterns are design patterns that ease the design by
identifying a simple way to realize relationships between entities.
Structural patterns are for tying together existing function.
Examples of Structural Patterns include:
1. Adapter:
Adapter is a structural design pattern that allows objects with incompatible interfaces
to collaborate. Adapts one interface for a class into one that a client expects
Example:
Imagine that you’re creating a stock market monitoring app. The app downloads the stock data
from multiple sources in XML format and then displays nice-looking charts and diagrams for the
user.
At some point, you decide to improve the app by integrating a smart 3rd-party analytics library.
But there’s a catch: the analytics library only works with data in JSON format.
You can create an adapter. This is a special object that converts the interface of one object so
that another object can understand it.
2. Bridge:
Bridge is a structural design pattern that lets you split a large class or a set of closely related
classes into two separate hierarchies—abstraction and implementation—which can be developed
independently of each other.Decouple an abstraction from its implementation so that the two can
vary independently.
Example:
Say you have a geometric Shape class with a pair of subclasses: Circle and Square. You want to
extend this class hierarchy to incorporate colors, so you plan to create Red and Blue shape
subclasses. However, since you already have two subclasses, you’ll need to create four class
combinations such as BlueCircle and RedSquare.
This problem occurs because we’re trying to extend the shape classes in two independent
dimensions: by form and by color. That’s a very common issue with class inheritance.
3. Composite:
Composite is a structural design pattern that lets you compose objects into tree structures and
then work with these structures as if they were individual objects. A tree structure of objects
where every object has the same interface.
Example:
Using the Composite pattern makes sense only when the core model of your app can be
represented as a tree.
The Composite pattern suggests that you work with Products and Boxes through a common
interface which declares a method for calculating the total price.
4. Decorator:
Decorator is a structural design pattern that lets you attach new behaviors to objects by placing
these objects inside special wrapper objects that contain the behaviors. Add additional
functionality to a class at runtime where subclassing would result in an exponential rise of new
classes
Example:
Imagine that you’re working on a notification library which lets other programs notify their users
about important events.
Extending a class is the first thing that comes to mind when you need to alter an object’s
behavior. However, inheritance has several serious caveats that you need to be aware of.
5. Facade:
Facade is a structural design pattern that provides a simplified interface to a library, a
framework, or any other complex set of classes. Create a simplified interface of an existing
interface to ease usage for common tasks.
Example:
Imagine that you must make your code work with a broad set of objects that belong to a
sophisticated library or framework. Ordinarily, you’d need to initialize all of those objects, keep
track of dependencies, execute methods in the correct order, and so on.
A facade is a class that provides a simple interface to a complex subsystem which contains lots
of moving parts. A facade might provide limited functionality in comparison to working with the
subsystem directly. However, it includes only those features that clients really care about.
6. Flyweight:
Flyweight is a structural design pattern that lets you 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 object. A high quantity of objects share a common properties object to save space.
Example:
To have some fun after long working hours, you decided to create a simple video game: players
would be moving around a map and shooting each other. You chose to implement a realistic
particle system and make it a distinctive feature of the game. Vast quantities of bullets, missiles,
and shrapnel from explosions should fly all over the map and deliver a thrilling experience to the
player.
On closer inspection of the Particle class, you may notice that the color and sprite fields consume
a lot more memory than other fields. What’s worse is that these two fields store almost identical
data across all particles. For example, all bullets have the same color and sprite.
7. Proxy:
Proxy is a structural design 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. A class functioning as an interface
to another thing.
Example:
Why would you want to control access to an object? Here is an example: you have a massive
object that consumes a vast amount of system resources. You need it from time to time, but not
always.
The Proxy pattern suggests that you create a new proxy class with the same interface as an
original service object. Then you update your app 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 Design Patterns
In software engineering, behavioral design patterns are design patterns that identify common
communication patterns between objects and realize these patterns. By doing so, these patterns
increase flexibility in carrying out this communication.
Behavioral patterns influence how state and behavior flow through a system. By optimizing how
state and behavior are transferred and modified, you can simplify, optimize, and increase the
maintainability of an application.
Below is a list of common behavioral design patterns.
1. Chain of responsibility:
Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain
of handlers. Upon receiving a request, each handler decides either to process the request or to
pass it to the next handler in the chain. Command objects are handled or passed on to other
objects by logic-containing processing objects.
Example:
Imagine that you’re working on an online ordering system. You want to restrict access to the
system so only authenticated users can create orders. Also, users who have administrative
permissions must have full access to all orders.
Like many other behavioral design patterns, the Chain of Responsibility relies on transforming
particular behaviors into stand-alone objects called handlers. In our case, each check should be
extracted to its own class with a single method that performs the check. The request, along with
its data, is passed to this method as an argument.
2. Command:
Command is a behavioral design pattern that turns a request into a stand-alone object that
contains all information about the request. This transformation lets you pass requests as a method
argument, delay or queue a request’s execution, and support undoable operations. Command
objects encapsulate an action and its parameters.
Example:
Imagine that you’re working on a new text-editor app. Your current task is to create a toolbar
with a bunch of buttons for various operations of the editor. You created a very neat Button class
that can be used for buttons on the toolbar, as well as for generic buttons in various dialogs.
Good software design is often based on the principle of separation of concerns, which usually
results in breaking an app into layers. The most common example: a layer for the graphical user
interface and another layer for the business logic. The GUI layer is responsible for rendering a
beautiful picture on the screen, capturing any input and showing results of what the user and the
app are doing. However, when it comes to doing something important, like calculating the
trajectory of the moon or composing an annual report, the GUI layer delegates the work to the
underlying layer of business logic.
3. Iterator:
Iterator is a behavioral design pattern that lets you traverse elements of a collection without
exposing its underlying representation (list, stack, tree, etc.). The pattern restricts direct
communications between the objects and forces them to collaborate only via a mediator object.
Iterators are used to access the elements of an aggregate object sequentially without exposing its
underlying representation.
Example:
Collections are one of the most used data types in programming. Nonetheless, a collection is just
a container for a group of objects.
Most collections store their elements in simple lists. However, some of them are based on stacks,
trees, graphs and other complex data structures.
The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a
separate object called an iterator.
4. Mediator:
Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between
objects. Provides a unified interface to a set of interfaces in a subsystem.
Example:
Say you have a dialog for creating and editing customer profiles. It consists of various form
controls such as text fields, checkboxes, buttons, etc.
Some of the form elements may interact with others. For instance, selecting the “I have a dog”
checkbox may reveal a hidden text field for entering the dog’s name. Another example is the
submit button that has to validate values of all fields before saving the data.
The Mediator pattern suggests that you should cease all direct communication between the
components which you want to make independent of each other. Instead, these components must
collaborate indirectly, by calling a special mediator object that redirects the calls to appropriate
components. As a result, the components depend only on a single mediator class instead of being
coupled to dozens of their colleagues.
5. Memento:
Memento is a behavioral design pattern that lets you save and restore the previous state of an
object without revealing the details of its implementation. Provides the ability to restore an
object to its previous state (rollback)
Example:
Imagine that you’re creating a text editor app. In addition to simple text editing, your editor can
format text, insert inline images, etc.
At some point, you decided to let users undo any operations carried out on the text. This feature
has become so common over the years that nowadays people expect every app to have it. For the
implementation, you chose to take the direct approach. Before performing any operation, the app
records the state of all objects and saves it in some storage. Later, when a user decides to revert
an action, the app fetches the latest snapshot from the history and uses it to restore the state of all
objects.
All problems that we’ve just experienced are caused by broken encapsulation. Some objects try
to do more than they are supposed to. To collect the data required to perform some action, they
invade the private space of other objects instead of letting these objects perform the actual action.
6. Observer:
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify
multiple objects about any events that happen to the object they’re observing. also known as
Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by
another object.
Example:
Imagine that you have two types of objects: a Customer and a Store. The customer is very
interested in a particular brand of product (say, it’s a new model of the iPhone) which should
become available in the store very soon.
The customer could visit the store every day and check product availability. But while the
product is still enrooted, most of these trips would be pointless.
The object that has some interesting state is often called subject, but since it’s also going to
notify other objects about the changes to its state, we’ll call it publisher. All other objects that
want to track changes to the publisher’s state are called subscribers.
The Observer pattern suggests that you add a subscription mechanism to the publisher class so
individual objects can subscribe to or unsubscribe from a stream of events coming from that
publisher. Fear not! Everything isn’t as complicated as it sounds. In reality, this mechanism
consists of 1) an array field for storing a list of references to subscriber objects and 2) several
public methods which allow adding subscribers to and removing them from that list.
7. State Pattern:
State is a behavioral design pattern that lets an object alter its behavior when its internal state
changes. It appears as if the object changed its class. A clean way for an object to partially
change its type at runtime.
Example:
The State pattern is closely related to the concept of a Finite-State Machine.
The State pattern suggests that you create new classes for all possible states of an object and
extract all state-specific behaviors into these classes.
Instead of implementing all behaviors on its own, the original object, called context, stores a
reference to one of the state objects that represents its current state, and delegates all the staterelated work to that object.
8. Strategy:
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of
them into a separate class, and make their objects interchangeable. Algorithms can be selected on
the fly.
Example:
One day you decided to create a navigation app for casual travelers. The app was centered
around a beautiful map which helped users quickly orient themselves in any city.
One of the most requested features for the app was automatic route planning. A user should be
able to enter an address and see the fastest route to that destination displayed on the map.
The Strategy pattern suggests that you take a class that does something specific in a lot of
different ways and extract all of these algorithms into separate classes called strategies.
9. Template Method:
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the
superclass but let us subclasses override specific steps of the algorithm without changing
its structure. Describes the program skeleton of a program.
Example:
Imagine that you’re creating a data mining application that analyzes corporate documents. Users
feed the app documents in various formats (PDF, DOC, CSV), and it tries to extract meaningful
data from these docs in a uniform format.
The first version of the app could work only with DOC files. In the following version, it was able
to support CSV files. A month later, you “taught” it to extract data from PDF files.
The Template Method pattern suggests that you break down an algorithm into a series of steps,
turn these steps into methods, and put a series of calls to these methods inside a single template
method. The steps may either be abstract, or have some default implementation. To use the
algorithm, the client is supposed to provide its own subclass, implement all abstract steps, and
override some of the optional ones if needed (but not the template method itself).
10.Visitor Pattern:
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on
which they operate. A way to separate an algorithm from an object.
Example:
Imagine that your team develops an app which works with geographic information structured as
one colossal graph. Each node of the graph may represent a complex entity such as a city, but
also more granular things like industries, sightseeing areas, etc. The nodes are connected with
others if there’s a road between the real objects that they represent. Under the hood, each node
type is represented by its own class, while each specific node is an object.
The Visitor pattern suggests that you place the new behavior into a separate class called visitor,
instead of trying to integrate it into existing classes. The original object that had to perform the
behavior is now passed to one of the visitor’s methods as an argument, providing the method
access to all necessary data contained within the object.
11.Iterator Pattern:
Iterator is a behavioral design pattern that lets you traverse elements of a collection without
exposing its underlying representation (list, stack, tree, etc.). Implement a specialized computer
language to rapidly solve a specific set of problems.
Example:
Collections are one of the most used data types in programming. Nonetheless, a collection is just
a container for a group of objects.
The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a
separate object called an iterator.
Refferences:
GOF Patterns Design Patterns Course(Introduction) (gofpatterns.com)
Refactoring GURU Iterator (refactoring.guru)
Creational Pattern Creational Design Patterns – Javatpoint
Three types of design patterns The 3 Types of Design Patterns All Developers Should Know (with code
examples of each) (freecodecamp.org)
Design patterns Design Patterns (sourcemaking.com)
Design patterns Design Patterns | Set 1 (Introduction) – GeeksforGeeks
Java design patterns Java Design Patterns – Example Tutorial – JournalDev

Purchase answer to see full
attachment

Explanation & Answer:
800 Words

Tags:
programming

Design Patterns

behavioural pattern types

User generated content is uploaded by users for the purposes of learning and should be used following Studypool’s honor code & terms of service.

Reviews, comments, and love from our customers and community:

Article Writing

Keep doing what you do, I am really impressed by the work done.

Alexender

Researcher

PowerPoint Presentation

I am speechless…WoW! Thank you so much!

Stacy V.

Part-time student

Dissertation & Thesis

This was a very well-written paper. Great work fast.

M.H.H. Tony

Student

Annotated Bibliography

I love working with this company. You always go above and beyond and exceed my expectations every time.

Francisca N.

Student

Book Report / Review

I received my order wayyyyyyy sooner than I expected. Couldn’t ask for more.

Mary J.

Student

Essay (Any Type)

On time, perfect paper

Prof. Kate (Ph.D)

Student

Case Study

Awesome! Great papers, and early!

Kaylin Green

Student

Proofreading & Editing

Thank you Dr. Rebecca for editing my essays! She completed my task literally in 3 hours. For sure will work with her again, she is great and follows all instructions

Rebecca L.

Researcher

Critical Thinking / Review

Extremely thorough summary, understanding and examples found for social science readings, with edits made as needed and on time. Transparent

Arnold W.

Customer

Coursework

Perfect!

Joshua W.

Student

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>