Search code examples
javadesign-patternsfactory-pattern

My implementation of the factory method is correct?


I am study factory method pattern and after reader in some places i did the following implementation. If in the future there is a need to add new types of boards, every time I have to change the BoardFactory class and the enum? Is this the correct approach to implement factory method?

public interface Board { }

public class MotherBoard implements Board { }

public class VideoBoard implements Board { }

public class AudioBoard implements Board { }

public enum BoardType {
    VIDEO,
    AUDIO,
    MOTHER_BOARD
}

public class BoardFactory {

    private BoardFactory() { }

    public static Board createBoard(BoardType boardType) {
        switch (boardType) {            
            case VIDEO:
                return new VideoBoard();
            case AUDIO:
                return new AudioBoard();
            default:
                return new MotherBoard();
        }
    }   
}

public class Main {
    public static void main(String[] args) {
        Board b1 = BoardFactory.createBoard(BoardType.VIDEO);
        Board b2 = BoardFactory.createBoard(BoardType.AUDIO);
        Board b3 = BoardFactory.createBoard(BoardType.MOTHER_BOARD);            
    }
}

Solution

  • You are using a factory pattern, but this seems more like Simple Factory rather than Factory Method, since the pattern used doesn't let you specify the factory type (should there be different types of BoardFactory).

    If you would like to use the Factory Method then you should

    1) Define a common interface or abstract class that serves as "Creator"
    2) Instantiate an instance of a Creator and remove the static modifier from createBoard

    something along the lines of

    abstract class AbstractFactory {
     public abstract BoardType createBoard(BoardType boardType);
    }  
    
    class BoardFactory extends AbstractFactory {
     // Implementation
    }
    
    class AwesomeBoardFactory extends AbstractFactory {
     // Implementation
    }
    
    public static void main(String[] args){
     AbstractFactory factory = new AwesomeFactory();
     Board b1 = factory.CreateBoard(BoardType.MOTHER_BOARD);
    }
    

    Reading material on the difference.