Skip to the content.

Design
Patterns
and
Principles

-

What we’ll cover

-

What is a Design Pattern?

-

Purpose of a Design Pattern

-

Four Essential Elements of a Pattern

  1. Pattern Name
  2. Problem
  3. Solution
  4. Consequences

-

1. Pattern name

-

2. Problem

-

3. Solution

-

4. Consequences

-

Classifying Design Patterns

-

Creational Patterns

-

Two Recurring Themes of Creational Patterns

  1. They encapsulate knowledge about which concrete classes the system uses
    • Abstracts the instantiation process
  2. Hide how instances of classes are created and put together
    • Helps make a system independent of how its objects are created, composed, or represented

-

Singleton Pattern

-

Brief Example

public class GoFishGame {
  private List<GoFishPlayer> playerList;

  public void createPlayer() {
    String userPrompt = "What is your profile ID?";
    IOConsole console = new IOConsole();
    ProfileManager profileManager = ProfileManager.getInstance();

    Integer profileId = console.getIntegerInput(userPrompt);
    Profile profile = profileManager.getById(profileId);
    GoFishPlayer player = new GoFishPlayer(profile);
    playerList.add(player);
  }
}

-

Creational Patterns: Builder

-

Brief Example

-

Creational Patterns: Factory

-

Brief Example

public class PersonFactory {
  // factory method
  public Person createRandomPerson() {
    return createRandomlyAgedPerson(RandomUtils.createInteger(0, 100));
  }

  // factory method
  public Person createRandomlyAgedPerson(String name) {
    Integer randomAge = RandomUtils.createInteger(0, 100);
    return new Person(name, randomAge);
  }
}

-

Structural Patterns

-

Brief Example

public void demo() {
	CasinoPlayerProfile player = ProfileManager.getCurrentPlayer();
	CasinoPlayerProfile blackJackPlayer = new BlackJackPlayer(player);
	blackJackPlayer.increaseProfileBalance(100);
}

-

Behavioral Patterns

-

Template Pattern

-

Example

// degree of 1
public static Integer[] getRange(int start) {
    return getRange(0, start, 1);
}

// degree of 2
public static Integer[] getRange(int start, int stop) {
    return getRange(start, stop, 1);
}

// template method; degree of 3
public static Integer[] getRange(int start, int stop, int step) {
    List<Integer> list = new ArrayList<>();
    for(int i = start; i<stop; i+=step) {
        list.add(i);
    }
    return list.toArray(new Integer[list.size()]);
}

-

Image of Puppies