SlideShare uma empresa Scribd logo
1 de 42
Design Patterns
Robert Brown
@robby_brown
What is a Design Pattern?


After working on related problems, patterns often
appear in the solutions.
Formalized description of best practice.
Singleton
What is a Singleton?

 A singleton is an object that only has one instance for
 the lifetime of the application.
 Some things are not safe to have more than one
 instance running. For example, an updater.
 Objective-C classes are singletons by design. You can
 take advantage of this when creating singletons.
Creating a Singleton



 https://gist.github.com/1116294
Related Patterns


Abstract Factory
Plug-in Registry
Notification Center
Delegate
What is a Delegate?

A delegate defines the behavior of a generic class.
This keeps implementation specific behavior out of the
generic class.
Data sources are similar to delegates, except they
define content rather than behavior.
UITableViews use both a delegate and a data source.
Delegate Interaction

            UIApplication




                            UIApplication
                              Delegate
Delegate Interaction

                     UITableView




       UITableView                 UITableView
       DataSource                   Delegate
Gotchas


Use “assign” instead of “retain” to avoid retain cycles.
  When using assign, be sure to nullify the delegate
  reference when deallocating the object.
Use “weak” instead of “assign” when using ARC.
Related Patterns
Data Source
Block Delegation
Callback
Chain of Responsibility
State
Flyweight
Block Delegation
What is Block Delegation?
Similar to a delegate object.
Rather than give an object that has one or more
methods defined, give a block that has the
implementation of one method.
Rule of thumb: If you have three or more delegate
methods, use a delegate. Otherwise, use block
delegation.
  Sometimes it’s appropriate to break this rule.
Block Delegation Interaction

                 Object




       Block 1            Block 2
Gotchas

Watch out for retain cycles, particularly with “self”
  __block __unsafe_unretained id selfRef = self;
  __block __weak id selfRef = self;
Don’t forget to copy your blocks. They are created on
the stack.
Related Patterns


Delegate
Callback
Model View Controller
What is MVC?
A strict organization of classes into their different roles.
  Model: Any underlying data.
  View: The graphical presentation of the data.
  Controller: Coordinates the interactions between the
  views and model.
Keeps programs modular and makes it easy to swap
out views when needed.
Model View Controller

Interface   View             Controller   Xcode
 Builder



                     Model



                   Core Data
Gotchas


Some implementations of MVC have the View and
Model directly connected. This can cause infinite
update cycles.
Related Patterns
Observer
Layers
What is the Layer Pattern?

 Modules of a program can be organized like a stack of
 layers.
 Strict Layering: A layer can only use the layer directly
 below it.
 Non-strict Layering: A layer can use any layer below it.
Core Data Layers
                       Application

                           NSManagedObject Subclass
  NSManagedObject
     Context
                                NSManagedObject

 NSPersistentStoreCoordinator   NSManagedObjectModel

                    NSPersistentStore

 XML       SQLite      Binary   In Memory   Custom
Gotchas

Occasionally you may find a need to call up a layer. To
do this, you will need to use dependency inversion.
Dependency inversion: A lower layer defines an
interface to interact with other layers. This is often used
with notifications. An upper layer can register itself to
receive these notifications through the defined
interface.
Façade
What is a Façade?

A façade is a single entry point to a complex collection
of classes.
Makes interaction with complex collections easier and
less dependent on internal implementation.
This is the basis of the layer pattern.
External   External   External
 Object     Object     Object




           Façade




Object                Object




Object     Object     Object
Related Patterns


Class cluster
Layer
Proxy
Observer
What is an Observer?

Sometimes you want to know when an object
changes.
Often used with MVC.
  When a model object changes, you want to update
  the view(s) accordingly.
The observer pattern is built into every NSObject via
Key-Value Observing (KVO).
Gotchas



Don’t forget to remove an object as an observer when
that object is deallocated.
Related Patterns


Model View Controller
Notification Center
Proxy
What is a Proxy?
A proxy receives actions in behalf of another object.
Many types of proxies:
  Lazy loading proxy
  Distributed (network) proxy (NSDistantObject)
  Immutable proxy
