The Swift programming language has transformed the world of iOS development and started a new age of modern development. Pro Design Patterns in Swift shows you how to harness the power and flexibility of Swift to apply the most important and enduring design patterns to your applications, taking yourContents at a GlanceAbout the authorAbout the technical reviewerPart I: Getting Ready mann 1Chapter 1: Understanding design patterns mmmmmm 3Chapter 2: Getting Used to Xcode9Chapter 3: Creating the SportsStore App■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■25Part i the creation patternsChapter 4: The object Template Pattern mmammmmammmmmmm.55Chapter 5: The Prototype Pattern■■■■■■■国■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■国■■Chapter 6: The Singleton Pattern aammmmmmn 113Chapter 7: The object Pool Patternng137Chapter8:0 bject Pool variati0ns…,,,,,,,,…,,,,,,…,,157Chapter 9: The Factory Method Pattern187Chapter 10: Abstract Factory Pattern■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■207Chapter 11: The Builder Pattern mmRRRRIBRRIRBR EEIIRRRIRIIRIRIIIIIIn 233Contents at a glancePartl:ThestructuralPatterns251Chapter 12: The Adapter Pattern■■■■■■■■■口■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■口■■■■■■253Chapter 13: The Bridge Pattern■■■■■■■■■■■■■■■■■■■■口■■■■■口■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■271Chapter 14: The Decorator Pattern293Chapter 15: The composite Pattern.ammmmammmmmmammaaaaaaaamamaam 311Chapter 16: The Facade Pattern■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■口■325Chapter 17: The Flyweight Pattern mamammammmmmamaaaammnn 339Chapter 18: The Proxy Patternmmmamma mamamIRIna 357Part va the behavioral patternsChapter 19: The Chain of Responsibility Pattern383Chapter 20: The command Pattern.mmmmmmm EIRIIaI 401Chapter 21: The Mediator Pattern■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■423Chapter 22: The observer Pattern an「■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■447Chapter 23: The Memento Pattern mmmmmmmmmmmam naa 473Chapter 24: The Strategy Pattern■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■口■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■491Chapter 25: The visitor Pattern mBm mmmm503Chapter 26: The Template Method Pattern mmmm 517Part v: The mvc pattern…n…■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■525Chapter 27: The Model/view/Controller Pattern527Index 553PartGetting readyChapterUnderstanding Design PatternsDesign patterns are insurance policies for software development. Insurance policies work by tradinga little cost now to avoid the possibility of a lot of cost later. the premium you pay to insure a caragainst theft, for example, costs a few percent of the value of the car, but when the car is stolenyour overall costs are minimized. You still have to go through the inconvenience of having your carstolen but at least you don 't have to bear the financial loss as wellIn software development, design patterns are insurance against the time taken to solve problemsThe premium is the time it takes to add extra flexibility to your code now, and the payout is avoidinga painful and protracted rewrite to change the way the application works later. Like real insurancepolicies, you may not benefit from paying the premium because the problem you anticipate mightnever happen, but software development rarely goes smoothly and problems often arise, so thatadditional flexibility is usually a good investmentThis is a book for hands-on professional programmers. I focus on the practical applications ofdesign patterns and focus on code examples instead of abstract descriptions I describe the mostimportant design patterns and demonstrate how they can be applied to ioS using Swift. Some of thepatterns I describe are already implemented in the Cocoa framework classes, and I show you howuse them to create more robust and adaptable applicationsBy the time you have finished reading this book, you will understand the most important designpatterns in contemporary software development, the problems they are intended to solve, and howto apply them to your Swift projectsPutting design Patterns into ContextEvery experienced programmer has a set of informal strategies that shape their coding style. Thesestrategies are insurance policies against the recurrence of problems from earlier projects. If you havespent a week dealing with a last-minute database schema change, for example, then you will take alittle extra time on future projects making sure that dependencies on the schema are not hard-codedthroughout the application, even though you don't know for certain that the schema will changethis time around. You pay a little premium now to avoid the potential for a bigger cost in the futureCHAPTER 1: Understanding Design PatternsYou may still have to make changes, but the process will be more pleasant, just like the process ofshopping for a replacement car is made more pleasant when the insurance company pays for thestolen oneThere are two problems with informal strategies. The first problem is inconsistency. Programmersith similar experiences may have different views about what the nature of a problem is and willdisagree about the best solutionThe second problem is that informal strategies are driven by personal experiences, which can beassociated with strong emotions. Describing the difficulty of fixing a problem rarely conveys thepain and misery you endured, and that makes it hard to convince others of the need to invest inpreventative measures. It also makes it difficult to be objective about the importance of the problemBad experiences linger, and you may find it hard to accept that there is little support for making thechanges that would avoid problems you have encountered on previous projectsIntroducing Design Patternsa design pattern identifies a common software development problem and provides a strategyfor dealing with it, rather like the informal approach that I described earlier but that is expressedobjectively, consistently, and free from emotional baggageThe strategies that design patterns describe are proven to work, which means you can compareyour own approach to them. And, since they cover the most common problems, you will find thatthere are design patterns for problems that you have not had to personally endureMost of the other design patterns in this book originate from a classic book called Design Patterns.Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnsonand John Vlissides(Addison-Wesley, 1995). The authors of this book are referred to as the gangof Four(GoF), and the patterns they describe are some of the most important and fundamental inmodern software developmentThe Gof book is worth reading but is somewhat academic in nature. Design patterns are expressedabstractly without reference to a particular programming language or platform. This abstractionmakes them hard to use; it can be difficult to figure out whether a pattern describes a problem thatyou are concerned about and difficult to be sure that you have correctly implemented the solutionMy goal in this book is to put design patterns in context and give you all the information you need toeasily identify and apply the patterns that you need, along with a Swift implementation that you canapply directly to your projectUnderstanding the structure of a Design PatternMost design patterns apply to small groups of objects in an application and solve a problem thatarises when one object- known as the calling component-needs to perform an operation on one ormore other objects in the applicationFor each of the design patterns in this book, I describe the problem the pattern solves, explain howthe pattern works, and show you how to implement the pattern using Swift. I also describe commonvariations on the pattern and describe the pitfalls most closely associated with the patternCHAPTER 1: Understanding Design PatternsWHERE IS THE UML?The Unified Modeling Language(UML) is often used to describe patterns, but I don't use it in this book. I am not a fan ofUML for several reasons. First, most developers don 't completely understand UMl and take in little information from aUML diagram. there are exceptions, of course and these tend to be people who work in large corporations where there isa detailed analysis and design phase before development commences. For the rest of the world, UML is a poorly definedand misinterpreted mess of boxes and linesfind that UML is good for expressing some kinds of relationship but fails dismally at representing others. to a greatextent, understanding patterns means understanding where logic that represents knowledge of other components exists,which is hard to convey using UMLFinally, and rather less objectively, UML is symptomatic of many aspects of software development that I don 't like. All toooften, UML is used as a weapon to enforce static and inflexible designs and inhibits adapting a development process tomeet evolving customer needs because the UML becomes an unchanging reference pointFor these reasons, as subjective as they are, don' t use UML in this book. Instead, I'll use free-form diagrams to illustratethe points that i want to emphasizeQuantifying the value of Design PatternsIt is easy to accept that design patterns are a good thing. Everyone understands the appeal ofproven solutions used on countless projects to solve difficult problems. It is much harder to convinceother programmers on the team that a specific pattern should be adopted in a projectYou can assess whether an insurance policy represents value for money by asking yourself somequestionsDoes the policy address something bad that is likely to happen to me?How often does the bad thing occur?Is the cost of the policy a small fraction of the cost of dealing with the badthing?These simple questions make it easy to understand that there is no point in buying car insurance ifyou don't have a car or if there are no car thieves in your town. They also highlight the poor valuein paying $10,000 per year to insure an $11,000 car unless you anticipate multiple thefts(in whichcase, you might also consider moving to a different area)The point is clear even though this is a simplistic view of insurance: don't buy a policy unless itoffers some benefit. The same is true for design patterns: dont adopt a pattern unless it offers valuethat you can quantify and articulate to others. the questions needed to assess the value for designpatterns are similarDoes the pattern identify a problem that I am likely to encounter?How often does this problem occur?Do I care enough about avoiding the risk of having to fix the problem in thefuture to undertake the work of implementing the design pattern today?CHAPTER 1: Understanding Design PatternsIt can be hard to answer these questions. There are no actuarial tables for software developmentand it can be hard to estimate the amount of future effort that will be required to fix a problemespecially one that may not arise)Instead, it can be easier to focus on the immediate benefits that a design pattern can offer Forexample, those patterns that increase the modularity of an application generally do so to minimizethe effect of a future change, but a modular application has fewer tightly coupled componentswhich means that it is easy to isolate units of code. Being able to isolate units of code is essentialfor effective unit testing, and so adopting a change-insurance pattern has an immediate benefit ofimproving the testability of codeEqually, design patterns that increase the amount of abstraction in an application allow new featuresto be added with less effort and less code duplication almost everyone can agree that quicker andeasier development is a good thing, even if they dont agree with the need to avoid the problem thata design pattern is intended to guard againstThere are no easy answers, however, and the final decision to adopt a design pattern will be drivenby the combined experience of the development team, the confidence in the completeness of thespecification, and the competence of individual developersUsing a Design Pattern After the Problem OccurredYou will find it hard to drive the adoption of patterns if you are the sole voice promoting them in ateam that has no experience of them and little time to consider them. The chances are that you willfail to convince others don t be frustratedMy advice is not to push too hard. If you force the team into following new practices, you will be heldaccountable for every problem and delay they cause, which will be especially difficult if the problemyou are trying to guard against never happens. Advocates for design patterns are, sadly, often seenpredictors of unlikely doomDon't lose hope, but put this book away and wait. If the problem you are concerned about doesntoccur-if, for example, the database schema doesn't change-then take pleasure in that the projectdodged a bullet and move on to the next assignmentDon't worry if the problem does occur; you can still benefit from design patterns. Your project is noyin a situation that you had hoped to avoid, but you can use the patterns as a framework for diggingyourself out of the hole. Select the most appropriate design pattern and use it as a framework tostructure the clean code around which you drive the resolution of the problem In this way, you canleverage a bad situation to introduce the team to a proven solution to the problem. This isn,'t as goodas avoiding the problem in first place, but at least you will be able to create a long-term solution andlend some credibility to your enthusiasm for design patternsUnderstanding the Limitations of Design PatternsThere is a lot to like about design patterns, but they have their limitations. By their nature, designpatterns are solutions to problems that other people have encountered on other projects Designpatterns are a starting point for avoiding or solving a problem and not a precisely tailored solutionThat doesn't mean they are not useful, but they do require some work in order to adapt them to fitinto your projectCHAPTER 1: Understanding Design PatternsTreat design patterns as recipes. Tinker, adapt, and adjust a pattern, and you will end up withsomething that works for you. You might need to refine your implementation a few times, and youuse of a pattern is likely to get better with insight gained from several projects, but you'll end up withsomething that improves on your starting position and that helps minimize the impact of a commonproblemSome programmers treat design patterns as immutable laws. They are pattern zealots, someonewho promotes the use of patterns as an inflexible"best practice"that should always be followedand cannot be adapted. That s rubbish. Applying patterns that you don't need or resisting adapting apattern to fit into a project misses the point entirelyThere is no point trying to argue with a pattern zealot They get their pleasure from being able toreference ever more obscure sources, and there is no effective way to ground their views in realityMy advice is to ignore them and focus on building good software by making it robust, scalable, andflexible enough to cope with changes, all of which can be aided by the design patterns described inthis bookAbout this bookIn this book, I describe how to use the most important design patterns using Swift and the Cocoaframeworks. Swift has attracted many new developers to the apple platform, so I have written thisbook to provide all of the information you will need about Swift and the Cocoa classes I use. I alsoshow you how to create the example projects using Xcode, which can be a confusing tool if you arenew to the world of Swift development. You can download all of the examples from Apress. com if youdon't want to type in the code yourselfWhat do you need to knowYou need to be an experienced developer to follow the concepts in book. No prior experience ofSwift is required, but you should understand the basic concepts of object-oriented programming andhave used a modern language such as Objective-C, C#, Java, or JavaScriptWhat Software Do you need?You need to have a Mac running Os X 10.10 (Yosemite) and have downloaded and installed Xcode6.1.TogetXcode,youwillneedtosignupasanAppleDeveloper,whichyoucandoathttps://developer. apple. com. Don't worry if you are new to Xcode; I,'ll show you everything you need toknow to follow the examples in Chapter 2What is the structure of this book?This book is split into five parts, each of which covers a set of related topics. Part 1 contains thischapter and an Xcode primer for the techniques you will need to follow for the example in thisbook. I also build an example application called Sports store that I return to throughout this book todemonstrate how to apply design pattern in context