Sunday, March 3, 2013

Delegate Design Pattern : Objective C vs Java

One of the most used design patterns in iOS is Delegate Design Pattern. The main usage on this design pattern is to delegate some functionality from called component to caller controller. On image below is shown simple diagram of this pattern where from main controller we call custom component with action to show data from concrete page loaded from the model. The custom component loads data and then displays. In case when no data is loaded for requested page the custom component throws notification thru implemented method in main controller from the custom component protocol. We can look on protocols in Objective C as in interfaces  in Java so the method which is defined in the protocol should be implemented in the the controller that expect some event delegated from the custom component, and also set instance on the caller controller to the custom component where the custom component will use method declaration to send some data to the caller controller or will try to execute the method.

       Delegate Design Pattern

To be much easier to understand, we’ll make comparison on implementation on delegate design pattern in iOS and in Java and we’ll see how can we create custom components in both platforms and use that components to return data to controllers where they are called.

Objective C version

ViewController.h

#import
#import "ServiceConsumer.h"

@interface ViewController : UIViewController

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ServiceConsumer *consumer = [[ServiceConsumer alloc] init];
consumer.delegate = self;
[consumer returnNumberToDelegate];
}

#pragma mark -
#pragma mark - ServiceConsumerDelegate methods

- (void)executeWithResult:(NSInteger)testValue {
NSLog(@"Returned value from delegate is %d", testValue);
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

In header file we import delegate module but also we conform with the delegate of the module. In implementation we make instance from the service consumer but also we set the delegate to self which mean we need to implement the methods defined in the protocol.

 ServiceConsumer.h

#import

@protocol ServiceConsumerDelegate

- (void)executeWithResult:(NSInteger)testValue;

@end

@interface ServiceConsumer : NSObject

@property (nonatomic, strong) iddelegate;

- (void)returnNumberToDelegate;

@end

ServiceConsumer.m

#import "ServiceConsumer.h"

@implementation ServiceConsumer

@synthesize delegate;

- (void)returnNumberToDelegate {
[self.delegate executeWithResult:32];

}


@end

In ServiceConsumer header we can see the protocol definition but also the most important line, property definition as id – generic object that have to confirm to the protocol defined in here. In implementation we can see the method that call method executeWithResult which is defined in the protocol but it call it from the delegate property which mean that the class that will have implemented the method defined in the protocol and also confirms with the delegate, if that class call the method returnNumberToDelegate from the ServiceConsumer that class will receive the response in implemented method executeWithResult. We can see that the functionality is delegated thru line [self.delegate executeWithResult:32];

Java version

With creation on instance of the ServiceConsumer we initialize engine with the instance that implements IServiceConsumer interface. That is done in constructor here. In this class we also have one method returnConsumerData that same as in Objective C version, if is called from the class that implements that interface and have implementation for method printMessage defined in the interface, this method will call that method thru the instance set to interface in the constructor.

ServiceConsumer.java

public class ServiceConsumer {

private IServiceConsumer consumer = null;

private static final String MESSAGE_0 = "MACHINE IS RUNNING";
public ServiceConsumer(IServiceConsumer consumer) {
super();
this.consumer = consumer;
}
public void returnConsumerData() {
this.consumer.printMessage(MESSAGE_0);
}
}



In Java version instead of protocol in Objective C we need to have interface with defined method.

IServiceConsumer.java

public interface IServiceConsumer {
public String returnConsumerData(String data);
public void printMessage(String messgeData);
}

The class that calls the engine makes instance from the ServiceConsumer class with setting the Machine.this to the constructor of the ServiceConsumer class because it already implements the interface. Also because it implements the interface it should also implement the methods defined in the interface in this case returnConsumerData. Method loadConsumerData is used to call returnConsumerData method implemented in the ServiceConsumer, which after calling return data thru method printMessage.

Machine.java


public class Machine implements IServiceConsumer {
private ServiceConsumer consumer = null;
public Machine() {
this.consumer = new ServiceConsumer(Machine.this);
}
public void loadConsumerData() {
this.consumer.returnConsumerData();
}


@Override
public String returnConsumerData(String data) {
// TODO Auto-generated method stub
return data;
}

@Override
public void printMessage(String messgeData) {
// TODO Auto-generated method stub
System.out.println(messgeData);
}

}


2 comments:

  1. Great example. it help me every time when i need to implement protocols.

    ReplyDelete
  2. Delegation design pattern is used by multiple classes to work collaboratively. Java emphasizes on principal of single responsibility i.e. One class should maintain code only for one specific business responsibility For example An Customer class should be responsible only for managing customer data If it starts managing the customer Orders as well It violates the principal of single responsibility. - See more at: http://www.blog.newventurewebsites.com/delegate-design-pattern-in-php/#comment-437

    http://efectivejava.blogspot.in/2013/08/delegation-design-pattern.html

    ReplyDelete