我的工厂方法的实现是否正确?

时间:2013-09-07 01:51:52

标签: java design-patterns factory-pattern

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

1 个答案:

答案 0 :(得分:1)

您正在使用工厂模式,但这看起来更像是简单工厂而不是工厂方法,因为使用的模式不允许您指定工厂类型(如果存在不同类型的BoardFactory)。 / p>

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

1)定义一个用作“创作者”的公共接口或抽象类
2)实例化Creator的实例并从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);
}
Reading material上的

difference