iOS常用设计模式

nan27 7年前
   <h2>1.为什么学习设计模式</h2>    <p>对于设计模式,我们并不陌生。一谈起设计模式,脑海里马上就想到单例模式,委托模式,观察者模式等等。而面试官们也通常把对“某某设计模式”的掌握程度作为考评求职者的重要指标之一。那么问题来了,为什么要学习设计模式呢?没有设计模式我们同样能够实现功能,为什么还要“多此一举”呢?原因很简单,所谓的设计模式,只是为了开发者更好地去理解程序,说白了代码是死的,它们本身没有什么设计模式可言,只是开发者为了更好地理解程序,总结了一些设计模式,为的是让代码看上去更有条理,也便于人们理解。</p>    <h2>2.介绍几种比较常用的设计模式</h2>    <h2>单例模式</h2>    <h3>单例模式的应用场景</h3>    <p>单例模式的作用是解决应用程序中只有一个实例的问题,这在我们设计中会经常遇到,比如应用程序启动时,应用状态由UIApplication类一个实例维护,还有NSUserDefaults和NSNotificationCenter等单例。</p>    <h3>单例模式的具体实现</h3>    <p>oc版</p>    <pre>  <code class="language-objectivec">+(Singleton *)sharedInstance{        static Singleton *sharedSingleton = nil;      static dispatch_once_t onceToken;      dispatch_once(&onceToken, ^{          sharedSingleton = [[Singleton alloc] init];      });       return  sharedSingleton;  }</code></pre>    <p>swift版</p>    <pre>  <code class="language-objectivec">private let sharedInstance = Singleton()  class Singleton: NSObject {      class var sharedManager: Singleton {          return sharedInstance;      }  }</code></pre>    <h2>委托模式</h2>    <h3>委托设计模式类图</h3>    <p style="text-align:center"><img src="https://simg.open-open.com/show/770ccedb70222f469b2c6a3feba3c3ee.png"></p>    <p style="text-align:center">委托设计模式类图</p>    <h3>委托模式的应用场景</h3>    <p>在iOS开发中,用到的系统的UITextField或者UITableView等都是应用的委托模式设计的,我们自己在开发过程中也会经常遇到,比如一些保存个人信息的界面,将信息填写完成之后,便可采用委托的方式将信息回传到首界面展示个人信息。还有很多类子,在这里就不一一列举了。</p>    <h3>委托模式的具体实现</h3>    <p>这里举一个简单的类子,比如我一天只干三件事,吃饭,睡觉,工作,为了更好地工作和生活,我请了一个助理。要成为我的助理,需要实现一个协议,协议要求能够处理吃饭,睡觉,工作问题。通用类就是我(coderPeng类),通过代理(delegate)属性保持委托对象的引用.委托对象(ViewController)就是我的助理,它实现了了协议coderPengDelegate.coderPengDelegate定义了三个方法:sleep,eat,work方法.</p>    <p>oc版</p>    <pre>  <code class="language-objectivec">CoderPeng类中的代码  .h中的代码  @protocol CoderPengDelegate <NSObject>  @required  - (void)sleep;  - (void)eat;  - (void)work;  @end  @interface CoderPeng : NSObject  //weak修饰为了防止内存的"强引用循环",从而避免内存泄漏问题  @property (nonatomic,weak)id<CoderPengDelegate>delegate;  - (void)start;  @end  .m中的代码  -(void)start{      if (self.delegate && [self.delegate respondsToSelector:@selector(sleep)] && [self.delegate respondsToSelector:@selector(eat)] && [self.delegate respondsToSelector:@selector(work)]) {          [self.delegate sleep];          [self.delegate work];          [self.delegate eat];      }  }  ViewControler类中的代码  @interface ViewController ()<CoderPengDelegate>    @end    @implementation ViewController     - (void)viewDidLoad {      [super viewDidLoad];      // Do any additional setup after loading the view, typically from a nib.      CoderPeng *coderPeng = [[CoderPeng alloc] init];      coderPeng.delegate = self;      [coderPeng start];    }  #pragma mark  协议方法  -(void)sleep{      NSLog(@"睡觉");  }  - (void)eat{      NSLog(@"吃饭");  }  - (void)work{      NSLog(@"工作");  }    @end</code></pre>    <p>swift版</p>    <pre>  <code class="language-objectivec">CoderPeng类中的代码  protocol coderPengDelegate {      func sleep()      func eat()      func work()  }  class CoderPeng: NSObject {      var delegate:coderPengDelegate?      func start()  {          self.delegate?.sleep()          self.delegate?.eat()          self.delegate?.work()      }  }  ViewController类中的代码  class ViewController: UIViewController,coderPengDelegate {        override func viewDidLoad() {          super.viewDidLoad()          let coderPeng = CoderPeng()          coderPeng.delegate = self          coderPeng.start()      }      //MARK:协议方法      func sleep() {          print("睡觉")      }      func eat() {          print("吃饭")      }      func work() {          print("工作")      }  }</code></pre>    <h2>观察者模式</h2>    <h3>观察者模式简述</h3>    <p>观察者模式也叫发布/订阅模式,是MVC模式的重要组成部分,它有4个角色,具体如下:</p>    <p>1. <strong>抽象主题(Subject):</strong> 在swift中,抽象主题是一个协议,它是一个观察者集合容器,定义了添加观察者方法,移除观察者方法和为所有观察者发送通知的方法;</p>    <p>2. <strong>抽象观察者(Observer):</strong> 在swift中,抽象观察者也是一个协议,它有一个更新方法;</p>    <p>3. <strong>具体观察者(ConcreteObserver):</strong> Observer协议的具体实现;</p>    <p>4. <strong>具体主题(ConcreteSubject):</strong> Subject协议的具体实现.</p>    <p>引入Subject和Observer这俩个协议之后,不仅提高了系统的可复用性,还降低了耦合度。</p>    <h3>通知机制和KVO机制</h3>    <p>在Cocoa Touch框架中,观察者模式的具体应用有俩个——通知机制和KVO机制,下面介绍这俩个机制:</p>    <p>通知机制</p>    <p>通知机制与委托机制不同,前者是”一对多“的对象之间的通信,后者是“一对一”的对象之间的通信。在通知机制中,对某个通知感兴趣的所有对象都可以成为接收者。</p>    <p>通知机制简单示例</p>    <p>在开发过程中,登录成功后通常需要刷新数据,这个需求就可以用通知机制来完成。具体实现代码如下:</p>    <p>oc版</p>    <pre>  <code class="language-objectivec">登录界面的代码(写在登录成功之后)  //name:通知名称  [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshData" object:nil];  需要刷新界面的代码  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData)name:@"RefreshData" object:nil];  //数据请求  -(void)loadData{    }  //移除通知  - (void)dealloc{   [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshData" object:nil];  }</code></pre>    <p>swift版</p>    <pre>  <code class="language-objectivec">登录界面的代码(写在登录成功之后)  NSNotificationCenter.defaultCenter().postNotificationName("refreshData", object: nil)  需要刷新界面的代码  NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.loadData), name: "refreshData", object: nil)  //数据请求  func loadData()  {  }  //移除通知  deinit {      NSNotificationCenter.defaultCenter().removeObserver(self, name: "refreshData", object: nil);      }</code></pre>    <p>KVO机制</p>    <p>KVO机制不像通知机制那样通过一个通知中心观察所有对象,而是在对象属性变化时将通知直接发送给观察者对象</p>    <p>KVO机制简单示例</p>    <p>监测应用程序状态变化,appStatus是我们要观察的对象的属性,示例代码如下</p>    <p>oc版</p>    <pre>  <code class="language-objectivec">在AppStatusObserver类中的代码  @implementation AppStatusObersver  -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{        NSLog(@"%@   %@",keyPath,change[NSKeyValueChangeNewKey]);  }  在appDelagate类中的代码  @interface AppDelegate ()  @property (nonatomic,strong)NSString *appStatus;  @property (nonatomic,strong)AppStatusObersver *observer;  @end    @implementation AppDelegate      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      // Override point for customization after application launch.      self.observer = [[AppStatusObersver alloc] init];      [self addObserver:self.observer forKeyPath:@"appStatus" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];      self.appStatus = @"launch";      return YES;  }    - (void)applicationWillResignActive:(UIApplication *)application {      self.appStatus = @"inactive";  }    - (void)applicationDidEnterBackground:(UIApplication *)application {      self.appStatus = @"background";  }    - (void)applicationWillEnterForeground:(UIApplication *)application {     self.appStatus = @"foreground";  }    - (void)applicationDidBecomeActive:(UIApplication *)application {      self.appStatus = @"active";  }    - (void)applicationWillTerminate:(UIApplication *)application {      self.appStatus = @"terminate";  }  @end</code></pre>    <p>swift版</p>    <pre>  <code class="language-objectivec">在AppStatusObersver类中的代码  //重写该方法的目的是为了监测属性的变化情况  override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {          print("--%@--%@",keyPath!,(change![NSKeyValueChangeNewKey] as! String))      }  在appDelegate类中的代码  //appStatus属性是我们观察的,用dynamic修饰表示该属性是在运行时动态派发的  dynamic var appStatus : NSString!  var  observer:AppStatusObersver!  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {          self.observer = AppStatusObersver()          self.addObserver(self.observer, forKeyPath: "appStatus", options: [NSKeyValueObservingOptions.New,NSKeyValueObservingOptions.Old] , context: nil)          self.appStatus = "launch"          return true      }  func applicationWillResignActive(application: UIApplication) {          self.appStatus = "inactive"      }        func applicationDidEnterBackground(application: UIApplication) {          self.appStatus = "background"      }        func applicationWillEnterForeground(application: UIApplication) {            self.appStatus = "foreground"      }        func applicationDidBecomeActive(application: UIApplication) {            self.appStatus = "active"      }        func applicationWillTerminate(application: UIApplication) {            self.appStatus = "terminate"      }</code></pre>    <h2>MVC模式</h2>    <h2>MVC模式简介</h2>    <p>MVC(Model-View-Controller 模型-视图-控制器),模式是相当古老的设计模式之一,MVC由三部分组成,这三部分作用如下:</p>    <p>1. <strong>模型:</strong> 保存应用数据的状态,回应视图对状态的查询,处理应用业务逻辑,完成应用的功能,将状态变化通知视图;</p>    <p>2. <strong>视图:</strong> 为用户展示信息并提供接口。用户通过视图向控制器发出动作请求,然后再向模型发出查询状态的申请,而模型状态的变化会通知给视图;</p>    <p>3. <strong>控制器:</strong> 接收用户请求,根据请求更新模型。另外,控制器还会更新选择的视图,并将其作为对用户请求的回应。控制器是视图和模型的媒介,可以降低视图与模型的耦合度,使视图和模型的职责更加清晰,从而提高开发效率。</p>    <h2>MVC模式模型图</h2>    <p style="text-align:center"><img src="https://simg.open-open.com/show/75902c99894d0963b50e1ff4dbd6ee1d.png"></p>    <p style="text-align:center">MVC模式模型图</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/7b3921c70fdd</p>    <p> </p>