Skip to content

FactoryMethod

A pattern that delegates the actual creation responsibility of a factory method to subclasses.

  • When projectile creation rules differ by weapon type.
  • When type-specific initialization logic should be separated.
  • Creator
  • Concrete Creator
  • Product

The code below is a simplified Unity example based on the scenario described above.

using UnityEngine;
public interface IProjectile
{
void Fire(Vector3 startPosition, Vector3 direction);
}
public abstract class ProjectileSpawner : MonoBehaviour
{
public void Shoot(Vector3 startPosition, Vector3 direction)
{
IProjectile projectile = CreateProjectile();
projectile.Fire(startPosition, direction);
}
protected abstract IProjectile CreateProjectile();
}
  • It clarifies module boundaries and reduces coupling.
  • Features can be extended or integrated without modifying existing code.
  • If wrapper layers become too deep, debugging gets harder.
  • Interfaces should stay small so responsibility boundaries do not blur.

This shows the flow where the parent keeps the creation procedure while subclasses choose the actual type.

Factory Method Flow