SlideShare a Scribd company logo
1 of 79
Fundamental Design Patterns
Jun
20th May
MVC
DELEGATION PATTERN
OBJECT NEEDING A DELEGATE
It’s the object that has a delegate.
• A delegate protocol, which defines the methods a delegate may or
should implement.
• A delegate, which is the helper object that implements the
delegate protocol.
WHY USE?
• By relying on a delegate protocol instead of a concrete object,
the implementation is much more flexible
• Use this pattern to break up large classes or create generic,
reusable components.
IN APPLE FRAMEWORKS
• Apple frameworks commonly use the term DataSource to group
delegate methods that provide data.
For example, UITableViewDataSource is expected to
provide UITableViewCells to display.
• Apple frameworks typically use protocols named Delegate to
group methods that receive data or events.
For example, UITableViewDelegate is notified whenever a row is
selected.
IN APPLE FRAMEWORKS
KYE POINTS
• Delegation is listed under Behavioral Patterns.
• The delegation pattern has three parts: an object needing a
delegate, a delegate protocol and a delegate.
• This pattern allows you to break up large classes and create
generic, reusable components.
• Delegates should be weak properties in the vast majority of use
cases.
STRATEGY
PATTERN
Strategy is listed
under Behavioral
Patterns.
• The object using a strategy. This is most often a view controller
when the pattern is used in iOS app development, but it can
technically be any kind of object that needs interchangeable
behavior.
• The strategy protocol defines methods that every strategy must
implement.
• The strategies are objects that conform to the strategy protocol.
WHAT IS DIFFERENT WITH DELEGATION?
• Unlike delegation, the strategy pattern uses a family of objects.
• Delegates are often fixed at runtime. For example,
the dataSource and delegate for a UITableView can be set from
Interface Builder, and it’s rare for these to change during
runtime.
• Strategies, however, are intended to be easily interchangeable at
runtime.
WHAT IS DIFFERENT WITH DELEGATION?
HOW TO IMPLEMENT
First, you need to create a strategy protocol.
Next, add the following implementation for RottenTomatoesClient.
Finally, add the following implementation for IMDbClient.
RottenTomatoes, IMDb are websites for searching movies
FIRST, YOU NEED TO CREATE A STRATEGY
PROTOCOL.
EXPLANATION
• You’ll use ratingServiceName to display which service provided
the rating. For example, this would return “Rotten Tomatoes.”
• You’ll use fetchRatingForMovieTitle(_:success:) to fetch movie
ratings asynchronously. In a real app, you’d also likely have
a failure closure too, as networking calls don’t always succeed.
NEXT, ADD THE FOLLOWING
IMPLEMENTATION
FOR ROTTENTOMATOESCLIENT.
FINALLY, ADD THE FOLLOWING
IMPLEMENTATION FOR IMDBCLIENT.
FOR
EXAMPLE
POINT!
• Notice how the view controller doesn’t know about the
concrete implementations of MovieRatingStrategy.
WHAT SHOULD YOU BE CAREFUL ABOUT?
• Be careful about overusing this pattern.
• In particular, if a behavior won’t ever change, it’s okay to put this
directly within the consuming view controller or object context.
The trick to this pattern is knowing when to pull out behaviors,
and it’s okay to do this lazily as you determine where it’s
needed.
KEY POINTS
The strategy pattern defines a family of interchangeable
objects that can be set or switched at runtime.
This pattern has three parts: an object using a strategy, a
strategy protocol, and a family of strategy objects.
The strategy pattern is similar to the delegation pattern:
Both patterns use a protocol for flexibility. Unlike the
delegation pattern, however, strategies are meant to be
switched at runtime, whereas delegates are usually fixed.
SINGLETON
PATTERN
Singleton is listed
under Creational Patterns.
(singleton is all about
creating a shared instance.)
The singleton
Vs
The “singleton plus” pattern is also common, which provides
a shared singleton instance that allows other instances to be
created, too.
WHAT IS SINGLETON?
• The singleton pattern restricts a class to only one instance.
• Every reference to the class refers to the same underlying
instance.
WHEN SHOULD YOU USE IT?
• Use the singleton pattern when having more than one instance
of a class would cause problems, or when it just wouldn’t be
logical.
WHEN SHOULD YOU USE IT?
• An example of this is FileManager, which handles everything to
do with filesystem access. There is a “default” instance which is a
singleton, or you can create your own. You would usually create
your own if you’re using it on a background thread.
IN APPLE FRAMEWORK
If you try to uncomment the let app2 line, you’ll get a compiler error!
• If you try to uncomment the let app2 line, you’ll get a compiler
error!
YOU CAN CREATE YOUR OWN CLASS
• You first declare a public static property called shared, which is
the singleton instance.
• You mark init as private to prevent the creation of additional
instances.
• You get the singleton instance by calling MySingleton.shared.
• You’ll get a compiler error if you try to create additional
instances of MySingleton.
SINGLETON PLUS
PLUS
• You declare a shared static property just like a singleton. This is
sometimes called default instead, but it’s simply a preference for
whichever name you prefer.
• Unlike a true singleton, you declare init as public to allow
additional instances to be created.
• You get the singleton instance by
calling MySingletonPlus.shared.
• You can also create new instances, too.
WHAT SHOULD YOU BE CAREFUL ABOUT?
• The singleton pattern is very easy to overuse.
• If you encounter a situation where you’re tempted to use a
singleton, first consider other ways to accomplish your task.
For example, singletons are not appropriate if you’re simply
trying to pass information from one view controller to another.
Instead, consider passing models via an initializer or property.
• If you determine you actually do need a singleton, consider
whether a singleton plus makes more sense.
• A very most common reason why singletons are problematic is
testing. If you have state being stored in a global object like a
singleton then order of tests can matter, and it can be painful to
mock them. Both of these reasons make testing a pain.
• Lastly, beware of “code smell” indicating your use case isn’t
appropriate as a singleton at all. For example, if you often need
many custom instances, your use case may be better as a
regular object.
KEY POINTS
• The singleton pattern restricts a class to only one instance.
• The singleton plus pattern provides a “default” shared instance
but also allows other instances to be created too.
• Be careful about overusing this pattern! Before you create a
singleton, consider other ways to solve the problem without it. If
a singleton really is best, prefer to use a singleton plus over a
singleton.
MEMENTO
PATTERN
The memento pattern
allows an object to be
saved and restored.
• The originator is the object to be saved or restored.
• The memento represents a stored state.
• The caretaker requests a save from the originator and receives a
memento in response. The caretaker is responsible for persisting
the memento and, later on, providing the memento back to the
originator to restore the originator’s state.
• While not strictly required, iOS apps
typically use an Encoder to encode an
originator’s state into a memento, and
a Decoder to decode a memento back to
an originator.
In computers, encoding is the process of putting a
sequence of characters (letters, numbers, punctuation,
and certain symbols) into a specialized format for efficient
transmission or storage. Decoding is the opposite process
WHEN SHOULD YOU USE IT?
• Use the memento pattern whenever you want to save and later
restore an object’s state.
For example, you can use this pattern to implement a save
game system, where the originator is the game state (such as
level, health, number of lives, etc), the memento is saved
data, and the caretaker is the gaming system.
• Here, you define a Game: it has an internal State that holds onto
game properties, and it has methods to handle in-game actions.
You also declare Game and State conform to Codable.
WHAT IS CODABLE?
• Apple introduced Codable in Swift 4. Any type that conforms
to Codable can, in Apple’s words, “convert itself into and out of
an external representation.” Essentially, it’s a type that can save
and restore itself. Sound familiar? Yep, it’s exactly what you want
the originator to be able to do.
• Foundation provides several default encoders for you,
including JSONEncoder for converting objects to JSON data.
• Technically, you don’t need to declare this line at all. Rather, it’s
here to inform you the GameMemento is actually Data. This will
be generated by the Encoder on save, and used by
the Decoder on restoration.
• You first declare properties
for decoder, encoder and userDefaults. You’ll use decoder to
decode Games from Data, encoder to encode Games to Data,
and userDefaults to persist Data to disk. Even if the app is re-
launched, saved Game data will still be available.
• save(_:title:) encapsulates the save logic. You first use encoder to
encode the passed-in game. This operation may throw an error,
so you must prefix it with try. You then save the
resulting data under the given title within userDefaults.
• load(title:) likewise encapsulates the load logic. You first
get data from userDefaults for the given title. You then
use decoder to decode the Game from the data. If either
operation fails, you throw a custom error
for Error.gameNotFound. If both operations succeed, you return
the resulting game.
KEY POINTS
• The memento pattern allows an object to be saved and restored.
It involves three types: the originator, memento and caretaker.
• The originator is the object to be saved; the memento is a saved
state; and the caretaker handles, persists and retrieves
mementos.
• iOS provides Encoder for encoding a memento to,
and Decoder for decoding from, a memento. This allows
encoding and decoding logic to be used across originators.
OBSERVER
PATTERN
T H E O B S E R V E R P A T T E R N L E T S
O N E O B J E C T O B S E R V E
C H A N G E S O N A N O T H E R
O B J E C T .
Y O U ’ L L S E E O B S E R V E R I S
L I S T E D U N D E R B E H A V I O R A L
P A T T E R N S .
T H I S I S B E C A U S E O B S E R V E R I S
A B O U T O N E O B J E C T O B S E R V I N G
A N O T H E R O B J E C T .
• Apple added language-level support for this pattern in Swift 5.1
with the addition of Publisher in the Combine framework.
• The subscriber is the “observer” object and receives updates.
• The publisher is the “observable” object and sends updates.
• The value is the underlying object that’s changed.
• First, you import Combine, which includes
the @Published annotation and Publisher & Subscriber types.
• Next, you declare a new User class; @Published properties
cannot be used on structs or any other types besides classes.
• Next, you create a var property for name and mark it
as @Published. This tells Xcode to automatically generate
a Publisher for this property. Note that
you cannot use @Published for let properties, as by definition
they cannot be changed.
• Finally, you create an initializer that sets the initial value
of self.name.
WHAT SHOULD YOU BE CAREFUL ABOUT?
• Before you implement the observer pattern, define what you
expect to change and under which conditions. If you can’t
identify a reason for an object or property to change, you’re
likely better off not declaring it as var or @Published, and
instead, making it a let property.
• A unique identifier, for example, isn’t useful as an published
property since by definition it should never change.
KEY POINTS
• The observer pattern lets one object observe changes on
another object. It involves three types: the subscriber, publisher
and value.
• The subscriber is the observer; the publisher is the observable
object; and the value is the object that’s being changed.
• Swift 5.1 makes it easy to implement the observer pattern
using @Published properties.
BUILDER
PATTERN
The builder pattern
allows you to create
complex objects by
providing inputs step-by-
step, instead of requiring
all inputs upfront via an
initializer.
You’ll see Builder is
listed under Creational
Patterns.
• The director accepts inputs and coordinates with the builder. This
is usually a view controller or a helper class that’s used by a view
controller.
• The product is the complex object to be created. This can be
either a struct or a class, depending on desired reference
semantics. It’s usually a model, but it can be any type depending
on your use case.
• The builder accepts step-by-step inputs and handles the creation
of the product. This is often a class, so it can be reused by
reference.
WHEN SHOULD YOU USE IT?
Use the builder pattern when you want to create a complex object
using a series of steps.
This pattern works especially well when a product requires multiple
inputs.
• For example, you can use this pattern to implement a
“hamburger builder.”
• The product could be a hamburger model, which has inputs such
as meat selection, toppings and sauces.
• The director could be an employee object, which knows how to
build hamburgers, or it could be a view controller that accepts
inputs from the user.
• You first define Hamburger, which has properties
for meat, sauce and toppings. Once a hamburger is made, you
aren’t allowed to change its components, which you codify
via let properties. You also make Hamburger conform
to CustomStringConvertible, so you can print it later.
• You declare Meat as an enum. Each hamburger must have
exactly one meat selection: sorry, no beef-chicken-tofu burgers
allowed. You also specify an exotic meat, kitten. Who doesn’t
like nom nom kitten burgers?
• You define Sauces as an OptionSet. This will allow you to
combine multiple sauces together. My personal favorite is
ketchup-mayonnaise-secret sauce.
• You likewise define Toppings as an OptionSet. You’re gonna
need more than pickles for a good burger!
• You declare properties for meat, sauces and toppings, which
exactly match the inputs for Hamburger. Unlike a Hamburger,
you declare these using var to be able to change them. You also
specify private(set) for each to ensure
only HamburgerBuilder can set them directly.
• Since you declared each property using private(set), you need to
provide public methods to change them. You do so
via addSauces(_:), removeSauces(_:), addToppings(_:), removeTo
ppings(_:) and setMeat(_:).
• Lastly, you define build() to create the Hamburger from the
selections.
• private(set) forces consumers to use the public setter methods.
This allows the builder to perform validation before setting the
properties.
• For example, you’ll ensure a meat is available prior to setting it.
Nom nom beef burger
Sorry, no kitten burgers here... :[
KEY POINTS
• The builder pattern is great for creating complex objects in a
step-by-step fashion. It involves three objects: the director,
product and builder.
• The director accepts inputs and coordinates with the builder; the
product is the complex object that’s created; and the builder
takes step-by-step inputs and creates the product.
WHAT SHOULD YOU BE CAREFUL ABOUT?
• The builder pattern works best for creating complex products
that require multiple inputs using a series of steps. If your
product doesn’t have several inputs or can’t be created step by
step, the builder pattern may be more trouble than it’s worth.
• Instead, consider providing convenience initializers to create the
product.
THANK YOU

More Related Content

Similar to Fundamental Design Patterns.pptx

Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...SQALab
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Sachintha Gunasena
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010Clay Helberg
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalSidereo
 
Deep Dive Time Series Anomaly Detection in Azure with dotnet
Deep Dive Time Series Anomaly Detection in Azure with dotnetDeep Dive Time Series Anomaly Detection in Azure with dotnet
Deep Dive Time Series Anomaly Detection in Azure with dotnetMarco Parenzan
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaErick M'bwana
 
advancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptxadvancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptxssuser6a1dbf
 
Break through e2e-testing
Break through e2e-testingBreak through e2e-testing
Break through e2e-testingtameemahmed5
 
Selenium web driver | java
Selenium web driver | javaSelenium web driver | java
Selenium web driver | javaRajesh Kumar
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)Horky Chen
 
OOP -interface and objects.pptx
OOP -interface and objects.pptxOOP -interface and objects.pptx
OOP -interface and objects.pptxEdFeranil
 

Similar to Fundamental Design Patterns.pptx (20)

Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
 
Deep Dive Time Series Anomaly Detection in Azure with dotnet
Deep Dive Time Series Anomaly Detection in Azure with dotnetDeep Dive Time Series Anomaly Detection in Azure with dotnet
Deep Dive Time Series Anomaly Detection in Azure with dotnet
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
advancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptxadvancedzplmacroprogramming_081820.pptx
advancedzplmacroprogramming_081820.pptx
 
Break through e2e-testing
Break through e2e-testingBreak through e2e-testing
Break through e2e-testing
 
Selenium web driver | java
Selenium web driver | javaSelenium web driver | java
Selenium web driver | java
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)
 
OOP -interface and objects.pptx
OOP -interface and objects.pptxOOP -interface and objects.pptx
OOP -interface and objects.pptx
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
Dynamic modeling
Dynamic modelingDynamic modeling
Dynamic modeling
 

More from JUNSHIN8

Swfit_Array_GDG.pdf
Swfit_Array_GDG.pdfSwfit_Array_GDG.pdf
Swfit_Array_GDG.pdfJUNSHIN8
 
