티스토리 뷰

1. Factory Method 패턴 이란?

객체를 생성하기 위한 interface를 두고, 이를 구현하는 subclass에서 실제 객체를 생성하도록 하는 패턴이다.

new ~ 를 통해 객체를 생성하는 부분을 캡슐화 함으로써, 결합도록 낮츨 수 있다.



public abstract class Component {
    abstract void paint();
}

public class Button extends Component {
    // @override
    public void paint() {
        System.out.println("paint BigButton");
    }
}

public class Label extends Component {
    // @override
    public void paint() {
        System.out.println("paint Label");
    }
}

public abstract ComponentFactory {

    // 보통 template method pattern 과 함께 사용하며, 객체 생성하는 method를 포함함.
    public Component create(String type) {
        Component c = createComponent(type)
        return c;
    }

    // Factory method    
    protected abstract Component createComponent(String type);
}

public ConcreteComponentFactory {
    @override
    protected Component createComponent(String type) {
        if (type == "Button") {
             return new Button();
        } else if (type == "Label") {
             return new Label();
        }
    }
}

public class Main {
    ComponentFactory factory = new ConcreteComponentFactory();
    Component button =  factory.create("Button");
    Component label = factory.create("Label);
    
     button.paint();
     label.paint();
}
위 Main class에 Button, Label 객체를 생성하는 code는 없다. (Factory를 구현하는 class에 객체생성부분이 캡슐화 되어 있음) Main class는 Button, Label 을 몰라도 되므로 낮은 결합도를 가진다.

'Programing > DesignPattern' 카테고리의 다른 글

GOF 디자인 패턴  (0) 2016.10.04
State 패턴  (0) 2016.09.01
Template Method 패턴  (0) 2016.08.30
Composite 패턴  (0) 2016.08.24
Singleton 패턴  (0) 2016.08.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함