Home - sivakrsna/DesignPatterns GitHub Wiki

Design Patterns

  • A general reusable solution to commonly occurring problem with a given context in software design.
  • Design patterns are solutions to programming problems that automatically implement good design techniques.
  • Someone has already faced the issues you’re facing, solved them, and is willing to show you what the best techniques are.
  • We need not re-invent the wheel.

Three Categories

  1. Creational
  2. Structural
  3. Behaviour

Design Principles

Encapsulate what varies

Identify the aspects of your application that vary and separate them from what stays the same.

  • Take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don’t.

Program to an interface, not an implementation.

“Program to an interface” really means “Program to a supertype.”

You can program to an interface, without having to actually use a Java interface. The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn’t locked into the code. And we could rephrase “program to a supertype” as “the declared type of the variables should be a supertype, usually an abstract class or interface, so that the objects assigned to those variables can be of any concrete implementation of the supertype, which means the class declaring them doesn’t have to know about the actual object types!”

Programming to an implementation would be:

Dog d = new Dog();
d.bark();

But programming to an interface/supertype would be:

Animal animal = new Dog();
animal.makeSound();

Favor composition over inheritance.

  • When you put two classes together like this you’re using composition. Instead of inheriting their behavior, the ducks get their behavior by being composed with the right behavior object.
  • It also lets you change behavior at runtime.

Strive for loosely coupled designs between objects that interact.

  • Loosely coupled designs allow us to build flexible OO systems that can handle change because they minimize the interdependency between objects.

The Open-Close Principle

  • Classes should be open for extension, but closed for modification.