ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [java] Factory Method 디자인 패턴
    IT/Design Patterns 2022. 7. 9. 17:09

    출처 : unsplash.com

     

    이 블로그는 Geeks for Geeks에 등록된 글을 번역한 글입니다.
    최대한 자연스럽게 의역하려 하였으나 수정 필요한 부분이 있다면 댓글 남겨 주세요~
    원문: https://www.geeksforgeeks.org/factory-method-design-pattern-in-java/?ref=leftbar-rightbar

     

     

     

    팩토리 메서드 패턴은 객체 생성에 대한 생성 패턴중 하나이다. 팩토리 메서드 패턴은 인터페이스(자바에서 interface 나 추상 클래스)를 정의하고 서브 클래스가 객체를 인스턴스화할 수 있도록 한다.팩토리 메서드는 클래스가 하나 혹은 그 이상의 서브 클래스에게 인스턴스화할 수 있도록 한다.팩토리 메서드 패턴이 객체의 인스턴스화에 대해 다루기 때문에 생성 패턴으로 분류하고 있다. 팩토리 메서드라는 것은 일반적으로 생성과 관련되어 있는 팩토리라는 메서드가 있고 거기서 객체가 생성된다는 것이다. 객체를 생성하는 최고의 방법은 client가 객체 생성 로직을 모르게 하는 것이다. 이제 구현을 보자!

     

    구현 :

    1. 인터페이스 내부에 팩토리 메서드 정의하기

    2. 서브 클래스가 팩토리 메서드를 구현하고 어떤 객체를 생성할지 결정하게 하기

    자바에서 생성자는 다형성은 아니지만, 서브 클래스가 객체를 생성하게 한다. 그러므로써 인스턴스화에 다형성 동작을 추가한다.

    요약하자면, 서브 클래스가 무엇을 생성할지 결정하게 함으로써 의사 다형성(Pseudo polymorphism)을 성취하려 한다. 이러한 사유로 팩토리 메서드는 가상 생성자라 불리기도 한다. 실제 사례와 코드를 통해 구현해보자.

     

    문제 상황 :

    이메일, SMS, 푸시 알림을 통해 알림 서비스를 구현하려 한다. 팩토리 메서드 패턴을 사용해서 구현해 보자. 우선 이를 위한 UML 클래스 다이어그램을 그릴 것이다.

     

    위 클래스 다이어그램에서 Notification이라는 interface가 있다. 그리고 3개 concrete class가 Notification 인터페이스를 구현하고 있다. 팩토리 클래스인 NotificationFactory는 Notification 객체를 얻기 위해 생성된다. 자, 이제 코딩을 해보자.

     

     

    Notification 인터페이스 생성

    public interface Notification {
    	void notifyUser() ;
    }

    참고 - 위의 인터페이스는 추상 클래스로도 생성할 수 있다.

     

     

    모든 구현 클래스 생성

     

    SMSNotification.java
    public class SMSNotification implements Notification {
    
    	@Override
        public void notifyUser() {
        	// TODO Auto-generated method stub
            System.out.println("Sending as SMS notification") ;
        }
    }

     

    EmailNotification.java
    public class EmailNotification implements Nofitication {
    
    	@Override
        public void notifyUser() {
        	// TODO Auto-generated method stub
            System.out.println("Sending an e-mail notification") ;
        }
        
    }

     

    PushNotification.java
    public class PushNotification implements Notification {
    
    	@Override
        public void notifyUser() {
        	// TODO Auto-generated method stub
            System.out.println("Sending a push notification") ;
        }
    
    }

     

    concrete class를 인스턴스화하기 위해 팩토리 클래스 NotificationFactory.java 생성

    public class NotificationFactory {
    
    	public Notification createNotification(String channel) {
        	if (channel == null || channel.isEmpty())
            	return null ;
                
            switch(channel) {
            case "SMS" :
            	return new SMSNotificaion() ;
            case "EMAIL" :
            	return new EmailNotification() ;
            case "PUSH" :
            	return new PushNotification() ;
            default :
            	throw new IllegalArgumentException("Unknown channel " + channel) ;
            }
        }
    
    }

     

    이제 몇몇 정보를 전달함으로써 concrete class의 객체를 생성하고 get하기 위해서 팩토리 클래스를 사용하자.

    public class NotificationService {
    
    	public static void main(String[] args) {
        	NotificatoinFactory notificationFactory = new NotificationFactory() ;
            Notification notificatino = notificationFactory.createNotification("SMS") ;
            notification.notifyUser() ;
        }
        
    }

     

    Output : Sending an SMS notification

     

    실 사례

    이 디자인 패턴은 JDK에서 폭넓게 사용되어 왔다.

    1. java.util.Calendar, NumberFormat, 그리고 ResourceBundle의 getInstance() 메서드는 팩토리 메서드 패턴을 사용한다.

    2. java에서 Integer, Boolean 등과 같은 모든 wrapper 클래스는 valueOf() 메서드를 사용해서 값을 평가하기 위해 이 디자인 패턴을 사용한다.

    3. java.nio.charset.Charset.forName(), java.sql.DriverManager#getConnection(), java.net.URL.openConnection(), java.lang.Class.newInstance(), java.lang.Class.forName() 도 팩토리 메서드 패턴을 사용하는 사례 중 일부이다.

     

    결론

    지금까지 팩토리 메서드 패턴이 무엇이고 어떻게 구현할지에 대해 배웠다. 이제 이 설계 메커니즘의 이점에 대해 충분히 이해했을 것이라 믿는다.

     

     

    'IT > Design Patterns' 카테고리의 다른 글

    [UML] 시퀀스 다이어그램 (Sequence Diagram)  (0) 2022.06.10
    GoF 디자인패턴  (0) 2022.05.22
    소프트웨어 설계 5원칙 - SOLID  (0) 2022.05.22

    댓글

Designed by Tistory.