AlamofirebyJun.pdf
AlamofirebyJun.pdfAlamofirebyJun.pdf
AlamofirebyJun.pdfJUNSHIN8
 
Hapit_mid_HyunjunShin.pptx
 Hapit_mid_HyunjunShin.pptx Hapit_mid_HyunjunShin.pptx
Hapit_mid_HyunjunShin.pptxJUNSHIN8
 
[Apple_Korea] Green World
[Apple_Korea] Green World[Apple_Korea] Green World
[Apple_Korea] Green WorldJUNSHIN8
 
CoreData.pptx
CoreData.pptxCoreData.pptx
CoreData.pptxJUNSHIN8
 
Computer_Architecture.pptx
Computer_Architecture.pptxComputer_Architecture.pptx
Computer_Architecture.pptxJUNSHIN8
 
Notification_Center.pptx
Notification_Center.pptxNotification_Center.pptx
Notification_Center.pptxJUNSHIN8
 
GithubWithTerminal.pptx
GithubWithTerminal.pptxGithubWithTerminal.pptx
GithubWithTerminal.pptxJUNSHIN8
 
Algorithm Introduction.pptx
Algorithm Introduction.pptxAlgorithm Introduction.pptx
Algorithm Introduction.pptxJUNSHIN8
 

More from JUNSHIN8 (9)

