iOS Design Pattern

2017 年 12 月開始了一個 iOS 的 project,需要把 etnet 的即時投資組合複製到另一個 app,這次 project 可說是目前為止寫得最多 iOS 的一次,當中鞏固了之前零零碎碎所學的 iOS 技巧。今天無意中看到一篇 iOS Design Pattern 的文章,在剛剛完成今次 project 後看到,就像是工作後的整理/筆記,可以 review 一次開發時所面對過的 design pattern,所以要記錄下來。

1. MVC Pattern 

2. The Singleton Pattern
在一個 class create 一個 public 的 object,可讓其他 class 存取這個 object,例如[UIScreen mainScreen], [NSFileManager defaultManager] 會 return 一個 Singleton object

 3. The Facade Design Pattern
4. The Decorator Design Pattern 
類似 Java 的 extend

The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It’s an alternative to subclassing where you modify a class’ behavior by wrapping it with another object.

In Objective-C there are two very common implementations of this pattern: Category and Delegation.


5. The Adapter Pattern
objective-c 的 protocol 類似 Java 的 interface

An Adapter allows classes with incompatible interfaces to work together. It wraps itself around an object and exposes a standard interface to interact with that object.

If you're familiar with the Adapter pattern then you'll notice that Apple implements it in a slightly different manner - Apple uses protocols to do the job. You may be familiar with protocols like UITableViewDelegate, UIScrollViewDelegate, NSCoding and NSCopying. As an example, with the NSCopying protocol, any class can provide a standard copy method.

@protocol HorizontalScrollerDelegate <NSObject>
// methods declaration goes in here
@end

6. The Observer Pattern

[[NSNotificationCenter defaultCenter] postNotificationName:@"BLDownloadImageNotification"
                                                    object:self
                                                  userInfo:@{@"imageView":coverImage, @"coverUrl":albumCover}];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadImage:) name:@"BLDownloadImageNotification" object:nil];


留言

這個網誌中的熱門文章

政府T-Contract vs Vendor vs In-house

我的 2 年 Developer 生涯