NSProxy can be used to make any kind of proxy
object.
Lazy Loading Proxy


   Object   Proxy    Photo
Distributed Proxy


                           Remote
Object   Proxy   Network   Object
Immutable Proxy


                    Mutable
   Object   Proxy   Object
Gotchas



If you use NSProxy, you need to be very familiar with
message forwarding.
Want to Learn More?


Design Patterns: Elements of Reusable Object-
Oriented Software
  Every developer should own this book!
Cocoa Design Patterns in the Apple Docs
Questions?

Mais conteúdo relacionado

Mais procurados

Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
Matteo Baglini
 
Introduction to nodejs
Introduction to nodejsIntroduction to nodejs
Introduction to nodejs
James Carr
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
Yung-Lin Ho
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
Behrad Zari
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
LearningTech
 

Mais procurados (20)

Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in Android
 
Paris Tech Meetup talk : Troubles start at version 1.0
Paris Tech Meetup talk : Troubles start at version 1.0Paris Tech Meetup talk : Troubles start at version 1.0
Paris Tech Meetup talk : Troubles start at version 1.0
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
 
Introduction to nodejs
Introduction to nodejsIntroduction to nodejs
Introduction to nodejs
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Module Ninja .JS
Module Ninja .JSModule Ninja .JS
Module Ninja .JS
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Redux
ReduxRedux
Redux
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 

Destaque (9)

Design Patterns in iOS
Design Patterns in iOSDesign Patterns in iOS
Design Patterns in iOS
 
iOS design patterns: blocks
iOS design patterns: blocksiOS design patterns: blocks
iOS design patterns: blocks
 
iOS Design Patterns
iOS Design PatternsiOS Design Patterns
iOS Design Patterns
 
Carlos lineo
Carlos lineoCarlos lineo
Carlos lineo
 
Peña - Analisis de datos multivariantes
Peña - Analisis de datos multivariantesPeña - Analisis de datos multivariantes
Peña - Analisis de datos multivariantes
 
Robert Hooke
Robert Hooke Robert Hooke
Robert Hooke
 
Claudio Galeno
Claudio GalenoClaudio Galeno
Claudio Galeno
 
Robert hooke
Robert hookeRobert hooke
Robert hooke
 
Cientificos y sus aportaciones a la bilogia
Cientificos y sus aportaciones a la bilogiaCientificos y sus aportaciones a la bilogia
Cientificos y sus aportaciones a la bilogia
 

Semelhante a Mac/iOS Design Patterns

Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
Jason Townsend, MBA
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 

Semelhante a Mac/iOS Design Patterns (20)

JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp concepts
 
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
 
Dependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSDependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJS
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
Design patterns
Design patternsDesign patterns
Design patterns
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
ActionScript Design Patterns
ActionScript Design Patterns ActionScript Design Patterns
ActionScript Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with Actionscript
 
Core Data
Core DataCore Data
Core Data
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 

Mais de Robert Brown

Mais de Robert Brown (11)

High level concurrency
High level concurrencyHigh level concurrency
High level concurrency
 
Data Source Combinators
Data Source CombinatorsData Source Combinators
Data Source Combinators
 
Elixir
ElixirElixir
Elixir
 
Reactive Cocoa
Reactive CocoaReactive Cocoa
Reactive Cocoa
 
UIKit Dynamics
UIKit DynamicsUIKit Dynamics
UIKit Dynamics
 
iOS State Preservation and Restoration
iOS State Preservation and RestorationiOS State Preservation and Restoration
iOS State Preservation and Restoration
 
Anti-Patterns
Anti-PatternsAnti-Patterns
Anti-Patterns
 
