iOS–iOS开发中的设计模式(2)

放假在家没写完,继续。

Structural 结构型模式

Facade 外观模式

外观模式为子系统中的一组接口提供一个统一的高层接口,将复杂子系统的类和接口隐藏,使得子系统更容易使用。外观模式挺好理解的OC中的业务逻辑太多不好拿出来,就用个C++的例子代替。

class CPU {
public:
void freeze() { ... }
void jump(long position) { ... }
void execute() { ... }
}

class Memory {
public:
void load(long position, char* data) {...}
}

class HardDrive {
public:
char* read(long lba, int size) {...}
}

/* Facade */

class Computer {
public:
void startComputer() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}

/* Client */

class You {
public:
void start(String[] args) {
Computer facade = new Computer();
facade.startComputer();
}
}

Behavioral 行为型模式

行为型模式用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。

Observer 观察者模式

在观察者模式中,一个对象通知其他对象自己状态的改变,发出通知的对象并不知道有多少对象会接收到通知并改变,也不知道接收通知的对象的细节。通常,在实现观察者模式需要注册一个观察者到对象中,当状态改变时,所有观察者对象都会收到通知。 在iOS中观察者模式被运用于Notification和KVO中。对于NSNotificationCenter中的

  • (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender

方法中的notificationName和notificationSender。

notificationName: The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.

notificationSender: The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.