SlideShare une entreprise Scribd logo
1  sur  61
iOS Design Patterns
    Ismael Delgado @ismaeldm
   Andreas Blick @aquarioverde
Agenda
   • MVC
   • Delegate
   • Observer
   • Command
   • Outlets, Targets & Actions
   • Singleton
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Agenda

   • Category
   • Factory Method & Abstract Factory
   • Façade
   • Mediator
   • Template Method
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Introduction
   • Templates for solving common problems
    • Problem and solution description
    • Not a library, not an algorithm!
   • Customized Solution
   • Reusability and Extensibility
   • Patterns for different purposes
iOS Design Patterns    19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Basic Principles

   • Program to an interface, not an
         implementation
   • Composition over Inheritance
   • iOS = Look & Feel driven design
    • Design first than develop
iOS Design Patterns     19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
MVC

   • Model View Controller
   • Most Cocoa Touch frameworks
   • Separation and Communication
   • Compound pattern

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
MVC
MVC




       Model

Data
MVC




       Model         View

Data                        UI
MVC
               Logica   Controller




       Model                         View

Data                                        UI
MVC
               Logica   Controller




       Model                         View

Data                                        UI
MVC
               Logica   Controller




       Model                         View

Data                                        UI
MVC
               Logica   Controller




       Model                         View

Data                                        UI
MVC
               Logica   Controller
                                     <delegate>




       Model                                      View

Data                                                     UI
MVC
               Logica   Controller
                                     <delegate>
                                        <datasource>




       Model                                           View

Data                                                          UI
MVC
               Logica   Controller
                                     <delegate>
                                        <datasource>




                                        outlet


       Model                                           View

Data                                                          UI
MVC
               Logica   Controller
                                         <delegate>
                                target      <datasource>




                                            outlet         action



       Model                                                  View

Data                                                                 UI
MVC
               Logica   Controller
                                         <delegate>
                                target      <datasource>




                                            outlet         action

KVO
       Model                                                  View

Data                                                                 UI
Delegates

   • Two objects coordination
   • Influence behaviour
   • Subclassing alternative
   • Reduce coupling
   • Name Convention (should, will, did)
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Observer

   • Publish - Subscribe
   • decouple objects with different behavior
   • Notifications

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Observer
           Notifier                                                       Observer
attachObserver                                                  update
detachObserver              for all in observers
notify                      {
                            [observer update]
                            }




  ConcreteNotifier                                                   ConcreteObserver
getState                                                        update
setState

notifierState                                                    observerState




iOS Design Patterns   19/11/2011 - Barcelona Developer Conference     @ismaeldm @aquarioverde
Observer
        Notifier                        Observer 1                           Observer 2

                                   setState


               notify




               update
                                   getState




               update
                                                                         getState




iOS Design Patterns     19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Observer
   • NSNotificationCenter / NSNotification
    • custom notifications

   • NSKeyValueObserving
    • listen to changes on certain object
              properties

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Observer
 NSNotification *notification =
    [NSNotification notificationWithName:@"BcnDevConScheduleChanged"
        object:self];

 NSNotificationCenter *notificationCenter =
    [NSNotificationCenter defaultCenter];

 [notificationCenter postNotification:notification];




 [notificationCenter addObserver:self
    selector:@selector(updateSchedule)
    name:@"BcnDevConScheduleChanged"
    object:nil];




iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Command

   • Request encapsulation
   • NSInvocation
   • Selector
   • Undo / Redo Stacks

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Outlets, Targets, Action

   • Connect User Interface objects to
         application specific operations
   • Connect views and controllers
   • based on Objective-C’s selector pattern

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Outlets, Targets, Action
   • Outlet is a reference to another object
    • id or IBOutlet
   • Stored in instance of
         NSNibOutletConnector
   • -set<Outlet>:
   • When awakeFromNib is called all outlets
         are connected

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Outlets, Targets, Action
   • Target is a special type of outlet
   • Stored in instance of
         NSNibControlConnector
   • Actions can be any method that returns
         void and accepts one argument
   • Stored as selectors
   • UIApplication sendAction:to:from
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Singleton

   • UIAccelerometer
   • Shared resources
   • Only one instance
   • Global point access

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Singleton
@interface Singleton : NSObject

+(Singleton *)sharedInstance;

@end


@implementation Singleton

static Singleton *sharedSingleton_ = nil;

+(Singleton *)sharedInstance
{
    if (sharedSingleton_ == nil)
    {
        sharedSingleton_ = [[Singleton alloc] init];
    }
    return sharedSingleton_;
}

@end


iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Singleton
 +(id)allocWithZone:(NSZone *)zone {
     return [[self sharedInstance] retain];
 }

 -(id)copyWithZone:(NSZone *)zone {
     return self;
 }

 -(id)retain {
     return self;
 }

 -(NSUInteger) retainCount {
     return NSUIntegerMax;
 }

 -(void)release {
     //do nothing
 }

 -(id)autorelease {
     return self;
 }


iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Singleton
+(Singleton *)sharedInstance
{
    @synchronized(self)
    {
        if (sharedSingleton_ == nil)
        {
            sharedSingleton_ = [[Singleton allocWi] init];
        }
    }
    return sharedSingleton_;
}


 +(Singleton *)sharedInstance
 {
     static dispatch_once_t pred = 0;
     __strong static id _sharedObject = nil;
     dispatch_once(&pred, ^{
         _sharedObject = [[self alloc] init]; // or some other init method
     });
     return _sharedObject;
 }


iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Category
   • Addition of methods to an object without
         subclassing
   • Replace methods at runtime
    • No instance variables!
   • Spread implementation over various files
   • Different methods in different frameworks
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Category
@interface UIButton (UIButton_PMProperties)

- (void)setPMDefaultButtonProperties;

@end



 #import "UIButton+PMProperties.h"

 @implementation UIButton (UIButton_PMProperties)

 - (void)setPMDefaultButtonProperties
 {
     self.titleLabel.font = [UIFont fontWithName:PM_DEFAULT_BUTTON_FONT
        size:PM_DEFAULT_BUTTON_FONT_SIZE];
     [self setTitleColor:[UIColor redColor]
        forState:UIControlStateNormal];
 }

 @end



iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Informal Protocol
   • Category header only to define classes that
         might or might not be implemented


 - (void)awakeFromNib
 {
     if ([UIControl instancesRespondToSelector:@selector(awakeFromNib)]) {
         [super awakeFromNib];
     }
 }




iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Anonymous Category

   • No category name, empty parentheses
   • Must be implemented in original class
   • used for organizing private methods

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Factory Method

   • Interface for creation
   • Creator vs. Product
   • Defer instantiation to subclasses

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Factory Method
          Product




  ConcreteProduct                                                   ConcreteCreator
                                                                factoryMethod




iOS Design Patterns   19/11/2011 - Barcelona Developer Conference    @ismaeldm @aquarioverde
Abstract Factory

   • Creator vs. Product
   • Interface for creating families of objects
   • Defer instantiation to subclasses

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Abstract Factory
           Abstract Factory                                         AbstractProductA
        createProductA
         createProductB


                                                        ProductA2                        ProductA1

 ConcreteFactory1
createProductA
 createProductB                                                      AbstractProductB

                   ConcreteFactory2
                  createProductA
                   createProductB
                                                          ProductB2                        ProductB1




         iOS Design Patterns        19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Façade
   • Unified, higher level interface to a set of
         different interfaces
   • Gateway to a set of subclasses
   • Hide complexity
   • Layer subsystems
   • NSPersistantStoreCoordinator
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Façade
                                      Façade




iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Mediator

   • Encapsulates objects interaction
   • Objects only know the mediator
   • Hub of communication
   • Many-to-Many to One-to-Many

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Mediator
       anAirplane                                                   anAirplane




                                     control tower




       anAirplane                                                   anAirplane



iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Template Method
   • Skeleton of an algorithm that partly needs
         to be implemented by subclassing
   • Used if specific behaviour can vary and
         common behaviour is needed
   • Used for so called “Hooks”
   • Assure primitive method implementation
   • “drawRect”, “dealloc”
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Template Methods
                  Abstract Class                               ...
                                                               [self primitiveOperation1]
              templateMethod                                   ...
              primitiveOperation1                              [self primitiveOperation2]
                                                               ...
              primitiveOperation2




                 Concrete Class
              primitiveOperation1
              primitiveOperation2




iOS Design Patterns           19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
References

   • Pro Objective-C Design Patterns for iOS
   • Cocoa Design Patterns
   • Design Patterns: Elements of Reusable
         Object-Oriented Software



iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Thank you!


Ismael Delgado @ismaeldm

Andreas Blick @aquarioverde
Backup
Composite
   • Hierachies
   • Solve structural problem
   • Tree with different node objects but same
         base type
   • UIViews are organized as composite
         structure
   • New operations:Visitor Pattern
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Composite
                         Composite




             Leaf                                Composite




                                   Leaf                               Composite




iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Visitor
   • Extending a classes functionality by using an
         external class
   • Usually used in combination with the
         Composite Pattern
   • Protocol defines visitXXX method
   • Elements have acceptVisitor method
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Proxy

   • Placeholder for different, bigger object
   • Lazy image loading
   • Mail Attachment
   • Remote Proxy

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Decorator


   • Attach additional responsibilities to an
         object dynamically
   • TextView with Scroll

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Anonymous Type

   • Type <id>
   • Pointer to an Objective-C object
    • No specific information
    • Can receive messages!
   • Heterogeneous Containers
iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Accessors

   • Funnel access to an object’s properties
   • Adhere to memory management
   • Necessary for key-value coding

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Archiving

   • Serialization
   • Encode an objects state into an archive
   • Used with Interface Builder
   • Used to create “deep copies”

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Memento

   • Save current state of an object
   • Hide loading and saving of an object
   • Originator, Memento and Caretaker

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Proxy

   • Placeholder for different objects
   • Save memory
   • Local representative for remote object
   • Access control

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Flyweight


   • Share objects and keep them in a pool


iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde
Archiving

   • Serialization
   • Save an objects state into an archive
   • Interface Builder
   • Deep Copy

iOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ismaeldm @aquarioverde

Contenu connexe

Tendances

Mobile developement
Mobile developementMobile developement
Mobile developementLilia Sfaxi
 
Domain Driven Design for Angular
Domain Driven Design for AngularDomain Driven Design for Angular
Domain Driven Design for AngularJennifer Estrada
 
Spring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsSpring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsVirtual Nuggets
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperFabrit Global
 
Server-side JS with NodeJS
Server-side JS with NodeJSServer-side JS with NodeJS
Server-side JS with NodeJSLilia Sfaxi
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkASG
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in phpLeonardo Proietti
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript ApplicationAnis Ahmad
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript DevelopmentAddy Osmani
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - IntroductionWebStackAcademy
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101Rich Helton
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSJinkyu Kim
 
Oracle MAF real life OOW.pptx
Oracle MAF real life OOW.pptxOracle MAF real life OOW.pptx
Oracle MAF real life OOW.pptxLuc Bors
 

Tendances (18)

Mobile developement
Mobile developementMobile developement
Mobile developement
 
Domain Driven Design for Angular
Domain Driven Design for AngularDomain Driven Design for Angular
Domain Driven Design for Angular
 
Spring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsSpring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggets
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular Developer
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Server-side JS with NodeJS
Server-side JS with NodeJSServer-side JS with NodeJS
Server-side JS with NodeJS
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in php
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript Application
 
Large-Scale JavaScript Development
Large-Scale JavaScript DevelopmentLarge-Scale JavaScript Development
Large-Scale JavaScript Development
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
 
Oracle MAF real life OOW.pptx
Oracle MAF real life OOW.pptxOracle MAF real life OOW.pptx
Oracle MAF real life OOW.pptx
 
WOdka
WOdkaWOdka
WOdka
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 

Similaire à iOS Design Patterns

Design Patterns in ZK: Java MVVM as Model-View-Binder
Design Patterns in ZK: Java MVVM as Model-View-BinderDesign Patterns in ZK: Java MVVM as Model-View-Binder
Design Patterns in ZK: Java MVVM as Model-View-BinderSimon Massey
 
ASP.NET MVC as the next step in web development
ASP.NET MVC as the next step in web developmentASP.NET MVC as the next step in web development
ASP.NET MVC as the next step in web developmentVolodymyr Voytyshyn
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksCiklum Ukraine
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
 
A Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid Applications
A Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid ApplicationsA Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid Applications
A Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid Applicationsajithranabahu
 
Marlabs - ASP.NET Concepts
Marlabs - ASP.NET ConceptsMarlabs - ASP.NET Concepts
Marlabs - ASP.NET ConceptsMarlabs
 
Android App Architecture
Android App ArchitectureAndroid App Architecture
Android App ArchitectureTai Dang
 
Model View Presenter
Model View Presenter Model View Presenter
Model View Presenter rendra toro
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)hchen1
 
Ios development 2
Ios development 2Ios development 2
Ios development 2elnaqah
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Svetlin Nakov
 
Spring MVC introduction HVA
Spring MVC introduction HVASpring MVC introduction HVA
Spring MVC introduction HVAPeter Maas
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobilenaral
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)Carles Farré
 

Similaire à iOS Design Patterns (20)

Design Patterns in ZK: Java MVVM as Model-View-Binder
Design Patterns in ZK: Java MVVM as Model-View-BinderDesign Patterns in ZK: Java MVVM as Model-View-Binder
Design Patterns in ZK: Java MVVM as Model-View-Binder
 
ASP.NET MVC as the next step in web development
ASP.NET MVC as the next step in web developmentASP.NET MVC as the next step in web development
ASP.NET MVC as the next step in web development
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&Tricks
 
Unit 07: Design Patterns and Frameworks (1/3)
Unit 07: Design Patterns and Frameworks (1/3)Unit 07: Design Patterns and Frameworks (1/3)
Unit 07: Design Patterns and Frameworks (1/3)
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
 
A Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid Applications
A Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid ApplicationsA Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid Applications
A Domain Specific Language for Enterprise Grade Cloud-Mobile Hybrid Applications
 
Marlabs - ASP.NET Concepts
Marlabs - ASP.NET ConceptsMarlabs - ASP.NET Concepts
Marlabs - ASP.NET Concepts
 
Iphone course 3
Iphone course 3Iphone course 3
Iphone course 3
 
Android App Architecture
Android App ArchitectureAndroid App Architecture
Android App Architecture
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Model View Presenter
Model View Presenter Model View Presenter
Model View Presenter
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Ios development 2
Ios development 2Ios development 2
Ios development 2
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
 
Presentation
PresentationPresentation
Presentation
 
MVVM Lights
MVVM LightsMVVM Lights
MVVM Lights
 
