我正在研究工厂方法模式,在某些地方的读者之后我做了以下实现。如果将来需要添加新类型的板,每次我都必须更改 BoardFactory 类和枚举?这是实现工厂方法的正确方法吗?
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);
}
}