iOS2012. 3. 10. 02:06


자바와 Objective-C의 Listener pattern의 차이
발췌) Learn Objective-C for Java Developers

Listing 1-2. Observer Pattern in Java and Objective-C

public interface SecurityGateListener

{

    void gateStateChanged( SecurityGate gate );
}
public class SecurityGate
{
    private HashSet listeners;
    private boolean open;
    public void addListener( SecurityGateListener listener )
        {
        listeners.add(listener);
        }
    public void removeListener( SecurityGateListener listener )
        {
        listeners.remove(listener);
        }
    private void fireStateChange( )
        {
        for ( SecurityGateListener listener: listeners )
            listener.gateStateChanged(this);
        }
    public boolean getOpen( )
        {
        return open;
        }
    public void setOpen( boolean open )
        {
        if (this.open!=open) {
            this.open = open;
            fireStateChange();
            }

} }

class SecurityManager implements SecurityGateListener
{
    SecurityGate gate;
    SecurityManager( )
        {
        gate = ...
        gate.addListener(this);
        }
    public void gateStateChanged( SecurityGate gate )
        {
        // security gate changed ...
        }

}

@interface SecurityGate : NSObject {

BOOL open; }

@property BOOL open;
@end
...
@implementation SecurityManager

- (id)init

{
    if ( (self=[super init])!=nil ) {

gate = ...

        [gate addObserver:self forKeyPath:@"open" options:0 context:NULL];
    }
    return self;
}
- (void)observeValueForKeyPath:(NSString*)keyPath
                      ofObject:(id)object
{
    if (object==gate) {
 change:(NSDictionary*)change
context:(void*)context
        // security gate changed...
    }

} @end 

Posted by 삼스

댓글을 달아 주세요

  1. 귀를 기울여봐 가슴이 뛰는 소리가 들리면 네가 사랑하는 그 사람 널 사랑하고 있는거야.

    2013.07.17 12:15 [ ADDR : EDIT/ DEL : REPLY ]