Pragmatic blocks
Pragmatic blocksPragmatic blocks
Pragmatic blocks
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Quick Look for iOS
Quick Look for iOSQuick Look for iOS
Quick Look for iOS
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Mac/iOS Design Patterns

  • 2. What is a Design Pattern? After working on related problems, patterns often appear in the solutions. Formalized description of best practice.
  • 4. What is a Singleton? A singleton is an object that only has one instance for the lifetime of the application. Some things are not safe to have more than one instance running. For example, an updater. Objective-C classes are singletons by design. You can take advantage of this when creating singletons.
  • 5. Creating a Singleton https://gist.github.com/1116294
  • 6. Related Patterns Abstract Factory Plug-in Registry Notification Center
  • 8. What is a Delegate? A delegate defines the behavior of a generic class. This keeps implementation specific behavior out of the generic class. Data sources are similar to delegates, except they define content rather than behavior. UITableViews use both a delegate and a data source.
  • 9. Delegate Interaction UIApplication UIApplication Delegate
  • 10. Delegate Interaction UITableView UITableView UITableView DataSource Delegate
  • 11. Gotchas Use “assign” instead of “retain” to avoid retain cycles. When using assign, be sure to nullify the delegate reference when deallocating the object. Use “weak” instead of “assign” when using ARC.
  • 12. Related Patterns Data Source Block Delegation Callback Chain of Responsibility State Flyweight
  • 14. What is Block Delegation? Similar to a delegate object. Rather than give an object that has one or more methods defined, give a block that has the implementation of one method. Rule of thumb: If you have three or more delegate methods, use a delegate. Otherwise, use block delegation. Sometimes it’s appropriate to break this rule.
  • 15. Block Delegation Interaction Object Block 1 Block 2
  • 16. Gotchas Watch out for retain cycles, particularly with “self” __block __unsafe_unretained id selfRef = self; __block __weak id selfRef = self; Don’t forget to copy your blocks. They are created on the stack.
  • 19. What is MVC? A strict organization of classes into their different roles. Model: Any underlying data. View: The graphical presentation of the data. Controller: Coordinates the interactions between the views and model. Keeps programs modular and makes it easy to swap out views when needed.
  • 20. Model View Controller Interface View Controller Xcode Builder Model Core Data
  • 21. Gotchas Some implementations of MVC have the View and Model directly connected. This can cause infinite update cycles.
  • 24. What is the Layer Pattern? Modules of a program can be organized like a stack of layers. Strict Layering: A layer can only use the layer directly below it. Non-strict Layering: A layer can use any layer below it.
  • 25. Core Data Layers Application NSManagedObject Subclass NSManagedObject Context NSManagedObject NSPersistentStoreCoordinator NSManagedObjectModel NSPersistentStore XML SQLite Binary In Memory Custom
  • 26. Gotchas Occasionally you may find a need to call up a layer. To do this, you will need to use dependency inversion. Dependency inversion: A lower layer defines an interface to interact with other layers. This is often used with notifications. An upper layer can register itself to receive these notifications through the defined interface.
  • 28. What is a Façade? A façade is a single entry point to a complex collection of classes. Makes interaction with complex collections easier and less dependent on internal implementation. This is the basis of the layer pattern.
  • 29. External External External Object Object Object Façade Object Object Object Object Object
  • 32. What is an Observer? Sometimes you want to know when an object changes. Often used with MVC. When a model object changes, you want to update the view(s) accordingly. The observer pattern is built into every NSObject via Key-Value Observing (KVO).
  • 33. Gotchas Don’t forget to remove an object as an observer when that object is deallocated.
  • 34. Related Patterns Model View Controller Notification Center
  • 35. Proxy
  • 36. What is a Proxy? A proxy receives actions in behalf of another object. Many types of proxies: Lazy loading proxy Distributed (network) proxy (NSDistantObject) Immutable proxy NSProxy can be used to make any kind of proxy object.
  • 37. Lazy Loading Proxy Object Proxy Photo
  • 38. Distributed Proxy Remote Object Proxy Network Object
  • 39. Immutable Proxy Mutable Object Proxy Object
  • 40. Gotchas If you use NSProxy, you need to be very familiar with message forwarding.
  • 41. Want to Learn More? Design Patterns: Elements of Reusable Object- Oriented Software Every developer should own this book! Cocoa Design Patterns in the Apple Docs

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n