Java EE Design Patterns

Classification and Scope Summary

The original Gang of Four Design Patterns can be categorized by their scope (compile-time or run-time) and by their purpose. Creational patterns are for creation and initialization. Structural patterns define relations between classes and objects. Behavioral patterns control communications and interactions.

CreationalStructuralBehavioral
Class Scope
(Compile-time)
-Factory Method-Adapter*-Interpreter
-Template Method
Object Scope
(Run-time)
-Abstract Factory
-Builder
-Prototype
-Singleton
-Adapter*
-Bridge
-Composite
-Decorator
-Facade
-Flyweight
-Proxy
-Chain of Responsibility
-Command
-Iterator
-Mediator
-Memento
-Observer
-State
-Strategy
-Visitor

*note that the Adapter can be Class or Object scope.

Factory Method

According to the table the Factory Method is set at compile-time so it should handle class creation and initialization. For my example, I have a table of Elements, a periodic table if you will. Each element has four properties: Number, Symbol, Name and Weight.

public class ElementFactory {
    //Factory Method
    public Element getElement(String element){
        //Creation
        if(element=="Hydrogen"){
            return new HydrogenElement();
        }else if (element=="Helium"){
            return new HeliumElement();
        }
        return null;
    }
}
package com.heathcasey.factorymethod;

import java.util.ArrayList;
import java.util.List;

public class FactoryMain {

    public static void main(String[] args) {
        ElementFactory elementFactory= new ElementFactory();
        List<Element> elements = new ArrayList<>();

        //Initialization
        elements.add(elementFactory.getElement("Hydrogen"));
        elements.add(elementFactory.getElement("Helium"));
        
        for(Element e:elements){
            System.out.printf("name:%s, symbol:%s, weight:%.3f, number:%s\n"
                    ,e.getName(),e.getSymbol(),e.getWeight(),e.getNumber());
        } 
    }  
}
public interface Element {
    public String getName();
    public String getSymbol();
    public Integer getNumber();
    public Double getWeight();
}

public class HydrogenElement implements Element{
    @Override
    public String getName() {return "Hydrogen";}
    @Override
    public String getSymbol() {return "H";}
    @Override
    public Integer getNumber() {return 1;}
    @Override
    public Double getWeight() {return 1.008;}
}

public class HeliumElement implements Element{
    @Override
    public String getName() {return "Helium";}
    @Override
    public String getSymbol() {return "He";}
    @Override
    public Integer getNumber() {return 2;}
    @Override
    public Double getWeight() {return 4.026;}  
}

Code can be found on my Github