Design Patterns
What is Design pattern?
A design pattern is a template for a design that solves a general, recurring problem in aparticular context. A design pattern is defined as a solution template to a recurring problem.
1 .Model-View-Controller
Models store data in an organized form. Encapsulate Data and Basic Behaviors. For a simple app, the model could just be the actual data store, either in-memory (maybe as an NSArray or NSDictionary), or to-and-from disk. In a more complex app, you may choose to use a SQLite database or Core Data, and your model would be a simple instance or one piece of data. Models are usually specific to your application, so they usually are not reusable, unless you have a “template” method to store data. In iOS, a model is usually a subclass ofNSObject
or in the case of Core Data (an iOS framework that helps save data to a database locally on the device) NSManagedObject
.
As with any model object it contains instance variables and getter /
setter methods. Most object-oriented languages have a mechanism to
provide encapsulation, in iOS a property
provides encapsulation and the keyword synthesize
automatically generates the getter and setter methods. In the case of Book
you would have methods such as getTitle
and setTitle
or getAuthor
and setAuthor
.protocols such as UITableViewDataSource
Model
- Custom Classes
- Responsibilities:
- Domain / Business Logic (Independent of the View!)
- Data Storage (Properties, KVC, NSCoding, CoreData)
- Examples
- User Data (Document, Person, BankAccount, ...)
- Application Data (Preferences, State, ...
- Functionality (Libraries,Algorithms, ...)
Views are what you actually see on-screen.The view should not store the data it is displaying though—a label should not keep its text around; a table view should not store a copy of its data. Classes from UIKit, including UILabel, UITableView, UITextView, and indeed UIView are views.Views, because they just display (any) data, can be very easily reused.
VIEW
- User Interface Elements
- Subclass of UIView
- Responsibilities:
- Look and Feel of the UI
- Data Visualization
- Generate UI Events
- Examples: UIButton, UILabel, UITableView, MyCustomView,
The controller serves as a median. If the model changes, the controller is notified and the view is changed accordingly (for example, you could call [tableView reloadData]). If user interaction changes the model (for example, deleting a row from a table view), the controller is also notified, and from there the change gets propagated to the data store. This goes back to the concept of abstraction, one of the fundamentals of object-oriented programming. Because the controller is the median and has to deal with specific views and data models, it is typically the least reusable. Most of your app logic goes into the controller. In iOS, the controller is generally a subclass of
UIViewController
that manages a view, it is also responsible for responding to delegation messages and target-action messages.Controller:
- Glue-code between Model and View
- Custom Classes, Subclass of UIViewController
- Responsibilities:
- Configure View according to Model
- React to UI Events and update Model
- Application Logic (Navigation,
- Examples:UIViewController, MyViewController,
- Built in Controllers: UINavigationController UITabBarController UISplitViewController UITableViewController
2. View Controllers
- Base class for a controller that manages a view
- UIViewController simplifies standard behavior:
- load resources from a Nib file
- configure navigation bar, tab bar, and tool bars
- pluggable architecture
- handle events and memory warnings
- manage interface orientation changes
3. Target-action design pattern
In the Target-action design pattern the object contains the necessary information to send a message to another object when an event occurs. Let’s say you are creating an app to manage food recipes. This app has a view to capture new recipes and this view contains a save button. The save button needs to notify the view controller that the button was clicked (in iOS it would be a touch event) and then the view controller can act upon the information to save it. For this to happen the button needs two things: target (to whom) and action method (what message to send). Calling the method of an object is known as messaging.1
2
3
4
| UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"Save"
style:UIBarButtonItemStyleDone
target:self
action:@selector(saveRecipe:)];
|
target
points to self because the UIBarButtonItem
is instantiated within the same controller that contains the saveRecipe
method but it could point to any instance of an object. Next we define the action with something known as the selector
. A selector simply identifies a method and points to the implementation of it within the specified class.Action method
The action method needs to follow a particular signature. Here are some of the acceptable variations:1
2
3
4
5
6
7
| - (void)doSomething;
// OR
- (void)doSomething:(id)sender;
// OR
- (IBAction)doSomething:(id)sender;
// OR
- (IBAction)doSomething:(UIButton *) sender;
|
The
sender
parameter is the control object sending the action message. When responding to an action message, you may query sender
to get more information about the context of the event triggering the action message.In the fourth definition we define a UIButton as the sender. This definition explicitly states that the sender can be only a UIButton. This constrain also carries over to the Interface Builder where it allows you only to wire a UIButton to this action method.
Control Events
Some controls require you to define a target-action based upon a particular event. For example:1
| [aUIButton addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];
|
UIControlEventTouchUpInside
fires the target-action only if there is a touch event inside the control. There are several control events such as: UIControlEventTouchDown
, UIControlEventTouchDragInside
, UIControlEventTouchDragOutside
, UIControlEventTouchUpOutside
, etc.4. Layer Pattern
- Modules of a program can be organized like a stack of layers.
- Strict Layering: A layer can only use the layer directly below it.
- Non-strict Layering: A layer can use any layer below it.
5. Observer Pattern
- Sometimes you want to know when an object changes
- Often used with MVC.
- When a model object changes, you want to update the view(s) accordingly.
- The observer pattern is built into every NSObject via Key-Value Observing (KVO).
6. Delegation
- Alternative to subclassing
- Delegate behaviour to another class
- Implement custom behavior in delegate methods
- Assign Delegate Object Usually via property.
- The delegate object is not retained (retain-cycle)
- e.g. UIApplicationDelegate, UITableViewDelegate, UIPickerControllerDelegate, UITextFieldDelegate,CMMotionManagerDelegate
7. Singleton
Problem:Many examples found online utilize the AppDelegate instance for global storage/variables. While this is a quick way of sharing data and methods between views and classes it can (and usually does) lead to several problems:
No control over global variables/storage:Each referencing class assumes direct control over this variable and won’t necessarily respect how another class is expecting to use it. With a singleton, the data has been fully encapsulated and controlled in one place.
Repeated business logic:If there is any business logic on how this global storage is to be used it has to be repeated throughout the application. While some may “encapsulate” this by using accessor methods the logic is in the wrong place.
Big Ball Of Mud:Very quickly, the AppDelegate class will become a big ball of mud and VERY difficult to maintain. This is compounded over time as the app is revisioned and different developers add more and more code to the ball of mud.
Fixing the problem: Singleton
One way of fixing the “I need to put all my global variables in the AppDelegate” is to use Singletons. A singleton is a design pattern (and implementation) ensuring that a given class exists with one and only one instance. The developer can now store like variables and implementations together with the confidence that the same data will be retained throughout the application. In fact, the AppDelegate is held in a singleton of your application ([UIApplication sharedApplication]).
The developer must also ensure to not repeat the same “big ball of mud” anti-pattern by simply moving all the code from the AppDelegate into one Singleton class.Implementation:The implementation is pretty straight-forward based on Apple’s Fundamentals and is made even simpler using ARC in iOS 5. The trick is ensuring all code that references this class is using the exact same instance.
Steps/tips for a Singleton in Objective-C:
1. Implement a “shared manager” static method to dynamically create and retrieve the same instance each time.
static SingletonSample *sharedObject;
+ (SingletonSample*)sharedInstance
{
if (sharedObject == nil) {
sharedObject = [[super allocWithZone:NULL] init];
}
return sharedObject;
}
2. Leverage public shared methods as a convenience factor to encourage
use of the singleton.
+(NSString *) getSomeData {
// Ensure we are using the shared instance
SingletonSample *shared = [SingletonSample sharedInstance];
return shared.someData;
}
3.Create and use instance variables and methods as you normally would
@interface SingletonSample : NSObject {
// Instance variables:
// - Declare as usual. The alloc/sharedIntance.
NSString *someData;
}
// Properties as usual
@property (nonatomic, retain) NSString *someData;
4. Use the class via the shared methods and/or instance
- (IBAction)singletonTouched:(id)sender {
// Using the convenience method simplifies the code even more
self.singletonLabel.text = [SingletonSample getSomeData];
}
SharedInstance pattern is IMO the best way to share data across multiple viewControllers in iOS applications.One practical example is a data manager to share Core Data stuff such managed object context. I realized my own manager so that I can access this objects anywhere with ease like:
[[MYDataManager sharedInstance] managedObjectContext]
;
|
This comment has been removed by the author.
ReplyDelete