Use design patterns to rationalize your iOS applications

Source: Internet
Author: User
Tags notification center
Document directory
  • Design Mode: design template for Solving Programming Problems
  • The most important design pattern: Model-View-Controller
  • Use design patterns to solve problems

Title: Use design patterns to rationalize your applications

Use design patterns to streamline your applications

In objective-C Programming, inheritance is a way to add specific behavior of an application. Subclass of the existing classes created, either adding the attributes and behaviors of the superclasses or modifying them to some extent. However, it also has other more dynamic ways to add specific behavior of the application, without involving subclass. These dynamic skills and methods are based on design patterns. As explained in this article, the adoption of design patterns in code helps increase the reusability and scalability of classes and framework classes.

Design Mode: design template for Solving Programming Problems

The design pattern is an abstract tool for Object-Oriented software development and other fields. It is a design template that solves general and repeated problems in a specific background. Therefore, the design pattern is a specific and specific design criterion: In a sense, it is the "instantiation" of the pattern ". There is a certain degree of flexibility in how to apply design patterns, such as programming languages and existing architectures, will affect how to apply the patterns.

There are several design themes or principles that affect the design model. These design principles are empirical rules for building object-oriented systems, such as "encapsulate the aspects of system structure that changes occur" and "interface-oriented programming, instead of implementing programming "(program to an interface, not an implementation ). They express important insights. For example, the encapsulation principle tells us that if we isolate and encapsulate the changed parts in the system, they can be changed independently of the other parts of the system, especially if you define interfaces that do not depend on implementation features for them. You can modify or expand these variable parts later without affecting other parts of the system. In this way, you have cleared the dependency between each part and reduced the coupling of each part, and the system will become more flexible and easy to modify.

This advantage makes the design pattern a key consideration for writing software. If you find the pattern in the application design, adjust and use it, the Program (and the objects and classes it contains) it will be more reusable, more scalable, and easier to modify when needed in the future. In addition, design-based applications are more elegant and more efficient than those that are not based on design patterns, because they can achieve the same purpose with only a small amount of code.

You will find that the application of the design pattern runs through the entire cocoa touch and cocoa framework, the runtime of objective-C, and the programming language itself. You can get some pattern-based mechanisms for almost "free", while others require you to do some work. When appropriate, you can apply the design pattern to your own application code. If you use the same pattern as the cocoa touch and cocoa frameworks, your code will often better match the Framework Code, and your running will be more elegant.

The most important design pattern: Model-View-Controller

Model-View-controller (Model-View-Controller) design pattern, usually called "MVC", assigns the following role to an object in the application: "model", "View", or "controller ". Mode not only defines the role of an object in an application, but also defines the communication mode between objects. Each of these three types of objects is separated by abstract boundaries and communicates with other types of objects through these boundaries. A set of MVC objects in an application, such as a model layer, is sometimes collectively referred to as a layer.

MVC is crucial to a good design for any iOS or Mac application. The benefits of using this design are numerous. Many objects in these applications tend to be more reusable, and their interfaces tend to be better defined. Applications designed with MVC are easier to expand than other applications. In addition, many of the technologies and architectures that your application can use are based on MVC and require your custom object to assume one of the MVC roles.

You may have created an MVC-based application: helloworld in your first IOS application. The model object is the username attribute (nsstring object), which is declared and managed by the helloworldviewcontroller class. An instance of the helloworldviewcontroller class and helloworldappdelegate class is the Controller object of an application. The view object of an application is a text bar, Tag, button, and background view.

