Marco
Marco

Reputation: 134

Factory-pattern for superclass and its subclasses

I have 3 classes which are one child of the other: Class C ->(subclass of)-> class B ->(subclass of)-> class A.

Every class is real and I want to choose which one to instantiate by a method. Can I use Factory-method and so factory-pattern to choose which class to create?

thank you.

Upvotes: 3

Views: 2936

Answers (2)

Krzysztof Błażełek
Krzysztof Błażełek

Reputation: 893

Yes, the factory method is the way to go in your context. I've provided quick example how to implement it.

import java.util.Scanner;

public class FactoryMethodExample
{
  public static void main(String[] args)
  {
    Scanner reader = new Scanner(System.in);
    System.out.println("Enter a letter A, B or C: ");
    String input = reader.nextLine();
    Factory factory = new ConcreteFactory();
    A myClass = factory.getClass(input.charAt(0));
    if(myClass != null)
    {
        myClass.print();
    }
    else
    {
        System.out.print("Wrong input");
    }
  }
}

class A
{
  public void print()
  {
    System.out.print("I'm class A");
  }
}

class B extends A
{
  @Override
  public void print()
  {
    System.out.print("I'm class B");
  }
}

class C extends B
{
  @Override
  public void print()
  {
    System.out.print("I'm class C");
  }
}

abstract class Factory
{
    public abstract A getClass(Character letter);
}

class ConcreteFactory extends Factory
{
    @Override
    public A getClass(Character letter)
    {
        if(letter.equals('A'))
        {
            return new A();
        } 
        else if(letter.equals('B'))
        {
            return new B();
        }
        else if(letter.equals('C'))
        {
            return new C();
        }
        return null;
    }
}

Upvotes: 2

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

Yes you can use factory method pattern with covarient return types. Here's a sample code.

public class MazeGame {

    public Maze createMaze() {
        // build the maze here.

        return aMaze;
    }

    public Room makeRoom(final int number) {
        return new Room(number);
    }

    public Wall makeWall() {
        return new Wall();
    }

    // ...
}


public class BombedMazeGame extends MazeGame {

    @Override
    public Room makeRoom(int number) {
        return new RoomWithABomb(number);
    }

    @Override
    public Wall makeWall() {
        return new BombedWall();
    }

}

Upvotes: 1

Related Questions