In our daily development, design patterns accompany each module of the project, and the clever use of design patterns allows us to write more efficient, concise, and beautiful code. However, due to my unfamiliarity with design patterns, many efficient design patterns have not been well used. Recently, I happened to review some codes written by my colleagues and myself, and then I talked about some optimizations made by using design patterns in the project during the optimization process. Of course, just personal views, any lack of welcome pat brick, we discuss and grow together.

1. The choice of using delegate Pattern and block in the project


In the tech community, I’ve seen tech gods arguing over which block and delegate should be used, and I’ve seen people say that the delegate is passing Pointers and the block is passing a structure, and in that sense delegate is better, but in our actual development environment, I prefer to make different choices based on specific business scenarios, because the delegate code is not as readable as the Block code. Specifically, we made the following choices.

First, the delegate and block are encapsulated in the network request layer. The reason is that in the specific business, the request will appear in class A, but the corresponding model created by the data we return will be called in class B. At this time, we use block to pass the data model. Because you might be encapsulating two or more layers of agents, this makes the code very unreadable. If the model passes on more layers, the code will look very messy.

Second, in the actual development of some complex interface will use dispatch_group_t, if you want to merge network requests, if you send two or more network requests in the same method, if you use the delegate to return the result, Dispatch_group_t is declared as a property, dispatch_group_leave(self.group) is used as a callback, and then dispatch_group_notify is used as a callback. I think this is not reasonable for group memory management, so I used block at this time. The rest of the time I’m in an interface, I’m more likely to use the #prama Mark method to identify a request and write the request as a proxy.

Of course, in addition to the network request layer processing, do we have a choice between the delegate and the block somewhere else? I remember that we have encountered it in the process of developing the live version of “U Sports”, a fitness coach. I believe that you are familiar with the live interface. If you click the anchor’s avatar, audience’s avatar and the nickname in the comment area, the user’s information will pop up. However, these three parts were divided into three small classes. At that time, my colleague proposed that each click event should be called back in the way of block, and a Manager management class should be written to handle the popup user information uniformly. I think many people would think of such a treatment scheme at the first time, but later they used the agent scheme.




The code structure of the solution is shown in the figure above, which is a simple demo. That is to say, we have differentiated the agent mode. All click events to obtain user data go through the agent of baseMethod1, so that all click events to obtain user data go through a method of controller. There is no need to create a manager for this, or even to expose a callback method in every attempt, which feels like an improvement in code simplicity and clarity, as well as being compatible with each attempt having its own callback event. So the choice between delegate mode and block is not fixed, you have to make your own analysis based on the specific business scenario and then make your choice.

2. The usage of Adapter pattern


I think some of my classmates in the process of company projects grow a lot of such a question, is will be returned by the server data into a data model and then to each tried to interface rendering interface, but sometimes tell us products, how about getting my user data, presented a parameter, if the interface name in the form of a parameter name is named, It’s going to be very difficult to change a lot of the places that were called. This time some friend will say interface incoming parameters is a kind of good, but if the user information to multiple interfaces in the same way, but each interface as a whole under the condition of the data returned is different, if the interface parameters, to do with class may need in trying to split the user data provide a lot of interface, And then exposed to the interface call, obviously such a way is not reasonable. So how do you solve this problem? That’s where the adapter pattern comes in. The code structure is as follows




Adapter pattern usage

If, in adapter mode, we are trying to pass parameters to multiple places that need to be used, instead of defining multiple parameters or classes through the interface, the parameters we define are the data model that complies with a certain protocol, and we can just follow the corresponding protocol in the data model returned by each interface. If the product tells us to change the requirement again, we add the corresponding method to the protocol, and then search for the class that complies with the corresponding protocol to implement the method, and the interface will be easier to deal with. Of course, I will only briefly analyze the use of adapters. It is not only used in the adaptation interface, some controllers in real projects also use such a scheme, even the adapter protocol has to do the operation of complying with the protocol, in its upper layer to create an adapter, which needs to be combined with the specific business scenario. However, adapters can help us a lot in increasing the readability of code and simplifying the code. Better use is still a friend to try and imagine

3. Use of singleton pattern


I think for most developers, this pattern of development is familiar to all of us. The reason for mentioning the singleton pattern here is that I think singletons may be overused in many projects, and there may be dozens or more singletons in a single project.

As we all know, after a singleton is created, it is not released until the end of the program, so the use of singleton should be noted from a memory management perspective. We should know when we can use singletons and in what business scenarios we can avoid singletons to save our memory. For example, if we do a live broadcast, some students may create a singleton to judge the current state of users and restrict their behaviors in order to record whether users are in the live broadcast. In fact, such a scenario, I think use singleton is a kind of irrational behavior, because in this mode, we can create a class in the broadcast management class method to create a method, that will be the current state of the state is stored in NSUserDefault judgment, thereby saving the corresponding memory, also avoid the unreasonable waste of memory space, There are many similar distances between indifference and here. Students who want to deal with the problem can check their own project and make a better solution.

4. Some issues that may need attention in other design patterns

In addition to the above most commonly used design patterns, we commonly used design patterns in projects such as factory pattern, observer pattern, policy pattern and some of the projects used in the mediator, template, share pattern and so on.

The first thing I want to talk about is the observer mode, and I think you’ve all used NSNotificationCenter and KVO or FBKVO in iOS development. But I don’t think everyone knows the exact thread in which the NSNotificationCenter observer receives the message. In fact, the thread on which the method is executed after receiving the message is the same as the thread on which the POST message was executed. Therefore, there may be a thread safety problem. Although Apple said in the official documentation that it has been handled, it does not mean that there will be no problems in actual development. For details, please refer to this article, which introduces the problem scenario. We have encountered such situation when using KVO in our project.

As for strategy mode, I think we have been useful in daily development, but some of our students do not know this is called strategy ~~~ in fact, the use of strategy really can greatly improve the readability of the program, so do not know the partner must baidu, I will not introduce in detail here.

The personal feeling of intermediary mode is mainly used for URL jump in componentized development. Our project always hopes to make efforts towards componentized development, so we may study this part in depth recently. If we have achievements to share with children, there will be too much to say, so we will not expand here.

The use of template pattern in the project is actually can be combined with the adapter pattern to play, so the adapter partner, for here must be familiar with, if this is not very understanding, really recommended to learn and pay attention to good code quality is very important.

Finally speaking of the share mode, I said that it was a very serious mistake to use it in very few projects, because I believe that every project must have tableView and its cell reuse pool mechanism is based on the share mode design, strictly speaking, the share mode in enterprise projects by their own design and use is relatively rare. However, when we need to reuse a large amount of data, considering the performance and other aspects of the problem, we must consider this mode, and then do the corresponding optimization, will have unexpected magic effect ~~~


By the end of the article, want to say that in fact I this person is lazy, don’t like to write articles, write their own small experiment were silly stay on your own computer, but some of the recent side has happened to my attitude has changed, so from now on, I should be mandatory requirements at least once a week to write an article with their own shallow view, Put your own little ideas and boring little wheels into Git. If you have any comments or dissatisfaction, you are welcome to poke fun here. Of course, I hope to grow up with kids who love iOS development