Swfit_Array_GDG.pdf
Swfit_Array_GDG.pdfSwfit_Array_GDG.pdf
Swfit_Array_GDG.pdf
 
AlamofirebyJun.pdf
AlamofirebyJun.pdfAlamofirebyJun.pdf
AlamofirebyJun.pdf
 
Hapit_mid_HyunjunShin.pptx
 Hapit_mid_HyunjunShin.pptx Hapit_mid_HyunjunShin.pptx
Hapit_mid_HyunjunShin.pptx
 
[Apple_Korea] Green World
[Apple_Korea] Green World[Apple_Korea] Green World
[Apple_Korea] Green World
 
CoreData.pptx
CoreData.pptxCoreData.pptx
CoreData.pptx
 
Computer_Architecture.pptx
Computer_Architecture.pptxComputer_Architecture.pptx
Computer_Architecture.pptx
 
Notification_Center.pptx
Notification_Center.pptxNotification_Center.pptx
Notification_Center.pptx
 
GithubWithTerminal.pptx
GithubWithTerminal.pptxGithubWithTerminal.pptx
GithubWithTerminal.pptx
 
Algorithm Introduction.pptx
Algorithm Introduction.pptxAlgorithm Introduction.pptx
Algorithm Introduction.pptx
 

Recently uploaded

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 

