MVC模式,与模式设计的学习

来源:互联网 发布:约翰丹佛 知乎 编辑:程序博客网 时间:2024/05/01 18:03

MVC模式(Module - View - Controller)

      MVC模式最早是smalltalk语言研究团提出的。而Object-C正是从smalltalk进化而来的。

      MVC模式是一个复杂的架构模式,其实现也显得非常复杂。但是,我们已经总结出了很多可靠的设计模式,多种设计模式结合在一起,使MVC模式的实现变得相对简单易行。Views可以看作一棵树,显然可以用Composite Pattern来实现。ViewsModels之间的关系可以用Observer Pattern体现。Controller控制Views的显示,可以用Strategy Pattern实现。Model通常是一个调停者,可采用Mediator Pattern来实现。

      Cocoa 提供了多个内部机制:Key-Value Coding(KVC)、Key-Value Observing(KVO)、
Key-Value Binding(KVB)。

      一个开发者可以利用这些功能,将自己创建的类写的很范化、很通用,然后通过KVB 将多个视图“绑定”到一个或多个控制器上,再将控制器绑定到最底层的数据模型上。这样一来,任何一个视图上的改变都会通过KVC 被“压”到控制器里,然后又通过KVC 从控制器“压”到数据模型里。当数据模型中的值发生改变时,一个或多个控制器又会得到KVO 的“通知”,接着只要被绑定了的视图又会得到这一个或多个控制器的KVO“通知”。这样以来,开发者只需要在适当的时候告诉Cocoa,什么对象的什么值该和什么对象的什么值绑定,就可以了,其余数据更新、格式化等工作Cocoa 都会替你完成。

      下面会依次学习分析上面的细节。

What is Key-Value Coding? 

(Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.)

http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/Overview.html#//apple_ref/doc/uid/20001838-SW1

What is Key-Value Observing?

(Key-value observing provides a mechanism that allows objects to be notified of changes to specific properties of other objects. )

http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueObserving/Concepts/Overview.html#//apple_ref/doc/uid/20001837-BAJEAIEE

What Are Cocoa Bindings?

(In the simplest functional sense, the Cocoa bindings technology provides a means of keeping model and view values synchronized without you having to write a lot of “glue code.” It allows you to establish a mediated connection between a view and a piece of data, “binding” them such that a change in one is reflected in the other.)

http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/WhatAreBindings.html

The Model-View-Controller Design Pattern

http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/WhatAreBindings.html#//apple_ref/doc/uid/20002372-175802