Spring MVC introduction HVA
Spring MVC introduction HVASpring MVC introduction HVA
Spring MVC introduction HVA
 
MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobile
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (1/3)
 

Dernier

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Dernier (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

iOS Design Patterns

  • 1. iOS Design Patterns Ismael Delgado @ismaeldm Andreas Blick @aquarioverde
  • 2. Agenda • MVC • Delegate • Observer • Command • Outlets, Targets & Actions • Singleton iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 3. Agenda • Category • Factory Method & Abstract Factory • Façade • Mediator • Template Method iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 4. Introduction • Templates for solving common problems • Problem and solution description • Not a library, not an algorithm! • Customized Solution • Reusability and Extensibility • Patterns for different purposes iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 5. Basic Principles • Program to an interface, not an implementation • Composition over Inheritance • iOS = Look & Feel driven design • Design first than develop iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 6. MVC • Model View Controller • Most Cocoa Touch frameworks • Separation and Communication • Compound pattern iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 7. MVC
  • 8. MVC Model Data
  • 9. MVC Model View Data UI
  • 10. MVC Logica Controller Model View Data UI
  • 11. MVC Logica Controller Model View Data UI
  • 12. MVC Logica Controller Model View Data UI
  • 13. MVC Logica Controller Model View Data UI
  • 14. MVC Logica Controller <delegate> Model View Data UI
  • 15. MVC Logica Controller <delegate> <datasource> Model View Data UI
  • 16. MVC Logica Controller <delegate> <datasource> outlet Model View Data UI
  • 17. MVC Logica Controller <delegate> target <datasource> outlet action Model View Data UI
  • 18. MVC Logica Controller <delegate> target <datasource> outlet action KVO Model View Data UI
  • 19. Delegates • Two objects coordination • Influence behaviour • Subclassing alternative • Reduce coupling • Name Convention (should, will, did) iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 20. Observer • Publish - Subscribe • decouple objects with different behavior • Notifications iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 21. Observer Notifier Observer attachObserver update detachObserver for all in observers notify { [observer update] } ConcreteNotifier ConcreteObserver getState update setState notifierState observerState iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 22. Observer Notifier Observer 1 Observer 2 setState notify update getState update getState iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 23. Observer • NSNotificationCenter / NSNotification • custom notifications • NSKeyValueObserving • listen to changes on certain object properties iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 24. Observer NSNotification *notification = [NSNotification notificationWithName:@"BcnDevConScheduleChanged" object:self]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter postNotification:notification]; [notificationCenter addObserver:self selector:@selector(updateSchedule) name:@"BcnDevConScheduleChanged" object:nil]; iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 25. Command • Request encapsulation • NSInvocation • Selector • Undo / Redo Stacks iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 26. Outlets, Targets, Action • Connect User Interface objects to application specific operations • Connect views and controllers • based on Objective-C’s selector pattern iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 27. Outlets, Targets, Action • Outlet is a reference to another object • id or IBOutlet • Stored in instance of NSNibOutletConnector • -set<Outlet>: • When awakeFromNib is called all outlets are connected iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 28. Outlets, Targets, Action • Target is a special type of outlet • Stored in instance of NSNibControlConnector • Actions can be any method that returns void and accepts one argument • Stored as selectors • UIApplication sendAction:to:from iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 29. Singleton • UIAccelerometer • Shared resources • Only one instance • Global point access iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 30. Singleton @interface Singleton : NSObject +(Singleton *)sharedInstance; @end @implementation Singleton static Singleton *sharedSingleton_ = nil; +(Singleton *)sharedInstance { if (sharedSingleton_ == nil) { sharedSingleton_ = [[Singleton alloc] init]; } return sharedSingleton_; } @end iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 31. Singleton +(id)allocWithZone:(NSZone *)zone { return [[self sharedInstance] retain]; } -(id)copyWithZone:(NSZone *)zone { return self; } -(id)retain { return self; } -(NSUInteger) retainCount { return NSUIntegerMax; } -(void)release { //do nothing } -(id)autorelease { return self; } iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 32. Singleton +(Singleton *)sharedInstance { @synchronized(self) { if (sharedSingleton_ == nil) { sharedSingleton_ = [[Singleton allocWi] init]; } } return sharedSingleton_; } +(Singleton *)sharedInstance { static dispatch_once_t pred = 0; __strong static id _sharedObject = nil; dispatch_once(&pred, ^{ _sharedObject = [[self alloc] init]; // or some other init method }); return _sharedObject; } iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 33. Category • Addition of methods to an object without subclassing • Replace methods at runtime • No instance variables! • Spread implementation over various files • Different methods in different frameworks iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 34. Category @interface UIButton (UIButton_PMProperties) - (void)setPMDefaultButtonProperties; @end #import "UIButton+PMProperties.h" @implementation UIButton (UIButton_PMProperties) - (void)setPMDefaultButtonProperties { self.titleLabel.font = [UIFont fontWithName:PM_DEFAULT_BUTTON_FONT size:PM_DEFAULT_BUTTON_FONT_SIZE]; [self setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; } @end iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 35. Informal Protocol • Category header only to define classes that might or might not be implemented - (void)awakeFromNib { if ([UIControl instancesRespondToSelector:@selector(awakeFromNib)]) { [super awakeFromNib]; } } iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 36. Anonymous Category • No category name, empty parentheses • Must be implemented in original class • used for organizing private methods iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 37. Factory Method • Interface for creation • Creator vs. Product • Defer instantiation to subclasses iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 38. Factory Method Product ConcreteProduct ConcreteCreator factoryMethod iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 39. Abstract Factory • Creator vs. Product • Interface for creating families of objects • Defer instantiation to subclasses iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 40. Abstract Factory Abstract Factory AbstractProductA createProductA createProductB ProductA2 ProductA1 ConcreteFactory1 createProductA createProductB AbstractProductB ConcreteFactory2 createProductA createProductB ProductB2 ProductB1 iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 41. Façade • Unified, higher level interface to a set of different interfaces • Gateway to a set of subclasses • Hide complexity • Layer subsystems • NSPersistantStoreCoordinator iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 42. Façade Façade iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 43. Mediator • Encapsulates objects interaction • Objects only know the mediator • Hub of communication • Many-to-Many to One-to-Many iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 44. Mediator anAirplane anAirplane control tower anAirplane anAirplane iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 45. Template Method • Skeleton of an algorithm that partly needs to be implemented by subclassing • Used if specific behaviour can vary and common behaviour is needed • Used for so called “Hooks” • Assure primitive method implementation • “drawRect”, “dealloc” iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 46. Template Methods Abstract Class ... [self primitiveOperation1] templateMethod ... primitiveOperation1 [self primitiveOperation2] ... primitiveOperation2 Concrete Class primitiveOperation1 primitiveOperation2 iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 47. References • Pro Objective-C Design Patterns for iOS • Cocoa Design Patterns • Design Patterns: Elements of Reusable Object-Oriented Software iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 48. Thank you! Ismael Delgado @ismaeldm Andreas Blick @aquarioverde
  • 50. Composite • Hierachies • Solve structural problem • Tree with different node objects but same base type • UIViews are organized as composite structure • New operations:Visitor Pattern iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 51. Composite Composite Leaf Composite Leaf Composite iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 52. Visitor • Extending a classes functionality by using an external class • Usually used in combination with the Composite Pattern • Protocol defines visitXXX method • Elements have acceptVisitor method iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 53. Proxy • Placeholder for different, bigger object • Lazy image loading • Mail Attachment • Remote Proxy iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 54. Decorator • Attach additional responsibilities to an object dynamically • TextView with Scroll iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 55. Anonymous Type • Type <id> • Pointer to an Objective-C object • No specific information • Can receive messages! • Heterogeneous Containers iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 56. Accessors • Funnel access to an object’s properties • Adhere to memory management • Necessary for key-value coding iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 57. Archiving • Serialization • Encode an objects state into an archive • Used with Interface Builder • Used to create “deep copies” iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 58. Memento • Save current state of an object • Hide loading and saving of an object • Originator, Memento and Caretaker iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 59. Proxy • Placeholder for different objects • Save memory • Local representative for remote object • Access control iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 60. Flyweight • Share objects and keep them in a pool iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
  • 61. Archiving • Serialization • Save an objects state into an archive • Interface Builder • Deep Copy iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. There&amp;#x2019;s about 30 known patterns, probably more\n12 design patterns we consider most important\n&amp;#x201C;The Gang of Four&amp;#x201D; - Design Patterns\n\nPurposes: (Creational, Structural, Behavioural)\nObject Creation\nInterface Adaption\nDecoupling Objects\nAbstract Collection\nBehavioural Extension\nAlgorithm Encapsulation\nPerformance and Object Access\n
  5. interface (protocol): \nclients don&amp;#x2019;t have to be aware of the type of object they are using\nabstract classes are more flexible\nprotocols permit kind of multiple-inheritance\n\ninheritance:\nsubclass knows details of super-class (no encapsulation)\ncan not change the inherited implementation at runtime\nchange in super-class need change in subclass\ncan&amp;#x2019;t reuse subclasses\n\ncomposition:\nwell defined interfaces\ndefined dynamically at runtime\nno details visible\nfew implemenation dependencies\neasy object replacement\nfocus on one task\nsmall hierarchies\n\n\n
  6. has been around in other programming languages for a long time\nseparates the three basic parts of an application and defines the way they communicate\n\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. 1.- Basic idea : 2 objects coordinates to solve a problem. One is more general and intended for reuse, keep a reference to the other (the delegate) and sends messages to it.\n\n2.- Messages indicate that something happened and:\n- give the delegate an opportunity to make extra process (reacts to changes)\n- ask the delegate for critical information that will control what happens (influence the behaviour)\n\n3.- Es una alternativa al subclassing muy utilizada en Cocoa\nReduce the need to subclass objects to implement application-specific behaviour\n\n4.- Reduce the coupling. Coupling is so loose that the object can function without any delegate and a delegate is free to implement any subset of methods.\n\n5.- Convenciones de nombres en los mensajes: \n- should : send before change, expected to return a value. Ex: BOOL\n- will : send before change, informative, not expected to return a value\n- did : send after change\n\n\nEjemplo : en MVC no es conveniente poner detalles relacionados con la aplicaci&amp;#xF3;n en la vista. Es decir, que la l&amp;#xF3;gica que controla el comportamiento de la vista va en el Controller y la vista se encarga de avisar al controller de que ha ocurrido un evento al que necesita responder de alguna manera y el controller le va a decir c&amp;#xF3;mo. \nEn MVC el controller es un Delegate (Strategy?) para la View. La View sabe c&amp;#xF3;mo dibujar pero no sabe el qu&amp;#xE9; hasta que el controller se lo dice.\n\n
  28. \n
  29. one to many relationship\n
  30. one to many relationship\n
  31. when to use them:\n2 types of abstraction that depend on each other\nchanges on a set of objects that can vary\nnotifying objects without knowing them\n\n\n
  32. object: any other object that will be invoked when notified\n
  33. 1.- Command &amp;#x201C;encapsulates a request (call to a method) as an object&amp;#x201D;\nSeparates an object sending a message from the object that receive and evaluate the message.\nThe originator of the message (Client) encapsulates a request by binding together one or more actions on a specific receiver.\n\n2.- En Cocoa est&amp;#xE1; implementado mediante la clase NSInvocation que contiene toda la informaci&amp;#xF3;n necesaria para llevar a cabo una acci&amp;#xF3;n (target, selector, arguments, return value) y que pueden ser modificados en cualquier momento.\n\n3.- El selector identifica de forma un&amp;#xED;voca un mensaje enviado a un objeto receptor. \nEn cierta manera el Target-Action mechanism (que veremos a continuaci&amp;#xF3;n) hace uso de este patr&amp;#xF3;n dado que las objetos Control (p.ej.:UIButton) encapsulan el target y la acci&amp;#xF3;n y se env&amp;#xED;an cuando el usuario activa dicho control. La action est&amp;#xE1; determinada por un selector que no es m&amp;#xE1;s que un identificador de un m&amp;#xE9;todo/mensaje. En UIKit un control (UIButton) mapea un target y una action a uno o m&amp;#xE1;s eventos multitouch que ocurran sobre el control.\n\n4.- Usos : undo/redo stacks, rollback transactions, progress bars (sequences of commands executed in order), Wizards with finish action,\n\nActores principales : client, invoker, receiver\nClient : instantiates the command object and provides information required to call the method at a later time.\nInvoker : decides when the method should be called.\nReceiver : instance of the class that contains the method&amp;#x2019;s code\n\nUsed to construct components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameter.\n\n\n
  34. vs subclassing or unique id\ndoes not break MVC\n
  35. \n
  36. The ability of the target to point to any object and the fact that the action is variable provide high flexibility.\n\n[someControl setAction:@selector(@&amp;#x201D;copy&amp;#x201D;)];\nNSSelectorFromString()\nNSStringFromSelector()\n\n[NSApplication sharedApplication] sendAction:[self action] to:[self target] from:self];\n\n
  37. 1.- Ejemplo de uso : acceso al aceler&amp;#xF3;metro. Se trata de un recurso al que no tiene sentido instanciar m&amp;#xE1;s de una vez en nuestra aplicaci&amp;#xF3;n. Al fin y al cabo el servicio que nos ofrece es &amp;#xFA;nico.\n2.- Su uso se da cuando, por ejemplo, queremos dar un &amp;#xFA;nico punto de acceso a un recurso.\n3.- C&amp;#xF3;mo podemos modelar este comportamiento cuyas caracter&amp;#xED;sticas podr&amp;#xED;amos resumir en: \n- la creaci&amp;#xF3;n de una clase de la que tan solo exista una &amp;#xFA;nica instancia durante toda la vida de nuestra aplicaci&amp;#xF3;n\n4.- - y tener un punto de acceso global a dicha instancia (Factory Pattern)\n\n\n\n\n\nPor ejemplo el aceler&amp;#xF3;metro con la clase UIAccelerometer y el acceso via sharedAccelerometer\n\n\n\n\n\n\nThink about resources that can be shared only in a system and no copies of them can be made available to others.\nA singleton class in an object-oriented application always returns the same instance of itself. It provides a global access point for the resources provided by the object of the class. A design pattern that is related to these kinds of designs is called the Singleton pattern.\nEnsures a class has only one instance, and provide a global point of access to it\nThe Singleton pattern provides a well-known access point to client classes that want to create a unique instance of and access to a shared resource.\nWhen?\nThere must be exactly one instance of a class with which it must be accessible from a well-known access point, e.g., a factory method \nThe sole instance can be extended only by subclassing, and it won&amp;#x2019;t break client code with the extended object \n\n\nObjective-C implementation\n1.- simple implementation\n2.- avoid alloc/init -&gt; allocWithZone, retain, release, autorelease, retainCount\nalloc calls allocWithZone\n3.- subclassing -&gt; [NSAllocateObject ([self class],0,NULL) init]\n4.- thread safety\n- via synchronize\n- via initialize trick (runtime call first time a message is sent to a class)\n\n
  38. Objective-C implementation\n1.- simple implementation\n- acceso global a la &amp;#xFA;nica instancia (factory method)\n- static instance\nCon esta primera implementaci&amp;#xF3;n tan solo estoy asegurando que todas las veces que llame al m&amp;#xE9;todo de clase sharedSingleton me va a devolver la misma instancia.\n\nEn el caso de herencia tan solo deber&amp;#xED;a sustituir la creaci&amp;#xF3;n por la llamada:\n\nsharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init];\n
  39. 2.- avoid alloc/init -&gt; allocWithZone, retain, release, autorelease, retainCount\nalloc calls allocWithZone\nC&amp;#xF3;mo evitar que se puedan crear nuevas instancias via alloc/init? Sobreescribiendo algunos m&amp;#xE9;todos.\n- allocWithZone es llamado por alloc\n- allocWithZone hace retain para simular el mismo comportamiento y que el cliente, cuando haga release de su variable no de problemas\n- ponemos el contador de retain al m&amp;#xE1;ximo porque una vez inicializado el objeto permanece con vida hasta que la aplicaci&amp;#xF3;n termina\n- en el m&amp;#xE9;todo sharedInstance deberemos llamar a [super allocWithInit:] dado que hemos sobreescrito el propio\n
  40. 3.- thread safety\n- via synchronize\n- via GCD (Grand Central Dispatch) &amp; ARC (Automatic Reference Counting)\n- otros ... p.ej.: via initialize trick (runtime call first time a message is sent to a class)\nHacer referencia a la sesi&amp;#xF3;n de Ricardo a continuaci&amp;#xF3;n sobre el ARC\n
  41. simplify development for multiple developers\ngroup commonly used methods\nfix bugs in existing classes\n\nCategory or subclass?\n\nExamples in Cocoa:\nNSObject has 69 Categories!\n
  42. use prefixes in category naming!\nother example: extending NSArray functionality\n\n
  43. fool the compiler\n
  44. \n
  45. 1.- Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex, for example if it depends on settings in configuration files or on user input\nEs uno de los patrones de creaci&amp;#xF3;n e intenta resolver el problema de la creaci&amp;#xF3;n de objetos sin tener que especificar la clase concreta a la que pertenecen.\n\n\n2.- Modelamos con este patr&amp;#xF3;n dos tipos de clases, las creadoras y las relacionadas con los productos que se crean.\n3.- El cliente que utiliza el patr&amp;#xF3;n conoce que tiene una f&amp;#xE1;brica que le va a devolver un objeto producto cuya clase padre es la que conoce y le interesa pero que internamente va a ser una instancia de una subclase de producto dado que dependiendo de las circustancias la f&amp;#xE1;brica crear&amp;#xE1; un producto u otro.\nEn el creador tendremos el metodo de creaci&amp;#xF3;n (Factory Method) que devuelve la clase producto que corresponda y que adem&amp;#xE1;s sea subclase de la clase abstracta producto.\nSe usa cuando:\n- una clase no puede anticipar a qu&amp;#xE9; clase pertenecen los objetos que debe crear\n- una clase quiere que sus subclases sean las que especifiquen a qu&amp;#xE9; clase pertenecen los objetos que crea\n\n\nEjemplo de alquiler de coches. Quiero un coche pero me da igual si es de clase A, B, o C. Eso lo decidir&amp;#xE1; el creator dependiendo de la disponibilidad\n\n\n\nEjemplo: clase ImageReader con un m&amp;#xE9;todo que devuelve un objeto de tipo DecodedImage. La clase ImageReader es el Producto. La clase ImageFactory es la interface del Creador con un m&amp;#xE9;todo getImageReader. Las subclases de ImageFactory implementan dicho m&amp;#xE9;todo.\n\nFactory\n\npublic class ImageReaderFactory\n{\n public static ImageReader getImageReader(InputStream is)\n {\n int imageType = determineImageType(is);\n \n switch(imageType)\n {\n case ImageReaderFactory.GIF:\n return new GifReader(is);\n case ImageReaderFactory.JPEG:\n return new JpegReader(is);\n // etc.\n }\n }\n}\n\nProduct\n\npublic interface ImageReader\n{\n public DecodedImage getDecodedImage();\n}\n \npublic class GifReader implements ImageReader\n{\n public DecodedImage getDecodedImage()\n {\n // ...\n return decodedImage;\n }\n}\n \npublic class JpegReader implements ImageReader\n{\n public DecodedImage getDecodedImage()\n {\n // ...\n return decodedImage;\n }\n}\n\nOtro ejemplo : testing de una clase A que tiene un metodo M que devuelve una instancia de otra clase B. Para testear la clase A sin tener en cuenta la clase B, lo que se hace es crear una subclase de A (TestA) en la que se sobreescribe el m&amp;#xE9;todo M para que devuelva una clase FakeB subclase de B. \n\n\n
  46. La elecci&amp;#xF3;n de qu&amp;#xE9; Creator utilizar se puede dar en:\n- la clase Creator. Dependiendo de las condiciones se eligir&amp;#xE1; una u otra subclase para devolver el Producto. No existen entonces ConcreteCreator&amp;#x2019;s sino que un &amp;#xFA;nico creator devuelve objetos ConcreteProducts\n- el cliente directamente. La clase cliente, dependiendo de las condiciones crear&amp;#xE1; una instancia de una u otra subclase de Creator para que devuelva el Producto (sin tener qu&amp;#xE9; conocer c&amp;#xF3;mo est&amp;#xE1; implementado, es decir, a qu&amp;#xE9; subclase de Producto pertenece). Ejemplo NSNumber\n
  47. 1.- Similar al patr&amp;#xF3;n Factory Method.\n\n2.- A method to build collections of Factories\nProvides an interface for creating families of related or dependent objects without specifying their concrete classes\n\n3.- Idem que en el anterior\n\n\n\n\n\n\nEn este caso la interfaz de la clase creadora define m&amp;#xE9;todos para crear diferentes clases de objetos que est&amp;#xE1;n relacionados o que son dependientes entre ellos\nEncapsula un conjunto de Factories \n
  48. Pasa lo mismo que con el anterior.\nEl cliente sabe qu&amp;#xE9; ConcreteFactory debe utilizar dependiendo de las condiciones de entorno. A partir de ah&amp;#xED; puede llamar a los diferentes m&amp;#xE9;todos sabiendo que los objetos que devuelvan corresponden con las clases abstractas sin tener que preocuparse de la clase concreta.\nEjemplo : look&amp;feel de la UI\n
  49. similarity to Manager pattern\nlegacy application\n
  50. example: Bank System (Account, Customer, Transaction)\n\n
  51. \n\nMetafora de los pilotos de avi&amp;#xF3;n que quieren aterrizar y en vez de hablar todos con todos se comunican con la torre de control\n\nDefine an object that encapsulates how a set of objects interact\nEl dise&amp;#xF1;o OO promueve la separaci&amp;#xF3;n del comportamiento en diferentes objetos. Esto conlleva que al final todos los objetos esten relacionados entre si y todos conozcan todo de todos. Esto reduce la reusabilidad.\nSin el Mediator, dado que la comunicaci&amp;#xF3;n de cada objeto con el resto est&amp;#xE1; definida en su misma clase, es dif&amp;#xED;cil su reutilizaci&amp;#xF3;n. En cambio si extraemos dicha comunicaci&amp;#xF3;n a un objeto &amp;#x201C;Director&amp;#x201D; nos queda tan solo el comportamiento propio de la clase\nVentajas : \nsi queremos modificar el comportamiento tan solo debemos subclass el mediator y no el resto de objetos\ndecoupling de objetos\nreplaces many-to-many to one-to-many interactions\nsepara la definici&amp;#xF3;n del comportamiento individual de cada objeto de la interacci&amp;#xF3;n entre objetos\nImplementaci&amp;#xF3;n:\nObjects communicates when events occurs\nMediator as an Observer\n
  52. NOTA : Deber&amp;#xED;a estar despu&amp;#xE9;s del patr&amp;#xF3;n Observer y de Notifications\n\nMetafora de los pilotos de avi&amp;#xF3;n que quieren aterrizar y en vez de hablar todos con todos se comunican con la torre de control\nDefine an object that encapsulates how a set of objects interact\nEl dise&amp;#xF1;o OO promueve la separaci&amp;#xF3;n del comportamiento en diferentes objetos. Esto conlleva que al final todos los objetos esten relacionados entre si y todos conozcan todo de todos. Esto reduce la reusabilidad.\nSin el Mediator, dado que la comunicaci&amp;#xF3;n de cada objeto con el resto est&amp;#xE1; definida en su misma clase, es dif&amp;#xED;cil su reutilizaci&amp;#xF3;n. En cambio si extraemos dicha comunicaci&amp;#xF3;n a un objeto &amp;#x201C;Director&amp;#x201D; nos queda tan solo el comportamiento propio de la clase\nVentajas : \nsi queremos modificar el comportamiento tan solo debemos subclass el mediator y no el resto de objetos\ndecoupling de objetos\nreplaces many-to-many to one-to-many interactions\nsepara la definici&amp;#xF3;n del comportamiento individual de cada objeto de la interacci&amp;#xF3;n entre objetos\nImplementaci&amp;#xF3;n:\nObjects communicates when events occurs\nMediator as an Observer\n
  53. common behaviour in common class\n
  54. one to many relationship\n
  55. \n
  56. \n
  57. \n
  58. \n
  59. one to many relationship\n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n