iOS Design Patterns    Ismael Delgado @ismaeldm   Andreas Blick @aquarioverde
Agenda   • MVC   • Delegate   • Observer   • Command   • Outlets, Targets & Actions   • SingletoniOS Design Patterns   19/...
Agenda   • Category   • Factory Method & Abstract Factory   • Façade   • Mediator   • Template MethodiOS Design Patterns  ...
Introduction   • Templates for solving common problems    • Problem and solution description    • Not a library, not an al...
Basic Principles   • Program to an interface, not an         implementation   • Composition over Inheritance   • iOS = Loo...
MVC   • Model View Controller   • Most Cocoa Touch frameworks   • Separation and Communication   • Compound patterniOS Des...
MVC
MVC       ModelData
MVC       Model         ViewData                        UI
MVC               Logica   Controller       Model                         ViewData                                        UI
MVC               Logica   Controller       Model                         ViewData                                        UI
MVC               Logica   Controller       Model                         ViewData                                        UI
MVC               Logica   Controller       Model                         ViewData                                        UI
MVC               Logica   Controller                                     <delegate>       Model                          ...
MVC               Logica   Controller                                     <delegate>                                      ...
MVC               Logica   Controller                                     <delegate>                                      ...
MVC               Logica   Controller                                         <delegate>                                ta...
MVC               Logica   Controller                                         <delegate>                                ta...
Delegates   • Two objects coordination   • Influence behaviour   • Subclassing alternative   • Reduce coupling   • Name Con...
Observer   • Publish - Subscribe   • decouple objects with different behavior   • NotificationsiOS Design Patterns   19/11/...
Observer           Notifier                                                       ObserverattachObserver                   ...
Observer        Notifier                        Observer 1                           Observer 2                            ...
Observer   • NSNotificationCenter / NSNotification    • custom notifications   • NSKeyValueObserving    • listen to changes o...
Observer NSNotification *notification =    [NSNotification notificationWithName:@"BcnDevConScheduleChanged"        object:...
Command   • Request encapsulation   • NSInvocation   • Selector   • Undo / Redo StacksiOS Design Patterns   19/11/2011 - B...
Outlets, Targets, Action   • Connect User Interface objects to         application specific operations   • Connect views an...
Outlets, Targets, Action   • Outlet is a reference to another object    • id or IBOutlet   • Stored in instance of        ...
Outlets, Targets, Action   • Target is a special type of outlet   • Stored in instance of         NSNibControlConnector   ...
Singleton   • UIAccelerometer   • Shared resources   • Only one instance   • Global point accessiOS Design Patterns   19/1...
Singleton@interface Singleton : NSObject+(Singleton *)sharedInstance;@end@implementation Singletonstatic Singleton *shared...
Singleton +(id)allocWithZone:(NSZone *)zone {     return [[self sharedInstance] retain]; } -(id)copyWithZone:(NSZone *)zon...
Singleton+(Singleton *)sharedInstance{    @synchronized(self)    {        if (sharedSingleton_ == nil)        {           ...
Category   • Addition of methods to an object without         subclassing   • Replace methods at runtime    • No instance ...
Category@interface UIButton (UIButton_PMProperties)- (void)setPMDefaultButtonProperties;@end #import "UIButton+PMPropertie...
Informal Protocol   • Category header only to define classes that         might or might not be implemented - (void)awakeFr...
Anonymous Category   • No category name, empty parentheses   • Must be implemented in original class   • used for organizi...
Factory Method   • Interface for creation   • Creator vs. Product   • Defer instantiation to subclassesiOS Design Patterns...
Factory Method          Product  ConcreteProduct                                                   ConcreteCreator        ...
Abstract Factory   • Creator vs. Product   • Interface for creating families of objects   • Defer instantiation to subclas...
Abstract Factory           Abstract Factory                                         AbstractProductA        createProductA...
Façade   • Unified, higher level interface to a set of         different interfaces   • Gateway to a set of subclasses   • ...
Façade                                      FaçadeiOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @ism...
Mediator   • Encapsulates objects interaction   • Objects only know the mediator   • Hub of communication   • Many-to-Many...
Mediator       anAirplane                                                   anAirplane                                    ...
Template Method   • Skeleton of an algorithm that partly needs         to be implemented by subclassing   • Used if specifi...
Template Methods                  Abstract Class                               ...                                        ...
References   • Pro Objective-C Design Patterns for iOS   • Cocoa Design Patterns   • Design Patterns: Elements of Reusable...
Thank you!Ismael Delgado @ismaeldmAndreas Blick @aquarioverde
Backup
Composite   • Hierachies   • Solve structural problem   • Tree with different node objects but same         base type   • ...
Composite                         Composite             Leaf                                Composite                     ...
Visitor   • Extending a classes functionality by using an         external class   • Usually used in combination with the ...
Proxy   • Placeholder for different, bigger object   • Lazy image loading   • Mail Attachment   • Remote ProxyiOS Design P...
Decorator   • Attach additional responsibilities to an         object dynamically   • TextView with ScrolliOS Design Patte...
Anonymous Type   • Type <id>   • Pointer to an Objective-C object    • No specific information    • Can receive messages!  ...
Accessors   • Funnel access to an object’s properties   • Adhere to memory management   • Necessary for key-value codingiO...
Archiving   • Serialization   • Encode an objects state into an archive   • Used with Interface Builder   • Used to create...
Memento   • Save current state of an object   • Hide loading and saving of an object   • Originator, Memento and Caretaker...
Proxy   • Placeholder for different objects   • Save memory   • Local representative for remote object   • Access controli...
Flyweight   • Share objects and keep them in a pooliOS Design Patterns   19/11/2011 - Barcelona Developer Conference   @is...
Archiving   • Serialization   • Save an objects state into an archive   • Interface Builder   • Deep CopyiOS Design Patter...
Upcoming SlideShare
Loading in...5
×

iOS Design Patterns

4,504

Published on

1 Comment
10 Likes
Statistics
Notes
No Downloads
Views
Total Views
4,504
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
220
Comments
1
Likes
10
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • 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
  • 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
  • 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
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • 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
  • \n
  • one to many relationship\n
  • one to many relationship\n
  • 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
  • object: any other object that will be invoked when notified\n
  • 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
  • vs subclassing or unique id\ndoes not break MVC\n
  • \n
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • use prefixes in category naming!\nother example: extending NSArray functionality\n\n
  • fool the compiler\n
  • \n
  • 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
  • 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
  • 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
  • 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
  • similarity to Manager pattern\nlegacy application\n
  • example: Bank System (Account, Customer, Transaction)\n\n
  • \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
  • 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
  • common behaviour in common class\n
  • one to many relationship\n
  • \n
  • \n
  • \n
  • \n
  • one to many relationship\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • iOS Design Patterns

    1. 1. iOS Design Patterns Ismael Delgado @ismaeldm Andreas Blick @aquarioverde
    2. 2. Agenda • MVC • Delegate • Observer • Command • Outlets, Targets & Actions • SingletoniOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    3. 3. Agenda • Category • Factory Method & Abstract Factory • Façade • Mediator • Template MethodiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    4. 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 purposesiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    5. 5. Basic Principles • Program to an interface, not an implementation • Composition over Inheritance • iOS = Look & Feel driven design • Design first than developiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    6. 6. MVC • Model View Controller • Most Cocoa Touch frameworks • Separation and Communication • Compound patterniOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    7. 7. MVC
    8. 8. MVC ModelData
    9. 9. MVC Model ViewData UI
    10. 10. MVC Logica Controller Model ViewData UI
    11. 11. MVC Logica Controller Model ViewData UI
    12. 12. MVC Logica Controller Model ViewData UI
    13. 13. MVC Logica Controller Model ViewData UI
    14. 14. MVC Logica Controller <delegate> Model ViewData UI
    15. 15. MVC Logica Controller <delegate> <datasource> Model ViewData UI
    16. 16. MVC Logica Controller <delegate> <datasource> outlet Model ViewData UI
    17. 17. MVC Logica Controller <delegate> target <datasource> outlet action Model ViewData UI
    18. 18. MVC Logica Controller <delegate> target <datasource> outlet actionKVO Model ViewData UI
    19. 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. 20. Observer • Publish - Subscribe • decouple objects with different behavior • NotificationsiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    21. 21. Observer Notifier ObserverattachObserver updatedetachObserver for all in observersnotify { [observer update] } ConcreteNotifier ConcreteObservergetState updatesetStatenotifierState observerStateiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    22. 22. Observer Notifier Observer 1 Observer 2 setState notify update getState update getStateiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    23. 23. Observer • NSNotificationCenter / NSNotification • custom notifications • NSKeyValueObserving • listen to changes on certain object propertiesiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    24. 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. 25. Command • Request encapsulation • NSInvocation • Selector • Undo / Redo StacksiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    26. 26. Outlets, Targets, Action • Connect User Interface objects to application specific operations • Connect views and controllers • based on Objective-C’s selector patterniOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    27. 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 connectediOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    28. 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:fromiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    29. 29. Singleton • UIAccelerometer • Shared resources • Only one instance • Global point accessiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    30. 30. Singleton@interface Singleton : NSObject+(Singleton *)sharedInstance;@end@implementation Singletonstatic Singleton *sharedSingleton_ = nil;+(Singleton *)sharedInstance{ if (sharedSingleton_ == nil) { sharedSingleton_ = [[Singleton alloc] init]; } return sharedSingleton_;}@endiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    31. 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. 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. 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 frameworksiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    34. 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]; } @endiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    35. 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. 36. Anonymous Category • No category name, empty parentheses • Must be implemented in original class • used for organizing private methodsiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    37. 37. Factory Method • Interface for creation • Creator vs. Product • Defer instantiation to subclassesiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    38. 38. Factory Method Product ConcreteProduct ConcreteCreator factoryMethodiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    39. 39. Abstract Factory • Creator vs. Product • Interface for creating families of objects • Defer instantiation to subclassesiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    40. 40. Abstract Factory Abstract Factory AbstractProductA createProductA createProductB ProductA2 ProductA1 ConcreteFactory1createProductA createProductB AbstractProductB ConcreteFactory2 createProductA createProductB ProductB2 ProductB1 iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    41. 41. Façade • Unified, higher level interface to a set of different interfaces • Gateway to a set of subclasses • Hide complexity • Layer subsystems • NSPersistantStoreCoordinatoriOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    42. 42. Façade FaçadeiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    43. 43. Mediator • Encapsulates objects interaction • Objects only know the mediator • Hub of communication • Many-to-Many to One-to-ManyiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    44. 44. Mediator anAirplane anAirplane control tower anAirplane anAirplaneiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    45. 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. 46. Template Methods Abstract Class ... [self primitiveOperation1] templateMethod ... primitiveOperation1 [self primitiveOperation2] ... primitiveOperation2 Concrete Class primitiveOperation1 primitiveOperation2iOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    47. 47. References • Pro Objective-C Design Patterns for iOS • Cocoa Design Patterns • Design Patterns: Elements of Reusable Object-Oriented SoftwareiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    48. 48. Thank you!Ismael Delgado @ismaeldmAndreas Blick @aquarioverde
    49. 49. Backup
    50. 50. Composite • Hierachies • Solve structural problem • Tree with different node objects but same base type • UIViews are organized as composite structure • New operations:Visitor PatterniOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    51. 51. Composite Composite Leaf Composite Leaf CompositeiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    52. 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 methodiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    53. 53. Proxy • Placeholder for different, bigger object • Lazy image loading • Mail Attachment • Remote ProxyiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    54. 54. Decorator • Attach additional responsibilities to an object dynamically • TextView with ScrolliOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    55. 55. Anonymous Type • Type <id> • Pointer to an Objective-C object • No specific information • Can receive messages! • Heterogeneous ContainersiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    56. 56. Accessors • Funnel access to an object’s properties • Adhere to memory management • Necessary for key-value codingiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    57. 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. 58. Memento • Save current state of an object • Hide loading and saving of an object • Originator, Memento and CaretakeriOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    59. 59. Proxy • Placeholder for different objects • Save memory • Local representative for remote object • Access controliOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    60. 60. Flyweight • Share objects and keep them in a pooliOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    61. 61. Archiving • Serialization • Save an objects state into an archive • Interface Builder • Deep CopyiOS Design Patterns 19/11/2011 - Barcelona Developer Conference @ismaeldm @aquarioverde
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×