Professional Documents
Culture Documents
Full Ebook of Software Design Patterns The Ultimate Guide First Edition Edition Sufyan Bin Uzayr Online PDF All Chapter
Full Ebook of Software Design Patterns The Ultimate Guide First Edition Edition Sufyan Bin Uzayr Online PDF All Chapter
https://ebookmeta.com/product/bootstrap-the-ultimate-guide-1st-
edition-sufyan-bin-uzayr/
https://ebookmeta.com/product/linux-the-ultimate-guide-1st-
edition-sufyan-bin-uzayr/
https://ebookmeta.com/product/kotlin-the-ultimate-guide-1st-
edition-sufyan-bin-uzayr/
https://ebookmeta.com/product/typescript-for-beginners-the-
ultimate-guide-1st-edition-sufyan-bin-uzayr-2/
TypeScript for Beginners: The Ultimate Guide 1st
Edition Sufyan Bin Uzayr
https://ebookmeta.com/product/typescript-for-beginners-the-
ultimate-guide-1st-edition-sufyan-bin-uzayr/
https://ebookmeta.com/product/vuepress-quick-start-guide-sufyan-
bin-uzayr/
https://ebookmeta.com/product/mastering-gnome-a-beginners-guide-
first-edition-sufyan-bin-uzayr/
https://ebookmeta.com/product/mastering-mysql-for-web-a-
beginners-guide-first-edition-edition-sufyan-bin-uzayr-ed/
https://ebookmeta.com/product/mastering-r-a-beginners-guide-
sufyan-bin-uzayr-editor/
Software Design Patterns
As a programmer, you can use Software Design Patterns to help you build more re-
liable structures. Design Patterns give you the skills to create smart and interactive
applications or software with simple and easy problem-solving methods; they also
allow you to create the greatest user-friendly apps and change them easily to meet
the latest requirements. Design Patterns are interesting to deal with since such
knowledge enables flexible coding patterns and techniques of structure, reusable
codes, loosely written codes, classes, patterns, and so on.
DOI: 10.1201/9781003308461
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
Acknowledgments, xv
About the Author, xvii
Delegation 23
Composition 23
Aggregation 23
Contract Design 24
Cohesion 24
Principle of Least Knowledge 24
The Open-Closed Principle 24
Composition vs. Inheritance in Object-Oriented Design Patterns 25
Inheritance 25
Composition 26
Favoring Composition over Inheritance in Java (with Examples) 27
Inheritance 28
Composition 29
Composition over Inheritance 30
IS INHERITANCE EXTINCT? A CLOSER LOOK AT THE
DECORATOR PATTERN 30
Exploding Class Hierarchy 31
To the Rescue Comes the Decorator Pattern 33
Decorators Queue 34
Testability 35
Other Advantages 35
Drawbacks 36
Decorator Pattern Has Native Support 37
Abstract Decorator 38
When Should We Use Inheritance? 39
KEY POINTS 40
EXAMPLE 66
CHECKLIST 66
RULES OF THUMB 66
Here’s a Real-World Example of an Observer Pattern in Java 67
IMPLEMENT THE OBSERVER PATTERN 67
Another Example 69
IObservable and IObserver (C#) Observer 71
USAGE 73
APPRAISAL, 197
BIBLIOGRAPHY, 419
INDEX, 429
Acknowledgments
There are many people who deserve to be on this page, for this book would
not have come into existence without their support. That said, some names
deserve a special mention, and I am genuinely grateful to:
xv
About the Author
Sufyan bin Uzayr is a writer, coder, and entrepreneur with over a decade
of experience in the industry. He has authored several books in the past, per-
taining to a diverse range of topics, ranging from History to Computers/IT.
Sufyan is the Director of Parakozm, a multinational IT company spe-
cializing in EdTech solutions. He also runs Zeba Academy, an online
learning and teaching vertical with a focus on STEM fields.
Sufyan specializes in a wide variety of technologies, such as JavaScript,
Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees,
including ones in Management, IT, Literature, and Political Science.
Sufyan is a digital nomad, dividing his time between four countries. He
has lived and taught in universities and educational institutions around
the globe. Sufyan takes a keen interest in technology, politics, literature,
history, and sports, and in his spare time, he enjoys teaching coding and
English to young students.
Learn more at sufyanism.com.
xvii
Chapter 1
Crash Course in
Software Design
Patterns
IN THIS CHAPTER
now might not be applicable tomorrow. And our code should be adaptable
enough that changes are not prohibitively expensive. As a result, Design
Patterns are best practices for covering such properties. The essence of
Design Patterns, in my opinion, consists of the following six rules:
Design Pattern
Creational
Class instantiation or object generation is the focus of these Design Patterns.
Class-creational patterns and object-creational patterns are two subsets of
these patterns. While class-creation patterns make good use of inheritance
in the instantiation process, object-creation patterns use delegation.
Factory Method, Abstract Factory, Builder, Singleton, Object Pool, and
Prototype are creational Design Patterns.
Structural
These Design Patterns deal with grouping distinct classes and objects
together to create larger structures and add new functionality.
Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Private
Class Data, and Proxy are structural Design Patterns.
Behavioral
Identifying and discovering shared communication patterns between
items are all about behavioral patterns.
Chain of Responsibility, Command, Interpreter, Iterator, Mediator,
Memento, Null Object, Observer, State, Scheme, Template method, and
Visitor are behavioral patterns.
Crash Course in Software Design Patterns ◾ 7
CRITICISM
Some programmers have questioned the concept of Design Patterns.
No Official Foundations
The study of Design Patterns has been overly ad hoc, and some suggest that
the subject urgently needs to be formalized. One of the GOF was exposed
to a show trial at OOPSLA 1999, in which they were “charged” with several
crimes against computer science. Twenty-three of the “jurors” present at
the trial “convicted” them.
1 https://sourcemaking.com/design_patterns
Crash Course in Software Design Patterns ◾ 13
1. The MVC Design Pattern: The MVC Design Pattern was the first
architectural pattern, and it consists of the following three parts:
• Model: The model consists of the backend business logic and
data.
Crash Course in Software Design Patterns ◾ 17
• View: Input starts here, and the required action is displayed here.
• View-Model: It has no reference to view; its sole function is to
keep the state of view and adjust the model when view actions
change.
• Factory Pattern
• Abstract Factory Pattern
• Builder Pattern
• Prototype Pattern
• Singleton Pattern
20 ◾ Software Design Patterns: The Ultimate Guide
• Adapter Pattern
• Bridge Pattern
• Composite Pattern
• Decorator Pattern
• Facade Pattern
• Proxy Pattern
• Flyweight Pattern
• Template Pattern
• Visitor Pattern
• Creational Patterns
• Structural Patterns
• Behavioral Patterns
Encapsulation
To guarantee data encapsulation, widespread manipulation of an object’s
variables by other objects or classes is often discouraged. A class should
provide methods that allow other objects to access variables. Objects that
are no longer in use are deleted by Java (garbage collection).
Abstraction
Java supports the abstraction of data specification and its concrete
application.
Crash Course in Software Design Patterns ◾ 23
The idea is separated from the concrete, which means that we define a
class first, which contains the variables and the behavior (methods), and then
we construct the actual objects, which all behave how the class described it.
A class is the behavior and data specification. A class cannot use directly.
A genuine object that may be dealt with is an object is an instance of
this class.
Polymorphisms
The capacity of object variables to hold objects of various kinds. If class X1
is a subclass of class X, then a method specified with a parameter for an
object X may be invoked on an object X1.
If we establish a supertype for a collection of classes, any subclass of that
supertype may use in place of the supertype.
Any object that implements the interface may be used as an argument
when an interface is utilized as a polymorphic type.
Inheritance
Classes may be based on each other because of inheritance. When class A
inherits another class B, this is referred to as “class A extends class B.”
For example, we may design a basic class that offers logging capabil-
ity and is extended by another class that adds email notification to the
functionality.
Delegation
Delegation occurs when we transfer responsibility for a certain job to
another class or method.
If we need to access functionality from another class but do not want to
alter it, use delegation instead of inheritance.
Composition
When referring to a group of behaviors, you use composition. We program
against an interface, and any class that implements that interface may be cre-
ated. The composition class is still declared in the caller class in composition.
When you use composition, the composing object owns the behaviors that
it employs, and they cease to exist when the composing object disappears.
Aggregation
Aggregation enables us to utilize functionality from another class without
restricting its lifespan.
24 ◾ Software Design Patterns: The Ultimate Guide
Contract Design
Contract programming requires that both parties in a transaction under-
stand what actions cause what behavior and will abide by that contract.
When failures occur in the programming by contract environment,
methods often produce null or unchecked exceptions.
Throw an unchecked runtime exception if you feel a method should
not be invoked in a certain manner. This has the potential to be really
effective. Instead of checking for exceptions in your calling code, you just
throw an exception in the called function. As a result, you may more easily
pinpoint the location in the code where an issue occurred. This adheres to
the “crash-early” philosophy, which states that if an error happens in your
software, you should crash promptly rather than later in the program since
this makes it challenging to discover the issue.
Cohesion
A system’s cohesiveness should be high.
Cohesion is how closely connected and concentrated a particular class’s
obligations are. It is advantageous in object-oriented programming to allo-
cate responsibilities to classes to maintain good cohesion.
In a highly coherent system, code readability and the chance of reuse
are raised while complexity is maintained reasonably.
As a result, avoid classes with many responsibilities; for example, a
Logger class should solely be responsible for logging.
Inheritance
An element that inherits from a parent element is said to have a “is a”
connection in terms of class relationships. Because a square is a shape, it
makes it logical for the square to inherit from form.
When we realize that we’re specifying the same behavior across several
instances, inheritance might be a useful pattern. In the case of software that
works with numerous sorts of shapes, we may have a method drawBorder
that is replicated across several distinct types of forms. So, what’s the big
deal, we may wonder? The problems occur when we wish to adjust drawBor-
der, or worse when we uncover a fault in the method. Refactoring involves
crawling through our project and updating each and every occurrence of
the method. A faulty drawBorder method implies we’ve now strewn the
same flaw across our source, resulting in extensive vulnerabilities.
Inheritance attempts to address this issue by abstracting the commonly
used method into a parent class that offers a generic enough implementa-
tion of drawBorder that it can be used to draw the border of any shape
regardless of type (this “genericness” is critical, as having an overly spe-
cialized base can lead to a slew of downstream issues).
26 ◾ Software Design Patterns: The Ultimate Guide
Every new class that “is a” shape may now inherit from the parent shape
class and utilize its drawBorder specification. One of the primary advantages
is efficient code reuse and easy message delegation across classes. We also gain
from following the open-closed concept, which specifies that components
should be open to expansion but closed to alteration. Assume we wanted to
add additional shapes to our software, each with its own distinct properties.
We may utilize inheritance to enhance the current drawBorder method to
add additional features without changing any code in the parent class.
While open-closed is ideal, we will sometimes need to alter the par-
ent class – maybe because we uncovered a problem or a new technique
to increase performance. Before inheritance, we had to track down every
instance of drawBorder, but now if we want to alter anything, all we have
to do is update the implementation of the parent class, and the change will
cascade down every subclass. That’s quite cool.
The disadvantage of this strategy is that altering the implementation of
the parent class would have cascade consequences on all subclasses. Isn’t
that an advantage? We’ve arrived at the double-edged sword of inheritance,
where enormous power comes with immense responsibility. Because inher-
itance makes it easy to modify the behavior of a wide portion of our code-
base with simple changes in one place, it has established tightly coupled
dependencies in our application. Every subclass is directly dependent on its
parent, and modifications in one may require changes in the other.
Another disadvantage of inheritance is that we must normally make
broad assumptions about how the program will use in the future. Maybe
we as a programmer can’t envision our drawBorder method ever being
given a form it doesn’t recognize, but we also never imagined that the
mind-bending Mobius strip would attempt to inherit from shape, and
your software would crumble.
This is why the refrain of favoring composition over inheritance is so
popular. It’s not that inheritance isn’t beneficial; nevertheless, when used
carelessly or as a solution to the incorrect issue, it may cause considerable
problems down the line, perhaps to the point where adding new function-
ality without breaking current features is almost difficult.
Composition
Composition defines a “has-a” connection, while inheritance defines a “is-
a” relationship. A project that employs composition to orchestrate com-
ponent interaction focuses on merging several little pieces that combine
forces to form something that is greater than the sum of their parts.
Another random document with
no related content on Scribd:
would be no chance to prove that McGee had stolen the fifty
thousand.
Someone was knocking on the front door! Amos trotted to the
front. It was the depot agent. He showed Amos a telegraph envelope
through the glass of the door.
Amos went to the door, shaking like a Hula dancer, and got the
message. It was for him. He jigged back to the rear door and looked
out. Then he almost swooned. Seated on the boxes, where
Ferdinand P. Putney was concealed, was the sheriff, Big Jim Potter,
smoking his pipe.
Amos staggered back to the front door. Seated on the sidewalk
across the street was “Slim” Caldwell, the deputy sheriff, watching
the bank front. Amos reeled. The clock was striking the hour, and at
every chime Amos Weed jerked inside his clothes.
Then he unlocked the door and went drunkenly toward his desk,
where he slumped in a chair, staring with unseeing eyes. The door
opened and a man came toward him. He opened his eyes. It was the
man he had directed to the doctor’s office. Amos shook his head
wearily. Nothing mattered now. He was still holding the telegram, and
now he opened it mechanically, his eyes scanning it quickly. It read:
Amos fell back in his chair, the world reeling around him. He
opened his eyes. The stranger with the cold had crouched back
against the wall, a gun in his hand, as Cloudy McGee came in
through the doorway. Slim Caldwell, the deputy sheriff, was running
across the street, almost to the door, when the stranger behind it
flung up his gun, covering McGee.
“Put ’em up, McGee!” he snapped, and McGee’s hands went up, a
look of wonder on his face.
Slim Caldwell ran in behind him, and the gun covered both of
them.
“Who are you?” asked the damp-nosed stranger of Caldwell.
“Deputy sheriff,” blurted Caldwell.
“All right. Handcuff that man.”
“But—but—” stammered the deputy.
The sheriff was coming in the back door, herding Ferdinand P.
Putney ahead of him. He stared at the tableau. The damp-nosed
stranger swung his back against the wall, half-facing the sheriff. For
several moments things were rather deadlocked.
“Who are you?” asked the stranger with the cold.
“I’m the sheriff!” snapped Jim Potter.
“And I’ve got you, Cloudy McGee!” snorted Caldwell addressing
the damp-nosed stranger, and covering him. “Drop that gun!”
The man addressed dropped his gun and Caldwell picked it up,
but before anyone could stop him, the damp-nosed man had made a
sudden dive and knocked the original McGee off his feet, and was
sitting on him.
“For heck’s sake, what’s this all about?” demanded the sheriff,
coming toward them, still clinging to Ferdinand P. Putney.
“Pud ha’d-cuffs on him, I tell you!” snapped the damp-nosed man.
“This is Cloudy McGee.”
“Yo’re crazy!” roared the sheriff. “Yo’re McGee yourself.”
“You thig so?” The damp-nosed man turned back the lapel of his
soiled vest and showed them the badge of a deputy U. S. marshal.
“By nabe is Morton,” he said thickly. “I hobe you’re sadisfied.”
“U. S. marshal?” blurted the sheriff.
“Yeah. I be been looking for Cloudy McGee, bud I didn’t hab much
of a describtion, excebt that he gambles quite a lot and is about my
size. I heard he was in Salt Wells, or aroud that part of the country.
“I med this sud-of-a-gud and he wod my horse, saddle, hat and
my gud. I thought he’d stay there bud he left; so I stole a horse and
followed him. I heard hib frame up to rob this bank. They called hib
McGee. That feller over there,” pointing at Amos, who was almost in
a state of collapse, “took ted thousad from the bank last night; so I
toog it away frob him. It’s ub in by roob.”
“Well, for the land’s sake!” blurted the man upon whom the deputy
marshal sat. “They mistook me for Cloudy McGee, and I let the
sheriff in on the deal. I thought you was McGee, because they
recognized me by that big hat which I won away from you at Salt
Wells, and we framed it to get Putney, Weed and you this morning.”
“Is thad so?” The marshal wiped his nose and stared down at the
man under him. “Who in hell are you?”
“Me? I’m the bank examiner.”
“Huh! Loogs like a mistage—dab id.”
The officer got to his feet, grinning widely.
Amos was coming toward them, holding out the telegram.
“I’ll deed it to the bank,” he quavered. “It’s a gusher, and they’re
worth more than fifty thousand dollars. Just so they don’t hang me,
I’ll agree to anything.”
The bank examiner shook his head. “That’s between you and the
bank officials, you cheap little crook.”
“Cheap?” muttered Ferdinand P. Putney. “That man must deal in
big money, if he calls a fifty-thousand steal cheap.”
The bank examiner took a roll of bills from his pocket and handed
them to the sheriff.
“Here’s the retaining fee I got from Putney last night. If you want to
prosecute him, that is evidence.”
“I dunno what I want to do,” said the sheriff blankly.
An apparition was coming in through the back door; a gobby-black
sort of a person, painted up like a war-path Indian in reds, greens,
blues, purples and black. They watched him come toward them.
“My Gawd!” blurted the sheriff. “It’s Miles Rooney!”
“It is,” wailed the editor. “Look at me! He tied me to my own press
and painted me with my own inks. I’ve been like this all night. I just
got loose!”
“Who painted you?” whispered Amos.
Miles Rooney turned his ink smeared countenance upon the
luckless cashier, pointing a gobby finger at him accusingly.
“Your friend. The man I seen you standing outside my window with
last night. The man you were talking to, darn you! Cloudy McGee!”
“The bank examiner!” exploded Amos. “He—he said he was.”
“He is,” said the sheriff. “He’s examined a lot of ’em.”
The real bank examiner and the marshal walked outside, halting
on the edge of the sidewalk, where they grinned at each other.
“You ought to take something for that cold,” said the examiner.
“The first thing you know you’ll be having pneumonia.”
“Dod be.” The officer shook his head. “You can’t scare be do
more. All by life I’be been scared of pneumonia. Never had the nerve
to visit a doctor. Bud I seen one today. Ha, ha, ha, ha! Fuddy, ain’t
id? I feel twedy years you’ger.”
“What did he say was the matter with you?”
“Hay fever.”
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.