0

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

1 回答 1

1

您正在使用工厂模式,但这似乎更像是简单工厂而不是工厂方法,因为使用的模式不允许您指定工厂类型(应该有不同的类型BoardFactory)。

如果您想使用工厂方法,那么您应该

1) 定义一个作为“Creator”的通用接口或抽象类
2) 实例化一个 Creator 的实例并从中移除 static 修饰符createBoard

类似的东西

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);
}

阅读材料上的区别

于 2013-09-07T02:02:19.020 回答