cocoa设计模式经典摘录1

cocoa设计模式经典摘录1,第1张

概述  id       The id type tells the compiler that a variable points to an object but doesn’t give the compiler any more specific information about the kind of object, hence the object is anonymous.     U

 

ID

 

    The ID type tells the compiler that a variable points to an object but doesn’t give the compiler any more specific information about the kind of object,hence the object is anonymous.

    Use the Anonymous Type pattern to send messages to anonymous objects,including objects that are not available at the time the sending code is compiled. Reduce coupling between classes by limiting the information that each class has about other classes. 

 

 

NSApplication,Events,and the Run Loop


    Most graphical user interface toolkits,including the Application Kit,use an event-driven model.That simply means applications react to events that are sent to the application by the operating system. Some events originate from user keyboard or mouse input.Timer events may arrive at periodic intervals. Other input sources like network sockets or inter- thread message queues may produce events.

    Cocoa applications receive events from the operating system with the help of the NSApplication and NSRunLoop classes. Every graphical Cocoa application contains one instance of the NSApplication class. NSApplication is a singleton,as described in Chapter 13,“Singleton.” The NSApplication instance creates an instance of NSRunLoop to receive events from the operating system. Multithreaded Cocoa application may use up to one NSRunLoop instance per thread.

    Run loops monitor input sources that are part of the operating system and block if no input is available.That just means that when there is no input available,the run loop doesn’t consume cpu resources. Many other user interface toolkits make the run loop a key focus for developers,but in Cocoa,the run loop plays only a small but crucial role. When input data becomes available,the run loop translates the data into events and sends Objective-C messages to varIoUs objects to process the events.

    In most cases,Cocoa programmers don’t need to access run loops directly because NSApplication takes care of all the details.The Application Kit uses the HIErarchIEs pat- tern and the Responder Chain pattern described in Chapters 16,“HIErarchIEs,” and 18,“Responder Chain,” respectively. NSApplication uses the hIErarchy of objects within your application and the resulting Responder Chain to determine which objects should receive which messages in response to events.

    The NSApplication class is seldom subclassed. Instead,the behavior of an application can be modifIEd through the use of an application delegate and notifications. Notification and Delegation are powerful patterns described in Chapters 14,“Notifications,”and 15,“Delegates,” respectively.

 

 

Delayed Perform


    To send a message after a delay,use NSObject’s - (voID)performSelector:(SEL)aSelector withObject:(ID)anArgument afterDelay:(NSTimeInterval)delay method.The message with the specifIEd selector and argument is scheduled and sent sometime after the specifIEd delay measured in seconds.

    Delayed Perform is actually implemented by Cocoa’sNSRunLoopclass.NSRunLoopis re- sponsible for accepting user input and monitoring a Cocoa application’s communication with the underlying operating system. Requests to send delayed messages are queued with the run loop associated with the thread making the request. Each time the run loop checks for user input,it also checks for queued requests. If enough time has elapsed since a queued request was made,the run loop sends the requested message with the specifIEd ar- gument.The run loop may not get a chance to run because the application is busy doing something else.Therefore,the run loop can’t guarantee that the requested message will be sent at a precise time. It can only guarantee that it won’t be sent too soon. If a zero delay is specifIEd when requesting the delayed message,the message is sent as soon as possible the next time the run loop runs. In all cases, performSelector:withObject:afterDelay: returns before the requested message is sent.

    The NSObject class method,+ (voID)cancelPrevIoUsPerformRequestsWithTarget: (ID)aTarget selector:(SEL)aSelector object:(ID)anArgument,can be used to cancel a prevIoUsly requested delayed message.This will cancel all delayed messages matching the target,selector,and argument specifIEd and queued by the run loop for the thread canceling the request.

    The NSRunLoop class can operate in several different modes.The modes determine which sources of input are read by the run loop.The performSelector:withObject: afterDelay: method schedules requests in the NSDefaultRunLoopMode,so if the run loop isn’t in that mode,the requested message won’t be sent.To specify which run loop modes are used to queue the delayed message request,use NSObject’s - (voID)performSelector: (SEL)aSelector withObject:(ID)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes method.

 

 

 

Objective-C runtime


    The Objective-C language uses a small,fast library of functions and data structures called a runtime.Many programming languages use a runtime;Java’sVirtual Machine is one of the best kNown runtimes,but C++ and even C also have runtimes. Objective-C’s run- time is primarily written in standard C and can be used from C or C++ programs even if those programs aren’t compiled with an Objective-C or Objective-C++ compiler.The Objective-C runtime provIDes supporting technology used to implement all of Cocoa’s design patterns,but some of the patterns in this book are little more than specific applica- tions of language runtime features:

    The runtime enables dynamic loading of Objective-C objects making the Bundles pattern possible.

    The runtime creates all object instances and underlIEs the Dynamic Creation pattern. n The runtime directly implements   

    The category pattern to add methods to existing classes.

    The runtime implements the messaging that is key to the Perform Selector and Delayed Perform patterns and the ProxIEs and Forwarding patterns.

 

 

 

Delegate


    A delegate is an object that’s given an opportunity to react to changes in another object or influence the behavior of another object.The basic IDea is that two objects coordinate to solve a problem. One object is very general and intended for reuse in a wIDe varIEty of situations. It stores a reference to another object,its delegate,and sends messages to the delegate at critical times.The messages may just inform the delegate that something has happened,giving the delegate an opportunity to do extra processing,or the messages may ask the delegate for critical information that will control what happens.The delegate is typically a unique custom object within the Controller subsystem of your application.

Delegates are one of the simplest and most flexible patterns in Cocoa and are made possible by the use of the Anonymous Type pattern described in Chapter 7,“Anonymous Type and Heterogenous Containers.” Delegates highlight key advantages of using anony- mous objects when designing reusable classes.

    Delegates simplify the customization of object behavior while minimizing coupling be- tween objects. Cocoa’s NSWindow class uses a delegate to control window behavior. NSWindow is a very general class that encapsulates all aspects of windows in a graphical user interface.windows can be resized and moved.They have embedded controls for closing,minimizing,or maximizing the window. Almost all graphical Cocoa applications use windows,yet window handling must be customized in many cases. For example,an application may need to constrain the size of a window or give users a chance to save changes to the content of a window before the window closes.

    One way to customize the behavior of the standard NSWindow class is to subclass it and implement new behaviors in the subclass. However,subclassing requires very tight cou- pling between the subclass and its superclass. Overuse of subclassing results in the creation of many classes that are application-specific and not very reusable. Subclassing statically establishes the relationship between the subclass and its superclass at compile time. In many cases,runtime flexibility is desired. For example,constraints on the resizing behav- ior of a window might change based on user actions at runtime. More importantly,the logic used to customize window behavior may depend on details of the application’s implementation. In the Model VIEw Controller pattern emphasized throughout Cocoa,windows are clearly part of the vIEw subsystem,but application details are better encapsu- lated within the model or controller subsystems. Subclassing NSWindow to add application logic causes a contamination between the separate subsystems.

    Thanks to the use of delegates,there is usually no need to subclass the NSWindow.The NSWindow class has a delegate and sends messages to the delegate just before the window is resized,closed,or otherwise modifIEd.When the window’s delegate receives messages sent by the window,the delegate can perform necessary application-specific processing such as checking to see if the window contains any unsaved changes before it is closed and if so,giving the user a chance to save the changes or cancel the operation.The dele- gate can be part of the controller subsystem and have little coupling to other subsystems. All the delegate has to do is implement the appropriate methods corresponding to mes- sages that the window will send to it.

    Using delegates simplifIEs application development. In many cases,this pattern is si- multaneously simpler to implement and more flexible than the alternative.The delegate is free to implement some,all,or none of the methods corresponding to delegate messages. A single object can be the delegate of multiple objects. For example,a single object might be the delegate for all of the windows in an application. Conversely,every window might have a different delegate,or the delegate might be changed at runtime.

 

 

 

Notifications


    The Notification pattern enables communication between objects without tight cou- pling.An object is able to broadcast information to any number of other objects without any specific information about the other objects.An instance of Cocoa’sNSNotification class encapsulates the information to be broadcast. Objects that are interested in receiving the information register themselves with an instance of Cocoa’s NSNotificationCenter class. Registered objects are called observers,and the Notification pattern is sometimes called the “Observer” pattern in other frameworks. Registered observers specify the types of communication desired.

    When a notification is sent to a notification center,the notification center distributes the notification to appropriate observers.A single notification may be broadcast to any number of observers.The object that sends a message to a notification center doesn’t need to kNow what observers exist or how many observers ultimately receive the notification. Similarly,the observers don’t necessarily need to kNow where notifications originate.     

    The NSNotificationCenter class stores registered observers as Anonymous Objects using the Heterogeneous Container pattern described in Chapter 7,“AnonymousType and Heterogeneous Containers.” Notification and Delegation are related patterns,and Delegation is explained in Chapter 15,“Delegates.” Notification is also similar to the Key Value Observing pattern described in Chapter 32,“Bindings and Controllers.”

    Use the Notification pattern to establish anonymous communication between objects at runtime.Within the ModelVIEw Controller design pattern,notifications safely cross sub- system boundarIEs without tying the subsystems together. Model objects often generate notifications that are ultimately received by controller objects,which react by updating vIEw objects. In the other direction,model and controller objects observe notifications that may originate in the vIEw or controller subsystems. For example,when a Cocoa ap- plication is about to terminate,the NSApplication controller object posts the NSApplicationWillTerminateNotification to the application’s default notification center. Model objects that need to perform clean-up processing before the application terminates register as observers to receive the NSApplicationWillTerminateNotification.

    Use the Notification pattern to broadcast messages. Notifications may be posted by any number of objects and received by any number of objects.The Notification pattern enables one-to-many and many-to-many relationships between objects.

Use the Notification pattern with Cocoa’s NSdistributedNotificationCenter class to achIEve simple asynchronous interprocess communication.

    Use the Notification pattern when anonymous objects need to passively observe and react to important events. In contrast,use the Delegates pattern when anonymous objects need to actively influence events as they happen.

总结

以上是内存溢出为你收集整理的cocoa设计模式经典摘录1全部内容,希望文章能够帮你解决cocoa设计模式经典摘录1所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1067589.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存