ITeye博客

简单工厂模式

zhangq168 · 2010-05-31 17:34 · 设计模式 · 企业架构 · Markdown

简单工厂模式的优点:隔离产品的创建者和使用者,明确各自的职责,降低耦合度

简单工厂模式的应用场景:使用者知道工厂需要的传入参数,但对如何生产出产品的逻辑并不关心

印证了

简单职责原则:一个类负责一件事情,一个类应该只有一个能引起他变化的因素。

变化点隔离原则:如果一块代码不同地方都有可能经常发生改变,则说明它们应该分开封装,同时避免超大类、超大方法的产生

 

public class Factory {
    public Window CreateWindow (String type) {
        if(type.equals("Big")) {
            return new WindowBig();
        } else if(type.equals("Small")) {
            return new WindowSmall();
        } else {
            return new WindowBig();
        }
    }

    // The Main function only for our test
    public static void main(String[] args) {
        Factory myFactory = new Factory();
        Window myBigWindow = myFactory.CreateWindow("Big");
        myBigWindow.func();

        Window mySmallWindow = myFactory.CreateWindow("Small");
        mySmallWindow.func();
    }
}

 

Factory的CreateWindow方法算是创建者,而main()方法算是使用者

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。