Fundamental Design Patterns.pptx

  • 2. MVC
  • 4. OBJECT NEEDING A DELEGATE It’s the object that has a delegate.
  • 5. • A delegate protocol, which defines the methods a delegate may or should implement. • A delegate, which is the helper object that implements the delegate protocol.
  • 6. WHY USE? • By relying on a delegate protocol instead of a concrete object, the implementation is much more flexible • Use this pattern to break up large classes or create generic, reusable components.
  • 7. IN APPLE FRAMEWORKS • Apple frameworks commonly use the term DataSource to group delegate methods that provide data. For example, UITableViewDataSource is expected to provide UITableViewCells to display.
  • 8. • Apple frameworks typically use protocols named Delegate to group methods that receive data or events. For example, UITableViewDelegate is notified whenever a row is selected. IN APPLE FRAMEWORKS
  • 9. KYE POINTS • Delegation is listed under Behavioral Patterns. • The delegation pattern has three parts: an object needing a delegate, a delegate protocol and a delegate. • This pattern allows you to break up large classes and create generic, reusable components. • Delegates should be weak properties in the vast majority of use cases.
  • 11. • The object using a strategy. This is most often a view controller when the pattern is used in iOS app development, but it can technically be any kind of object that needs interchangeable behavior. • The strategy protocol defines methods that every strategy must implement. • The strategies are objects that conform to the strategy protocol.
  • 12. WHAT IS DIFFERENT WITH DELEGATION? • Unlike delegation, the strategy pattern uses a family of objects.
  • 13. • Delegates are often fixed at runtime. For example, the dataSource and delegate for a UITableView can be set from Interface Builder, and it’s rare for these to change during runtime. • Strategies, however, are intended to be easily interchangeable at runtime. WHAT IS DIFFERENT WITH DELEGATION?
  • 14. HOW TO IMPLEMENT First, you need to create a strategy protocol. Next, add the following implementation for RottenTomatoesClient. Finally, add the following implementation for IMDbClient. RottenTomatoes, IMDb are websites for searching movies
  • 15. FIRST, YOU NEED TO CREATE A STRATEGY PROTOCOL.
  • 16. EXPLANATION • You’ll use ratingServiceName to display which service provided the rating. For example, this would return “Rotten Tomatoes.” • You’ll use fetchRatingForMovieTitle(_:success:) to fetch movie ratings asynchronously. In a real app, you’d also likely have a failure closure too, as networking calls don’t always succeed.
  • 17. NEXT, ADD THE FOLLOWING IMPLEMENTATION FOR ROTTENTOMATOESCLIENT.
  • 18. FINALLY, ADD THE FOLLOWING IMPLEMENTATION FOR IMDBCLIENT.
  • 20. POINT! • Notice how the view controller doesn’t know about the concrete implementations of MovieRatingStrategy.
  • 21. WHAT SHOULD YOU BE CAREFUL ABOUT? • Be careful about overusing this pattern. • In particular, if a behavior won’t ever change, it’s okay to put this directly within the consuming view controller or object context. The trick to this pattern is knowing when to pull out behaviors, and it’s okay to do this lazily as you determine where it’s needed.
  • 22. KEY POINTS The strategy pattern defines a family of interchangeable objects that can be set or switched at runtime. This pattern has three parts: an object using a strategy, a strategy protocol, and a family of strategy objects. The strategy pattern is similar to the delegation pattern: Both patterns use a protocol for flexibility. Unlike the delegation pattern, however, strategies are meant to be switched at runtime, whereas delegates are usually fixed.
  • 23. SINGLETON PATTERN Singleton is listed under Creational Patterns. (singleton is all about creating a shared instance.)
  • 24. The singleton Vs The “singleton plus” pattern is also common, which provides a shared singleton instance that allows other instances to be created, too.
  • 25. WHAT IS SINGLETON? • The singleton pattern restricts a class to only one instance. • Every reference to the class refers to the same underlying instance.
  • 26. WHEN SHOULD YOU USE IT? • Use the singleton pattern when having more than one instance of a class would cause problems, or when it just wouldn’t be logical.
  • 27. WHEN SHOULD YOU USE IT? • An example of this is FileManager, which handles everything to do with filesystem access. There is a “default” instance which is a singleton, or you can create your own. You would usually create your own if you’re using it on a background thread.
  • 28. IN APPLE FRAMEWORK If you try to uncomment the let app2 line, you’ll get a compiler error!
  • 29. • If you try to uncomment the let app2 line, you’ll get a compiler error!
  • 30. YOU CAN CREATE YOUR OWN CLASS
  • 31. • You first declare a public static property called shared, which is the singleton instance. • You mark init as private to prevent the creation of additional instances. • You get the singleton instance by calling MySingleton.shared. • You’ll get a compiler error if you try to create additional instances of MySingleton.
  • 33. PLUS
  • 34. • You declare a shared static property just like a singleton. This is sometimes called default instead, but it’s simply a preference for whichever name you prefer. • Unlike a true singleton, you declare init as public to allow additional instances to be created. • You get the singleton instance by calling MySingletonPlus.shared. • You can also create new instances, too.
  • 35. WHAT SHOULD YOU BE CAREFUL ABOUT? • The singleton pattern is very easy to overuse.
  • 36. • If you encounter a situation where you’re tempted to use a singleton, first consider other ways to accomplish your task. For example, singletons are not appropriate if you’re simply trying to pass information from one view controller to another. Instead, consider passing models via an initializer or property.
  • 37. • If you determine you actually do need a singleton, consider whether a singleton plus makes more sense.
  • 38. • A very most common reason why singletons are problematic is testing. If you have state being stored in a global object like a singleton then order of tests can matter, and it can be painful to mock them. Both of these reasons make testing a pain.
  • 39. • Lastly, beware of “code smell” indicating your use case isn’t appropriate as a singleton at all. For example, if you often need many custom instances, your use case may be better as a regular object.
  • 40. KEY POINTS • The singleton pattern restricts a class to only one instance. • The singleton plus pattern provides a “default” shared instance but also allows other instances to be created too. • Be careful about overusing this pattern! Before you create a singleton, consider other ways to solve the problem without it. If a singleton really is best, prefer to use a singleton plus over a singleton.
  • 41. MEMENTO PATTERN The memento pattern allows an object to be saved and restored.
  • 42. • The originator is the object to be saved or restored. • The memento represents a stored state. • The caretaker requests a save from the originator and receives a memento in response. The caretaker is responsible for persisting the memento and, later on, providing the memento back to the originator to restore the originator’s state.
  • 43. • While not strictly required, iOS apps typically use an Encoder to encode an originator’s state into a memento, and a Decoder to decode a memento back to an originator.
  • 44. In computers, encoding is the process of putting a sequence of characters (letters, numbers, punctuation, and certain symbols) into a specialized format for efficient transmission or storage. Decoding is the opposite process
  • 45. WHEN SHOULD YOU USE IT? • Use the memento pattern whenever you want to save and later restore an object’s state. For example, you can use this pattern to implement a save game system, where the originator is the game state (such as level, health, number of lives, etc), the memento is saved data, and the caretaker is the gaming system.
  • 46.
  • 47. • Here, you define a Game: it has an internal State that holds onto game properties, and it has methods to handle in-game actions. You also declare Game and State conform to Codable.
  • 48. WHAT IS CODABLE? • Apple introduced Codable in Swift 4. Any type that conforms to Codable can, in Apple’s words, “convert itself into and out of an external representation.” Essentially, it’s a type that can save and restore itself. Sound familiar? Yep, it’s exactly what you want the originator to be able to do.
  • 49.
  • 50. • Foundation provides several default encoders for you, including JSONEncoder for converting objects to JSON data.
  • 51.
  • 52. • Technically, you don’t need to declare this line at all. Rather, it’s here to inform you the GameMemento is actually Data. This will be generated by the Encoder on save, and used by the Decoder on restoration.
  • 53.
  • 54. • You first declare properties for decoder, encoder and userDefaults. You’ll use decoder to decode Games from Data, encoder to encode Games to Data, and userDefaults to persist Data to disk. Even if the app is re- launched, saved Game data will still be available. • save(_:title:) encapsulates the save logic. You first use encoder to encode the passed-in game. This operation may throw an error, so you must prefix it with try. You then save the resulting data under the given title within userDefaults. • load(title:) likewise encapsulates the load logic. You first get data from userDefaults for the given title. You then use decoder to decode the Game from the data. If either operation fails, you throw a custom error for Error.gameNotFound. If both operations succeed, you return the resulting game.
  • 55. KEY POINTS • The memento pattern allows an object to be saved and restored. It involves three types: the originator, memento and caretaker. • The originator is the object to be saved; the memento is a saved state; and the caretaker handles, persists and retrieves mementos. • iOS provides Encoder for encoding a memento to, and Decoder for decoding from, a memento. This allows encoding and decoding logic to be used across originators.
  • 56. OBSERVER PATTERN T H E O B S E R V E R P A T T E R N L E T S O N E O B J E C T O B S E R V E C H A N G E S O N A N O T H E R O B J E C T . Y O U ’ L L S E E O B S E R V E R I S L I S T E D U N D E R B E H A V I O R A L P A T T E R N S . T H I S I S B E C A U S E O B S E R V E R I S A B O U T O N E O B J E C T O B S E R V I N G A N O T H E R O B J E C T .
  • 57. • Apple added language-level support for this pattern in Swift 5.1 with the addition of Publisher in the Combine framework.
  • 58. • The subscriber is the “observer” object and receives updates. • The publisher is the “observable” object and sends updates. • The value is the underlying object that’s changed.
  • 59. • First, you import Combine, which includes the @Published annotation and Publisher & Subscriber types. • Next, you declare a new User class; @Published properties cannot be used on structs or any other types besides classes. • Next, you create a var property for name and mark it as @Published. This tells Xcode to automatically generate a Publisher for this property. Note that you cannot use @Published for let properties, as by definition they cannot be changed. • Finally, you create an initializer that sets the initial value of self.name.
  • 60.
  • 61. WHAT SHOULD YOU BE CAREFUL ABOUT? • Before you implement the observer pattern, define what you expect to change and under which conditions. If you can’t identify a reason for an object or property to change, you’re likely better off not declaring it as var or @Published, and instead, making it a let property. • A unique identifier, for example, isn’t useful as an published property since by definition it should never change.
  • 62. KEY POINTS • The observer pattern lets one object observe changes on another object. It involves three types: the subscriber, publisher and value. • The subscriber is the observer; the publisher is the observable object; and the value is the object that’s being changed. • Swift 5.1 makes it easy to implement the observer pattern using @Published properties.
  • 63. BUILDER PATTERN The builder pattern allows you to create complex objects by providing inputs step-by- step, instead of requiring all inputs upfront via an initializer. You’ll see Builder is listed under Creational Patterns.
  • 64. • The director accepts inputs and coordinates with the builder. This is usually a view controller or a helper class that’s used by a view controller. • The product is the complex object to be created. This can be either a struct or a class, depending on desired reference semantics. It’s usually a model, but it can be any type depending on your use case. • The builder accepts step-by-step inputs and handles the creation of the product. This is often a class, so it can be reused by reference.
  • 65. WHEN SHOULD YOU USE IT? Use the builder pattern when you want to create a complex object using a series of steps. This pattern works especially well when a product requires multiple inputs.
  • 66. • For example, you can use this pattern to implement a “hamburger builder.” • The product could be a hamburger model, which has inputs such as meat selection, toppings and sauces. • The director could be an employee object, which knows how to build hamburgers, or it could be a view controller that accepts inputs from the user.
  • 67.
  • 68.
  • 69.
  • 70. • You first define Hamburger, which has properties for meat, sauce and toppings. Once a hamburger is made, you aren’t allowed to change its components, which you codify via let properties. You also make Hamburger conform to CustomStringConvertible, so you can print it later. • You declare Meat as an enum. Each hamburger must have exactly one meat selection: sorry, no beef-chicken-tofu burgers allowed. You also specify an exotic meat, kitten. Who doesn’t like nom nom kitten burgers? • You define Sauces as an OptionSet. This will allow you to combine multiple sauces together. My personal favorite is ketchup-mayonnaise-secret sauce. • You likewise define Toppings as an OptionSet. You’re gonna need more than pickles for a good burger!
  • 71.
  • 72. • You declare properties for meat, sauces and toppings, which exactly match the inputs for Hamburger. Unlike a Hamburger, you declare these using var to be able to change them. You also specify private(set) for each to ensure only HamburgerBuilder can set them directly. • Since you declared each property using private(set), you need to provide public methods to change them. You do so via addSauces(_:), removeSauces(_:), addToppings(_:), removeTo ppings(_:) and setMeat(_:). • Lastly, you define build() to create the Hamburger from the selections. • private(set) forces consumers to use the public setter methods. This allows the builder to perform validation before setting the properties. • For example, you’ll ensure a meat is available prior to setting it.
  • 73.
  • 74.
  • 75. Nom nom beef burger
  • 76. Sorry, no kitten burgers here... :[
  • 77. KEY POINTS • The builder pattern is great for creating complex objects in a step-by-step fashion. It involves three objects: the director, product and builder. • The director accepts inputs and coordinates with the builder; the product is the complex object that’s created; and the builder takes step-by-step inputs and creates the product.
  • 78. WHAT SHOULD YOU BE CAREFUL ABOUT? • The builder pattern works best for creating complex products that require multiple inputs using a series of steps. If your product doesn’t have several inputs or can’t be created step by step, the builder pattern may be more trouble than it’s worth. • Instead, consider providing convenience initializers to create the product.