Skip to content

Instantly share code, notes, and snippets.

@funmia
Last active September 23, 2018 17:26
Show Gist options
  • Select an option

  • Save funmia/caf704f7fe53698b3cb4016bbabf8673 to your computer and use it in GitHub Desktop.

Select an option

Save funmia/caf704f7fe53698b3cb4016bbabf8673 to your computer and use it in GitHub Desktop.
Head First Design Patterns - Chapter 1

source: http://shop.oreilly.com/product/9780596007126.do

Chapter 1

  • Inheritance: extends
  • Interface: implements

Design patterns elevate your thinking about architectures by letting you think at the pattern level, not the nitty gritty object level.

What is a design pattern, why do we need design patterns, difference between a design pattern and a framework/library - Chapter1,pg 28,29.

OO Basics

  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

OO Design Principles

1). Separating what changes from what stays the same: Identify the aspects of your application that vary and separate them from what stays the same. If there's an aspect of the code that is changing, with every new requirement, then you know you have a behaviour that needs to be pulled out and separated from all the stuff that doesn’t change.

2). Program to an interface, not an implementation.

Relationships between classes:

  • IS-A
  • HAS-A
  • Implements

3). Favour composition over inheritance: When using the HAS-A relationship it allows for composition. Instead of inheriting behaviour from super type, they get their behaviour by being composed with the right behaviour object.

Design patterns rely on Objected Oriented basics and principles and shows ways to build systems with good OO design qualities.

Strategy Pattern:

The strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable. This allows you to choose the required process at run time.

Example

protocol WeaponProtocol {
    func useWeapon()
}

final class AxeBehaviour: WeaponProtocol {
    func useWeapon() {
        print("implements chopping with an axe")
    }
}

final class SwordBehaviour: WeaponProtocol {
    func useWeapon() {
        print("implements swinging a sword")
    }
}


class Character {
    var weapon: WeaponProtocol

    init(weapon: WeaponProtocol) {
        self.weapon = weapon
    }

    func set(weapon: WeaponProtocol) {
        self.weapon = weapon
    }

    func fight() {
        weapon.useWeapon()
    }
}

Usage:

let aQueen = Character(weapon: AxeBehaviour())
aQueen.fight()

aQueen.set(weapon: SwordBehaviour())
aQueen.fight()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment