Builder Pattern

  • Build Complex Objects
  • Separate Object Creation from Other Code
  • Reduce Complex Links Between Objects

Target Classes

class Crayon:
String color
class CrayonBox:
List[Crayon] contents
function addCrayon(Crayon c): contents.add(c)

Builder Interface

interface CrayonBoxBuilder:
function buildBox()

Builder Class

class EightBoxBuilder implements CrayonBoxBuilder:
function buildBox(): CrayonBox box = new CrayonBox() box.add(new Crayon("White")) box.add(new Crayon("Black")) box.add(new Crayon("Red")) box.add(new Crayon("Orange")) box.add(new Crayon("Yellow")) box.add(new Crayon("Green")) box.add(new Crayon("Blue")) box.add(new Crayon("Violet"))

Builder Class

class SixteenBoxBuilder implements CrayonBoxBuilder:
function buildBox(): CrayonBox box = new CrayonBox() box.add(new Crayon("White")) box.add(new Crayon("Black")) box.add(new Crayon("Red")) box.add(new Crayon("Dark Red")) box.add(new Crayon("Blue Green")) box.add(new Crayon("Sunbeam")) box.add(new Crayon("Sky Blue")) box.add(new Crayon("Royal Purple")) box.add(new Crayon("Tan")) box.add(new Crayon("Brown")) box.add(new Crayon("Pink")) box.add(new Crayon("Eggshell")) ...

Using the Builder

class Main:
function main(): CrayonBoxBuilder builder = new SixteenBoxBuilder() CrayonBox box = builder.buildBox()

Factory Method Pattern

  • Get Objects By Name/Enum/ID
  • Don't Need Underlying Type
  • Easily Modify Factory Class
  • Decoupled Architecture

Factory Method Class

class CrayonBoxFactory:
function getBox(int size): if size == 8: return new EightBoxBuilder().buildBox() else if size == 16: return new SixteenBoxBuilder().buildBox() else if size == 32: return new ThirtyTwoBoxBuilder().buildBox() else if size == 48: return new FortyEightBoxBuilder().buildBox() ...

Using the Factory Method

class Main:
function main(): CrayonBoxFactory factory = new CrayonBoxFactory() CrayonBox box = factory.getBox(16)

Singleton Pattern

  • Only One Instance
  • Conserve Resources
  • Globally Shared State
  • Alternative to Static

Singleton Class

class CrayonBoxFactorySingleton:
static CrayonBoxFactorySingleton instance = null
static function getInstance(): if instance is null: instance = new CrayonBoxFactorySingleton() return instance
function getBox(int size): if size == 8: return new EightBoxBuilder().buildBox() else if size == 16: return new SixteenBoxBuilder().buildBox() ...

Using the Factory Singleton

class Main:
function main(): CrayonBox box = CrayonBoxFactorySingleton.getInstance().getBox(16)

Creational Patterns

  • Simplify Building Objects
  • Reduce Links Between Classes
  • Don't Repeat Yourself (DRY)
  • Easily Add New Types of Items
  • Think About Imports