For complete information about "Model-View-controller", see "Model-View-controller" in concepts in objective-C Programming (Concepts in objective-C programming ".

Model object

The model object encapsulates the data of an application and defines the logic and operations for manipulating and processing the data. For example, the model object may be a role in the game or a contact in the address book. Sometimes the model layer of an application is actually one or more graphics of the relevant object. After the data is loaded into the application, most of the data that is part of the application's persistence State (whether stored in a file or in a database) should reside in the model object. Because Model Objects represent knowledge and expertise related to specific problem areas, they can be reused in similar problem areas. The "pure" model object should not be explicitly connected to the view object (the view object displays its data and allows users to edit the data). It should not be concerned with the user interface and display issues.

The Data creation or modification operations performed by the user in the view layer are communicated through the Controller object, and the model object will be created or updated. When a model object is changed (for example, new data is received through a network connection), it notifies the Controller object that the controller object updates the corresponding view object.

View object

View objects are visible to users in applications. The view object knows how to draw itself and may respond to user operations. The main purpose of a view object is to display data from an application model object and make the data editable. However, in MVC applications, view objects are usually separated from model objects.

Because you usually re-use and reconfigure the object, the view object ensures consistency between applications. For iOS, The uikit framework provides a set of view classes; for OS X, the appkit framework provides similar sets. In uikit, view objects are ultimately inherited from the uiview class; In appkit, view objects are ultimately inherited from the nsview class.

View objects learn about the changes to model data through the Controller objects of the application, and modify the changes initiated by the user through the Controller objects (for example, text entered in the text column ), model object that is passed to the application.

Controller object

The Controller object acts as a medium between one or more view objects of an application and one or more model objects. The Controller object is therefore a synchronization pipeline program. Through this, the view object understands the changes to the model object, and vice versa. Controller objects can also perform setup and coordination tasks for applications and manage the lifecycles of other objects.

The Controller object interprets user operations performed on the view object and transmits new or changed data to the model object. When a model object is changed, a controller object transmits the new model data to the view object so that the view object can display it.

Use design patterns to solve problems

Object-Oriented systems (such as applications) are dynamic. What an object can do at runtime is not limited to the behavior set during writing. An object can send messages to another object, and the target of the same message changes according to the running status. An object can also work with a variable set of other objects at runtime, and use a variety of techniques to effectively complete the work of the application. To do this, an object or a group of objects must use many techniques and framework architectures, all of which are derived from design patterns.

The following sections describe many of these skills and architectures. Use them as part of your objective-C Programming toolkit.

Delegate: represents another object

In the delegate, an object called the delegate is represented by the request of another object. The object to delegate, usually the framework model. In some cases, it sends a message to the delegate, tells the delegate that some events are about to occur, and requests it to respond. The delegate (usually a custom instance) implements the method for calling the message and returns the corresponding value. Generally, this value is a Boolean value that indicates whether the delegate object continues the operation.

Therefore, a delegate is a means to add a specific behavior of an application to a framework class, without the need to create a subclass for this class. It is a common and powerful design to expand and influence the behavior of the framework.

You should remember that the helloworldappdelegate object was created when you wrote your first iOS app helloworld. Xcode automatically assigns the delegate to the Application Object (Framework object. The application delegate can process application: didfinishlaunchingwitexceptions: and other delegate messages sent to the application object.

There are two programmable components for delegation. The delegate class must define attributes (by the Convention named delegate) to save a reference pointing to the delegate. It must also declare the Protocol required for the delegate class (see the following section for more information about the Protocol ). Many classes of the cocoa touch and cocoa frameworks provide delegation as a way for applications to increase their specific framework behavior.

However, delegation is not limited to framework classes. You can perform delegation between two custom objects in the application. The common design of the cocoa touch application is to use delegation as a means to allow the subview controller to transmit certain values (usually user-input values) to the parent View Controller.

Protocol: enables communication between irrelevant objects through inheritance

A protocol is a declaration of a programmable interface, and any class can implement its method. The class instance associated with the Protocol calls the Protocol method and obtains the values returned by the formal adoption and implementation of the Protocol. Such communication between objects produces a specific target, such as parsing XML code or copying objects. Objects on both sides of the Protocol interface can be inherited to implement remote correlation. As with delegation, the Protocol can be used as a subclass replacement method, which is usually part of the Framework Implementation delegation.

The framework provided by Apple declares dozens of protocols. In addition, your application can declare custom protocols so that classes can adopt them. Protocols are part of your programming toolkit. Programming with objective-C (using objective-C Programming) describes the protocol comprehensively.

Notification center: Notify the observer interested in the event

The notification center is a subsystem of the foundation framework that broadcasts messages (notifications) to all objects registered as event observers in an application ). (From a programming perspective, it is an instance of the nsnotifcenter center class ). This event can be anything that occurs in the application, such as entering the background status, or the user starts to type in the text bar. The notification tells the observer that the event has occurred or is about to happen, so the observer has the opportunity to respond in the appropriate way. Dissemination of notifications through the notification center is a way to increase the cooperation and cohesion between application objects.

For example, The View Controller in the iOS app can observe the uikeyboardwillshownotification notification to adjust the ry of its view to accommodate the virtual keyboard. As shown in this example, a notification is an object. The object name specifies a specific event, and the event has occurred or is about to happen. It also sends a reference (pointing to an object that publishes or sends a notification) to the notification center, which can contain a supplemental information dictionary.

Any object can observe the notification, but to do so, the object must be registered to receive the notification. During registration, it must specify a selector to determine the method called by notification transmission. The method signature must have only one parameter: Notification object. After registration, the observer can also specify the publish object.

The notification in the notification center is similar to the delegate message. When some events occur, both are sent to any object. However, the notification processing method is different from the delegate method, and it cannot return a value. Notifications in the notification center are synchronized, just like delegated notifications.

Custom objects of the application can define and publish their own notifications. Other custom objects can observe the notifications.

Target-operation: encapsulate the message to be sent when an event occurs.

Objective-the operation design is very simple in concept. An object stores elements that constitute a message expression. When some events occur, these elements are put together and a message is sent. These elements are a selector used to determine the message (operation) and the object (target) that receives the message ). The target class will implement the method corresponding to the operation and the target. when it receives a message during running, it will respond to the event through the execution method.

Objective-the operation is mainly a control function in the cocoa touch and cocoa frameworks. Control is a user interface object. For example, a user sends a user's intent to an application through a signal by clicking or dragging a button, Slider, or switch. Cocoa touch controls store operations and goals. Most cocoa controls are paired with one or more unit objects, which store goals and operations.

Some frameworks use the target-action instead of control in objects. For example, the uikit framework uses the target-action when designing the gesture identification tool. After a gesture is recognized, the Operation message is sent to the target object.

Key Value observation: notifies the observer when the value is changed

Key-value observation (KVO) allows an object to observe the attributes of another object. When this attribute value is changed, the observed object is notified. It understands the new value and old value. If the observed attribute is a many-to-many relationship (such as an array), it also needs to know which object has changed. KVO helps make applications more cohesive and synchronize objects and changes in the model, Controller, and view layers.

Similar to nsicationicationcenter notifications, multiple KVO observers can observe a single attribute. In addition, KVO is more dynamic because it allows an object to observe any attributes without any new APIs, such as notification names. KVO is a lightweight point-to-point communication mechanism that does not allow you to observe the specific attributes of all instances.

Other framework designs based on design patterns

The cocoa touch and cocoa frameworks also include other designs based on the design patterns, including the following:

View level. The view displayed by the application is arranged in a hierarchical structure (intuitively based on inclusion ). This mode allows applications to treat a single view as a merged view. The root of the hierarchy is a window object. Each view below the root has a parent view and zero or multiple child views. The parent view contains the child view. View hierarchy is a structural component for drawing and event processing. Responder chain. The responder chain is a series of objects (mainly views, but also windows, view controllers, and application objects). events or operation messages can be transmitted along the responder chain, wait until an object in the chain processes the event. Therefore, it is a cooperative event processing mechanism. The responder chain is closely related to the view level. View Controller. Although both the uikit and appkit frameworks have View Controller classes, they are particularly important in IOS. A View Controller is a special controller object used to display and manage a group of views. The View Controller object provides a basic structure to manage content-related views and coordinate view display and hiding. View controllers manage child hierarchies of application views. Front-end. In foreground mode, the work performed by the application is redirected (or bounced back) from one execution environment to another. (The execution environment is a scheduling queue or operation queue associated with the main thread or auxiliary thread .) You apply the foreground mode to the following scenarios: tasks that must be executed in the queue, such as operations to update the user interface, are generated. Category. Category provides a way to extend the class by adding the method to a class. Like delegation, it allows you to customize behaviors without subclass. Category is a function of objective-C, which is described in the compilation of objective-C code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.