Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Swift 2 Design Patterns
  • Table Of Contents Toc
Swift 2 Design Patterns

Swift 2 Design Patterns

By : Lange
3 (2)
close
close
Swift 2 Design Patterns

Swift 2 Design Patterns

3 (2)
By: Lange

Overview of this book

Swift is a multi-paradigm language. It has expressive features familiar to those used to work with modern functional languages, while also keeping the object-oriented features of Objective-C. It remains compatible with Apple’s legacy codes and frameworks. A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem in object-oriented systems. It describes the problem, the solution, when to apply the solution, and its consequences. It also gives implementation hints and examples. Knowledge about design patterns is also one of the best ways to make you different compared to other low-level developers. This book shows you how to use Swift 2 to learn about 23 Gang of Four (GoF) design patterns, and is organized into three categories. The book will present you the five creational patterns, followed by the seven structural patterns, and finishing with the 11 behavioral patterns as defined by the GoF. Each chapter will introduce the pattern by defining its role, which common problems the pattern should be used for, its generic UML representation, how each objects presented in the class diagram participate in the pattern, and what the role of each of these objects is. The book then presents you with a concrete case as an illustration that will be used to implement the pattern using Swift.
Table of Contents (10 chapters)
close
close
9
Index

The factory method pattern

Our second pattern is a very well-known pattern. It introduces you to the famous concept: "Program to an interface, not an implementation." The instantiation is done in the factory class that depends on the type that we need and the type that needs to be returned to the client.

Roles

The factory method pattern is one of the most used patterns in software designs. The purpose of this pattern is to abstract the creation of an object. The factory method lets a class defer instantiation to subclasses.

You'll see from that time to time that we have mentioned "program to an interface." This is exactly what this pattern does. With Swift, instead of an interface, you'll code with the "protocol" instead of the class itself.

This pattern is used in the following use cases:

  • A class only knows about abstract classes or interfaces of objects with whom it has some relationships
  • A class wants its subclasses to instantiate the object in order to benefit of polymorphism mechanism

Design

The following diagram shows the generic class of the factory method pattern:

Design

Participants

Participant to this pattern are as follows:

  • Product interface: This class contains the definition of our product. We will define what a card is here.
  • Abstract product: This abstract class implements the signature of our cards and some methods. You'll see that we keep the prototype pattern that allows us to eventually clone a card. These classes define the properties of our products.
  • Concrete product: This class defines our product; in our example, the Raid Leader card is a concrete product, such as the Faceless Manipulator card.
  • Concrete creator: This class implements our factory method.

Illustration

In our previous pattern, you would have seen the following line:

let raidLeader = Card(name: "Raid Leader", mana: 3, attack: 2, defense: 2)

Here, we directly program an implementation. We need a way to create some cards, but without having the knowledge to know exactly how to construct the card; we can only tell to create the raidLeader and Faceless Manipulator cards. At this point of time, the client doesn't want to know that the Raid Leader card needs three manas, so it provides two points of attack and two points of defense.

Implementation

The implementation of the factory method pattern is as follows:

import UIKit
import Foundation

//Define what a card is
protocol Card {
  var name: String? {get set}
  var attack: Int? {get set}
  var defense: Int? {get set}
  var mana: Int? {get set}
  func clone() -> Card
  func toString() -> String
}

// AbstractCard
// implements the signature and some properties
class AbstractCard: NSObject, Card {
  private var _name: String?
  private var _mana: Int?
  private var _attack: Int?
  private var _defense: Int?
  
  init(name: String?, mana: Int?, attack: Int?, defense: Int?) {
    self._name = name
    self._attack = attack
    self._defense = defense
    self._mana = mana
    super.init()
  }
 
  override init(){
    super.init()
  }
  
  //property name
  var name: String?{
    get{ return _name }
    set{ _name = newValue }
  }
  
  //property mana
  var mana: Int? {
    get{ return _mana }
    set{ _mana = newValue }
  }
  
  //property attack
  var attack: Int? {
    get{ return _attack }
    set{ _attack = newValue }
  }
  
  //property attack
  var defense: Int? {
    get{ return _defense }
    set{ _defense = newValue }
  }
  
  func clone() -> Card {
    return AbstractCard(name: self.name, mana: self.mana, attack: self.attack, defense: self.defense)
  }
  
  func toString() -> String{
    return ("\(self.name, self.mana, self.attack,self.defense)")
  }
}

enum CardType {
  case FacelessManipulator, RaidLeader
}

// our Factory Class
// Depending what we need, this class return an instance of the 
// appropriate object.
class CardFactory{
  class func createCard(cardtype: CardType) -> Card?{
    
    switch cardtype {
    case .FacelessManipulator:
      return FacelessManipulatorCard()
    case .RaidLeader:
      return RaidLeaderCard()
    default:
      return nil
    }
  }
}

//Concrete Card "Raid Leader"
//This is the full definition of the Raid Leader Card
class RaidLeaderCard: AbstractCard {
  override init()
  {
    super.init()
    self._mana = 3
    self._attack = 2
    self._defense = 2
    self._name = "Raid Leader"
  }
}

//Concrete Card "Faceless Manipulator"
//this is the full definition of the FacelessManipulator Card.
class FacelessManipulatorCard: AbstractCard {
  override init()
  {
    super.init()
    self._mana = 5
    self._attack = 3
    self._defense = 3
    self._name = "Faceless Manipulator"
    
  }
}

Usage

To simulate the use of the factory method pattern by a client, we can write the card creation as follows:

//simulate our client

var c = CardFactory.createCard(.FacelessManipulator)
c?.toString()

Note

To simulate our client, we simply tell the CardFactory method that we want a FacelessManipulator card.

To do this, we use the createCard method (our factory method), and this method will delegate the instantiation of the card that was asked.

The variable c has the type Card and not FacelessManipulator.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Swift 2 Design Patterns
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon