자바와 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