Factory Method (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼  Factory Method 패턴은 Creational 패턴에 속한다.  

 

Factory Method Pattern Structure


패턴의 목적 ( Intent ) : 

 Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

팩토리 메소드 패턴은 하나의 객체를 생성하는 인터페이스를 정의하는데 이때 어떤 객체를 생성할 것인지에 대한 결정권은 서브클래스에게 위임한다. 

 

패턴이 나오게 된 동기 ( Motivation ) :


프 레임워크는 일반적으로 추상클래스로 객체 사이의 관계를 정의하는데, 종종 객체를 생성해야 할 때도 있다. 아래 다이어그램은 다양한 종류의 문서를 사용자에게 보여줄 수 있는 프레임워크의 클래스 다이어그램이다. 아래 다이어그램에서 관계를 맺고 있는 추상클래스들은 Document와 Application이다. 사용자가 그림그리기 애플리케이션을 만들려면 두 추상클래스를 상속받아 DrawingApplication과 DrawingDocument 클래스를 정의해야하고, Application클래스는 필요에따라 Document 클래스를 생성 혹은 열기가 가능해야 한다. 

자, 그런데 문제는 특정 문서는 특정 애플리케이션에 의존적이라는 점이다. 예를 들어, docx는 워드에서 생성하는 문서이지 한글에서 생성하는 문서가 아닌 것과 같은 현상이라고 보면 된다. 따라서 Application의 CreateDocument()를 추상메소드로 정의하고 이를 서브클래스에서 구현하도록 하여 각각의 Application마다 각각의 Document를 생성하도록 한 것이다. 이때 CreateDocument()를 팩토리 메소드라고 부른다. 

 

 

유용성 ( Applicability ) :

 Use the Factory Method pattern when


· a class can't anticipate the class of objects it must create.
· a class wants its subclasses to specify the objects it creates.
· classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


등장 인물 ( Participants ) :

· Product (Document)
o defines the interface of objects the factory method creates.
· ConcreteProduct (MyDocument)
o implements the Product interface.
· Creator (Application)
o declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
o may call the factory method to create a Product object.
· ConcreteCreator (MyApplication)
o overrides the factory method to return an instance of a ConcreteProduct.


원리 ( Collaborations ) :

· Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.


패턴 사용의 장단점 ( Consequences ): 

 Factory methods eliminate the need to bind application-specific classes into your code. The code only deals with the Product interface; therefore it can work with any user-defined ConcreteProduct classes. A potential disadvantage of factory methods is that clients might have to subclass the Creator class just to create a particular ConcreteProduct object. Subclassing is fine when the client has to subclass the Creator class anyway, but otherwise the client now must deal with another point of evolution. 

 

Here are two additional consequences of the Factory Method pattern:


1. Provides hooks for subclasses. Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object.
In the Document example, the Document class could define a factory method called CreateFileDialog that creates a default file dialog object for opening an existing document. A Document subclass can define an application-specific file dialog by overriding this factory method. In this  case the factory method is not abstract but provides a reasonable default implementation.


2. Connects parallel class hierarchies. In the examples we've considered so far, the factory method is only called by Creators. But this doesn't have to be the case; clients can find factory methods useful, especially in the case of parallel class hierarchies.
Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class. Consider graphical figures that can be manipulated interactively; that is, they can be stretched, moved, or rotated using the mouse. Implementing such interactions isn't always easy.
It often requires storing and updating information that records the state of the manipulation at a given time. This state is needed only during manipulation; therefore it needn't be kept in the figure object. Moreover, different figures behave differently when the user manipulates them. For example, stretching a line figure might have the effect of moving an endpoint, whereas stretching a text figure may change its line spacing. With these constraints, it's better to use a separate Manipulator object that implements the interaction and keeps track of any manipulation-specific state that's needed. Different figures will use different Manipulator subclasses to handle particular interactions. The resulting Manipulator class hierarchy parallels (at least partially) the Figure class hierarchy:


The Figure class provides a CreateManipulator factory method that lets clients create a Figure's corresponding Manipulator. Figure subclasses override this method to return an instance of the Manipulator subclass that's right for them. Alternatively, the Figure class may implement CreateManipulator to return a default Manipulator instance, and Figure subclasses may simply inherit that default. The Figure classes that do so need no corresponding Manipulator subclass—hence the hierarchies are only partially parallel.
Notice how the factory method defines the connection between the two class hierarchies. It localizes knowledge of which classes belong together.

 

관련 패턴들 : 

 Abstract Factory is often implemented with factory methods. The Motivation example in the Abstract Factory pattern illustrates Factory Method as well.
Factory methods are usually called within Template Methods. In the document example above, NewDocument is a template method.
Prototypes don't require subclassing Creator. However, they often require an Initialize operation on the Product class. Creator uses Initialize to initialize the object. Factory Method doesn't require such an operation.

 

추가 정보 :     

 
  • Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype.
  • Factory Methods are usually called within Template Methods.
  • Factory Method: creation through inheritance. Prototype: creation through delegation.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Prototype doesn't require subclassing, but it does require an Initialize operation. Factory Method requires subclassing, but doesn't require Initialize.
  • The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
  • Some Factory Method advocates recommend that as a matter of language design (or failing that, as a matter of style) absolutely all constructors should be private or protected. It's no one else's business whether a class manufactures a new object or recycles an old one.
  • The new operator considered harmful. There is a difference between requesting an object and creating one. The new operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.

 

출처 :  http://sourcemaking.com/design_patterns/factory_method

Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )