One of IOS design patterns (MVC and Singleton)

Source: Internet
Author: User

One of IOS design patterns (MVC and Singleton)
IOS design patterns-you may have heard of this term, but do you really understand what it means? Although most developers may think that design patterns are very important, there are not many articles on the subject of design patterns, and sometimes our developers do not pay too much attention to the code when writing it.
In the field of software design, design patterns are reusable solutions to common problems. The design pattern is a series of templates that help you write more understandable and reusable code. The design pattern helps you create loosely coupled code so that you can change or replace the components in the code without much effort.
If you are new to the design model, we have good news! First, thanks to the Cocoa build method, you have used many design patterns and encouraged best practices. Next, this guide will show you how to use IOS design patterns that are frequently used in most (not all) Cocoa.
This guide is divided into many parts, each of which involves a design pattern. In each part, you will understand the following content :? What is the design pattern ?? Why are you using the design model ?? How to use the design pattern and where it is appropriate and where it is worth attention. In this guide, you will create a music library application that displays your albums and their associated information. During the development of this application, you will be familiar with the frequently used Cocoa design patterns :? Creation type: Single-profit (single-State) and abstract factory? Structural: Model-View-controller, decorator, adapter, appearance (facade) and combination mode? Behavior Type: Observer, Memorandum, responsibility chain, and command mode should not be misled. This is an article about design pattern theory. In this music application, you will use the majority of these design patterns, and eventually your music application will grow as shown in:

Let's get started!Download the starter project, export the zip file, and use xcode to open BlueLibrary. xcodeproj. there are not many files in the project, only including the default ViewController and HTTP Client with empty implementations. note: When you create a new Xcode project, your code actually involves the design pattern. Do you know? Model-View-controller, Delegate, protocol, Singleton-you can use them for free without any effort. Before going deep into the first design mode, you must first create two classes to save and display the information of the music library album. In Xcode, navigate to "File \ New \ File..." (or press the Command + N shortcut), select IOS> Cocoa Touch, then Objective-C class, and click Next. Set the class name to Album, select NSObject as the parent class, click Next, and create.
Open the Album. h file and add the following attributes and method prototype between @ interface and @ end: Objective-c code.

  1. @ Property (nonatomic, copy, readonly) NSString * title, * artist, * genre, * coverUrl, * year;
  2. -(Id) initWithTitle :( NSString *) title artist :( NSString *) artist coverUrl :( NSString *) coverUrl year :( NSString *) year;

    Note that all the attributes in the new code are read-only, because they do not need to be modified after the Album object is created. The new method is object initializer. When you create a new album (album) object, you need to pass the album (album) Name, artist, album album art URL and year. Open the Album. m file and add the following code between @ implementation and @ end: Objective-c code.
    1. -(Id) initWithTitle :( NSString *) title artist :( NSString *) artist coverUrl :( NSString *) coverUrl
    2. Year :( NSString *) year {
    3. Self = [super init];
    4. If (self)
    5. {
    6. _ Title = title;
    7. _ Artist = artist;
    8. _ CoverUrl = coverUrl;
    9. _ Year = year;
    10. _ Genre = @ "Pop ";
    11. }
    12. Return self;
    13. }
      There is nothing complicated and fancy here. It is just an initialization method for creating an Album instance. In Xcode, navigate to "File \ New \ File..." again, select Cocoa Touch, then Objective-C class, and click Next. The setting class is named AlbumView, but this time the parent class is set to UIView. Click next and then click Create. Note: If you find that keyboard shortcuts are easier to use, Command + N creates a new file, Command + Option + N creates a new group, and Command + B builds your project, command + R will run it. Now open AlbumView. h and add the following method prototype between @ interface and @ end: Objective-c code
      1. -(Id) initWithFrame :( CGRect) frame albumCover :( NSString *) albumCover; now open AlbumView. m and replace all the code after @ implementation with the following code: Objective-c code
        1. @ ImplementationAlbumView
        2. {
        3. UIImageView * coverImage;
        4. UIActivityIndicatorView * indicator;
        5. }
        6. -(Id) initWithFrame :( CGRect) frame albumCover :( NSString *) albumCover
        7. {
        8. Self = [super initWithFrame: frame];
        9. If (self)
        10. {
        11. Self. backgroundColor = [UIColor blackColor];
        12. // The coverImage has a 5 pixels margin from its frame
        13. CoverImage = [[UIImageView alloc] initWithFrame: CGRectMake (5, 5, frame. size. width-10,
        14. Frame. size. height-10)];
        15. [Self addSubview: coverImage];
        16. Indicator = [[UIActivityIndicatorView alloc] init];
        17. Indicator. center = self. center;
        18. Indicator. activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        19. [Indicator startAnimating];
        20. [Self addSubview: indicator];
        21. }
        22. Return self;
        23. }
        24. @ End

          In the above Code, you must first note the coverImage instance variable. It represents the album art. The second variable is an indicator indicating that the cover image is being downloaded by rotation. In the initialization implementation, you set the background color to black, create an image view with a 5-pixel border, and create an indicator.
          Note: you may want to know why private variables are defined in the implementation file rather than in the interface file? This is because classes other than AlbumView do not need to know the existence of these variables. These variables are only used by internal functions of the class. This Convention is very important if you are developing a framework for other developers. Build (Command + B) Your project to ensure everything is well organized, are you OK? Then we are ready to welcome our first design model!
          Model-View-controller (MVC) pattern-king of Design Pattern

          Model-View-controller (MVC) is one of the building blocks of Cocoa and is undoubtedly the most frequently used design pattern. It classifies general roles so that class responsibilities can be clearly divided by roles. The three roles involved are as follows: Model stores application data and defines how to operate on it. For example, in this application, the model is the Album class. View: A View is a visual representation of a model and a control for user interaction. Basically, all the UIView objects and their subclasses belong to the View. In this application, AlbumView represents the view. Controller: the Controller is a Mediator that coordinates all work ). It accesses data in the model and displays them in the view. It also listens to events and operates data as needed. Can you guess which class is a controller? It is: ViewController. A good implementation of an MVC pattern means that every object will be divided into the group mentioned above. We can well describe the interaction process between views and models implemented by controllers:
          VcTjtcTXysHPv + response/Uyr6159Owus3K6byuyv2 + 3aGjuPy9 + response/response + response/Response ODW0Nfpus/queues + 7rP1eLW1rmk1/queues/uPa5pLPM1 + queues = "File \ create \ Group (File \ New \ Group)" (or press Command + Option + N ), name the group as Model. Repeat the same process to create the View and Controller groups. Now drag Album. h and Album. m to the model group, drag AlbumView. h and AlbumView. m to the view group, and then drag ViewController. h and ViewController. m to the Controller group. The project structure should look similar to the following:

          Without it, all the files are scattered everywhere, and now your project has been opened much better. Obviously, you can also have other groups and classes, but the core of this application is included in these three categories (Model, View, Controller ). Now all the components have been arranged. You need to obtain the album data from somewhere. You will create an API for managing data throughout the Code-this represents the opportunity to discuss the next design pattern-singleton (single-State) pattern.
          Singleton (single-State) ModeThe Singleton design mode ensures that only one instance exists for a given class and this instance has a globally unique access point. It usually uses the lazy loading method to create an instance when it is used for the first time. Note: This mode is widely used by Apple. For example, [NSUserDefaults standardUserDefaults], [UIApplication sharedApplication], [UIScreen mainScreen], and [NSFileManager defamanager manager]. All these methods return a singleton object. You may wonder why a class has multiple instances? After all, code and memory are cheap, right?
          In some cases, it is reasonable to have only one instance. For example, you do not need to have multiple Logger instances unless you want to write multiple log files. Or a global configuration processing class: it is easy to access Shared instances in a thread-safe way. For example, a configuration file contains multiple classes that modify the file at the same time.How to Use Singleton ModeFirst, let's take a look at the figure below:

          The figure above describes a class with a single attribute (it is a single instance), sharedInstance, and init methods. When the client sends the sharedInstance message for the first time, the instance attribute has not been initialized. Therefore, you need to create a new instance and return its reference. When you call sharedInstance next time, the instance can be returned immediately without any initialization. This logic always has only one instance. You will use this mode to create a class for managing all album data. You will notice that there is an API group in the project. In this group, you can put all the classes that provide services to your application. In this group, use the IOS \ Cocoa Touch \ Objective-C class template to create a new class, name it LibraryAPI, and set the parent class to NSObject. open LibraryAPI. h. replace its content with the following code: Objective-c code
          1. @ InterfaceLibraryAPI: NSObject
          2. + (LibraryAPI *) sharedInstance;
          3. @ End
            Open LibraryAPI. m now and insert the following method after @ implementation: Objective-c code
            1. + (LibraryAPI *) sharedInstance
            2. {
            3. // 1
            4. Static LibraryAPI * _ sharedInstance = nil;
            5. // 2
            6. Static dispatch_once_t oncePredicate;
            7. // 3
            8. Dispatch_once (& oncePredicate, ^ {
            9. _ SharedInstance = [[LibraryAPI alloc] init];
            10. });
            11. Return _ sharedInstance;
            12. }
              In this short method, there are some Notes: 1. Declare a static variable to save the class instance to ensure its global availability in the class. 2. declare a static variable dispatch_once_t, which ensures that the initialization code is executed only once. use Grand Central Dispatch (GCD) to execute the block to initialize the LibraryAPI variable. this is the key to the singleton mode: Once the class has been initialized, The initiattor will never be called again. The next time you call sharedInstance, the code in the dispatch_once block will not be executed (because it has been executed once), and you will get the original initialized instance.
              Note: to learn
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.