Post

Episode 6: ChampionFactory – Applying the Factory Design Pattern

Goal: Use the Factory Pattern to create heroes by name instead of using new manually. This helps scalability and readability.

Episode 6: ChampionFactory – Applying the Factory Design Pattern

1. Project Structure

1
2
3
src/
└── factory/
    └── ChampionFactory.java

2. Create ChampionFactory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package factory;

import model.*;
import java.util.Locale;

public class ChampionFactory {

    public static Hero createChampion(String name) {
        switch (name.toLowerCase(Locale.ROOT)) {
            case "garen":
                return new Warrior("Garen");
            case "darius":
                return new Warrior("Darius");
            case "ahri":
                return new Mage("Ahri");
            case "lux":
                return new Mage("Lux");
            default:
                throw new IllegalArgumentException("Unknown champion: " + name);
        }
    }
}

3. Update Champion Selection in Main.java

Modify your champion pool and selection code to use the factory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import factory.ChampionFactory;
import model.*;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<String> championNames = Arrays.asList("Garen", "Ahri", "Lux", "Darius");

        System.out.println("🔥 Welcome to Java MOBA Console 🔥\n");
        System.out.println("Choose your champion:");

        for (int i = 0; i < championNames.size(); i++) {
            System.out.println((i + 1) + ". " + championNames.get(i));
        }

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of your champion: ");
        int choice = scanner.nextInt() - 1;

        if (choice < 0 || choice >= championNames.size()) {
            System.out.println("Invalid choice. Exiting...");
            return;
        }

        Hero playerHero = ChampionFactory.createChampion(championNames.get(choice));
        Hero botHero = ChampionFactory.createChampion(championNames.get((choice + 1) % championNames.size()));

        System.out.println("\nYou chose: " + playerHero.getName());
        System.out.println("Bot will play: " + botHero.getName());

        playerHero.attack(botHero);
        botHero.attack(playerHero);

        scanner.close();
    }
}

This post is licensed under CC BY 4.0 by the author.