IOS development-common IOS design patterns-delegated Mode

Source: Internet
Author: User

For iOS development, several design modes under the cocoa framework are analyzed for everyone. Of course, there are far more content about the design pattern in the cocoa framework. We have selected several common ones: Singleton pattern, delegate pattern, Observer pattern, and MVC pattern.

 

Delegation Mode

The delegated mode evolved from the gof decorator, adapter, and template method modes. Almost every application uses the delegate mode more or less. Not only the cocoatouch framework, but also the delegated mode has been widely used in the cocoa framework.

Problem proposal

For the non-running state of the application life cycle-application startup scenario, we have refined the process from clicking the icon to starting the first screen.

Assume that this series of processing is completed in a God-class uiapplication. It is called "God class" because it is "omnipotent" and "contains all ". In object-oriented software design, "God class" is not very friendly and needs to be reconstructed. In the programming process, we should try to avoid the use of the god class, because the god class is highly coupled, unclear responsibilities, so it is difficult to maintain. We need to "Remove the god class" and put the seemingly powerful and difficult-to-maintain class, assign your own attributes or methods to their respective classes according to their responsibilities, or break down the classes that can be clearly defined, so as to remove the "God class ".

Fortunately, Apple did not design the uiapplication class as a "God class". Apple's processing is divided into two different role classes, one of which plays the role of the framework class, the framework class is generic, reusable, and unrelated to specific applications. Another role plays the role of application-related classes. Application-related classes are related to specific applications. to be controlled by framework classes, they are often designed as "protocols" and called "interfaces" in Java ". Developers need to implement this "protocol" in specific applications ".

Extract the application: didfinishlaunchingwitexceptions: And applicationdidbecomeactive: Completed functions and define them in the uiapplicationdelegate Protocol. In this way, the uiapplication class becomes the framework class.

Implement the uiapplicationdelegate protocol and the class diagram of the helloworld application. Uiapplication does not directly rely on the appdelegate class, but on the uiapplicationdelegate protocol, which is called "interface-oriented programming" in the object-oriented software design principles ". The implementation protocol of the appdelegate class is uiapplicationdelegate, which is the delegate class.

We provide the definition of delegation. Delegation aims to reduce the complexity and coupling of an object and make it more universal. Some of the processing methods are placed in the encoding method of the delegate object. Generic classes become framework classes because of their versatility, that is, they are irrelevant to specific applications. Framework classes maintain the reference of the delegate object and send messages to the delegate object at a specific time. A message may only notify the delegate object to do something, or control the delegate object.

Implementation Principle

We use a case study to introduce the principle and application scenarios of delegated design patterns, and re-draw a class diagram of delegated design patterns.

There was a philosopher in ancient Greece who had only three things in his life: "sleeping", "eating", and "working ". For a better life and a higher work efficiency, he will find an apprentice and entrust these things to the apprentice. However, to become his apprentice, an agreement must be implemented, which requires the ability to handle "sleeping", "eating", and "working" issues. The relationship between the three.

In the philosopher's class diagram, philosopher maintains the "weak reference" (ID <philosopherdelegate> delegate) pointing to the delegate object (viewcontroller), and the delegate object (viewcontroller) he is the philosopher's "apprentice". He implements the Protocol philosopherdelegate. philosopherdelegate defines three methods:-(void) sleep,-(void) Eat, and-(void) work.

The implementation code is as follows:

@protocol PhilosopherDelegate@required-(void) sleep;-(void) eat;-(void) work;@end

 

 

The delegate protocol philosopherdelegate defines three methods. The Protocol does not have m files, and its definition can be placed in other hfiles. Its implementation class is the code of the delegate class viewcontroller as follows:

//// Viewcontroller. h // @ interface viewcontroller: uiviewcontroller <philosopherdelegate> @ end // viewcontroller. M // @ implementation viewcontroller-(void) viewdidload {[Super viewdidload]; philosopher * OBJ = [[philosopher alloc] init]; obj. delegate = self; [OBJ start] ;}# pragma-philosopherdelegate method implementation-(void) sleep {nslog (@ "sleep ...");} -(Void) Eat {nslog (@ "eat ...");} -(Void) work {nslog (@ "work ...");} @ End

 

 

How can a delegated object establish a reference relationship with a common class? We use the obj. Delegate = self statement in the viewdidload method to specify the reference relationship between the delegate object and the common class. In general, generic classes are provided directly by the framework. In this example, we implement the code of generic classes philosopher and philosopher. h as needed:

////  Philosopher.h//  DelegatePattern//#import “PhilosopherDelegate.h”@interface Philosopher : NSObject{    NSTimer *timer;    int count;}@property  (nonatomic, weak) id<PhilosopherDelegate> delegate;-(void) start;-(void) handle;@end

 

 

In philosopher. H, the delegate attribute is defined. Its type is ID <philosopherdelegate>. It can save the reference of the delegate object. The weak attribute indicates "weak reference ". The philosopher. M file code is as follows:

//// Philosopher.m//  DelegatePattern#import “Philosopher.h”@implementation Philosopher@synthesize delegate;-(void) start{    count= 0;    timer = [NSTimer scheduledTimerWithTimeInterval:3.0               target:self selector:@selector(handle)userInfo:nil repeats:YES];}-(void)handle{    switch (count)    {        case 0:            [self.delegate sleep];            count++;            break;        case 1:            [self.delegate eat];            count++;            break;        case 2:            [self.delegate work];            [timer  invalidate];            break;    }}@end

 

In this example, philosopher simulates some common classes to send a call. The call is sent through nstimer every 3 seconds and sends messages sleep, eat, and work to the delegate object in sequence. In the code, self. delegate is a reference to the delegate object viewcontroller, and [self. Delegate sleep] is a call to the sleep method in viewcontroller.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.