Introduction

I am going to complete something I have always want to do, which is finishing the Design Patterns book written by Eric Freeman. I have read this book for several times, but I never managed to finish it. I believe it’s time to finaly complete it. And for not forgeting the knowledge I have learned, I will write down the notes here.

Agenda

The following are the agenda of this hands-on. I will try to base on my understanding to explain the design pattern.

  • [ ] Day1: Introd to Design Pattern
  • [ ] Day2: Observer Pattern
  • [ ] Day3: Decorator Pattern
  • [ ] Day4: Factory Pattern
  • [ ] Day5: Singleton Patterns
  • [ ] Day6: Command Pattern
  • [ ] Day7: Adapter and Facade Pattern
  • [ ] Day8: Template Method Pattern
  • [ ] Day9: Iterator and Composite Pattern
  • [ ] Day10: State Pattern
  • [ ] Day11: Proxy Pattern
  • [ ] Day12: Compound Pattern

How to bend your brain into submission?

These tips are a starting point; listen to your brain and figure out what works for you and what doesn’t. Try new things.

  • Slow down. The more you understand, the less you have to memorize.
  • Do the exercises. Write your own notes.
  • Read the “There Are No Dumb Questions”
  • Make this the last thing you read before bed. Or at least the last challenging thing.
  • Drink water. Lots of it.
  • Talk about it. Out loud.
  • Listen to your brain.
  • Feel something! Get involved with the stories.
  • Design something!

When to use superclass and interface?

Let’s tell a story, we are an game factory and making different species of ducks. Every duck have their own quack and fly behavior. So we can create a superclass called Duck and put the common behavior in it. However, when the boss wants to add new behavior, such as fly, if we put the fly behavior in the superclass, then all the ducks will have the fly behavior. But not all the ducks can fly, so we need to create an interface called Flyable and put the fly behavior in it. Then we can implement the interface in the duck that can fly.

  • reduce code duplication in subclasses, we need to implement the fly behavior in every duck that can fly or even can’t fly.

  • Now we take out the fly behavior from the superclass and put it in the interface. So we can implement the interface in the subclass duck that can fly. And the duck that can’t fly doesn’t need to implement the interface.

But there is a problem. If you want to override a few methods, these implemented subclass are all needed to be changed, which is a lot of work.

Therefore, we need to use the Design Pattern to solve this problem.

The core of Design Pattern

Take what varies and “encapsulate” it so it won’t affect the rest of your code.

Design Pattern provide a way to let some part of a system vary independetly of all other parts.