logo

팩토리 메소드 패턴

팩토리 패턴 또는 팩토리 메소드 패턴은 다음과 같습니다. 객체를 생성하기 위한 인터페이스나 추상 클래스를 정의하되 인스턴스화할 클래스를 하위 클래스가 결정하도록 하세요. 즉, 하위 클래스는 클래스의 인스턴스를 생성하는 역할을 담당합니다.

팩토리 메소드 패턴은 다음과 같이 알려져 있습니다. 가상 생성자.

팩토리 디자인 패턴의 장점

  • 팩토리 메소드 패턴을 사용하면 하위 클래스가 생성할 객체 유형을 선택할 수 있습니다.
  • 그것은 촉진한다 느슨한 결합 애플리케이션별 클래스를 코드에 바인딩할 필요가 없어졌습니다. 이는 코드가 결과 인터페이스 또는 추상 클래스하고만 상호 작용하므로 해당 인터페이스를 구현하거나 해당 추상 클래스를 확장하는 모든 클래스와 작동한다는 의미입니다.

팩토리 디자인 패턴 활용

  • 클래스가 어떤 하위 클래스를 생성해야 하는지 알 수 없는 경우
  • 클래스가 하위 클래스에서 생성할 객체를 지정하기를 원하는 경우.
  • 상위 클래스가 하위 클래스에 객체 생성을 선택하는 경우.

팩토리 메소드 패턴용 UML

  • 우리는 Plan 추상 클래스와 Plan 추상 클래스를 확장하는 구상 클래스를 생성할 것입니다. 팩토리 클래스 GetPlanFactory가 다음 단계로 정의됩니다.
  • generateBill 클래스는 GetPlanFactory를 사용하여 Plan 개체를 가져옵니다. 정보(DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN)를 GetPalnFactory에 전달하여 필요한 개체 유형을 가져옵니다.

전기요금 계산 : 팩토리 방식의 실제 사례

1 단계: Plan 추상 클래스를 만듭니다.

 import java.io.*; abstract class Plan{ protected double rate; abstract void getRate(); public void calculateBill(int units){ System.out.println(units*rate); } }//end of Plan class. 

2 단계: Plan 추상 클래스를 확장하는 구체적인 클래스를 만듭니다.

 class DomesticPlan extends Plan{ //@override public void getRate(){ rate=3.50; } }//end of DomesticPlan class. 
 class CommercialPlan extends Plan{ //@override public void getRate(){ rate=7.50; } }//end of CommercialPlan class. 
 class InstitutionalPlan extends Plan{ //@override public void getRate(){ rate=5.50; } }//end of InstitutionalPlan class. 

3단계: 주어진 정보를 기반으로 구체적인 클래스의 객체를 생성하기 위해 GetPlanFactory를 생성합니다.

 class GetPlanFactory{ //use getPlan method to get object of type Plan public Plan getPlan(String planType){ if(planType == null){ return null; } if(planType.equalsIgnoreCase('DOMESTICPLAN')) { return new DomesticPlan(); } else if(planType.equalsIgnoreCase('COMMERCIALPLAN')){ return new CommercialPlan(); } else if(planType.equalsIgnoreCase('INSTITUTIONALPLAN')) { return new InstitutionalPlan(); } return null; } }//end of GetPlanFactory class. 

4단계: GetPlanFactory를 사용하여 계획 유형 DOMESTICPLAN, COMMERCIALPLAN 또는 INSTITUTIONALPLAN과 같은 정보를 전달하여 구체적인 클래스의 개체를 가져옴으로써 Bill을 생성합니다.

 import java.io.*; class GenerateBill{ public static void main(String args[])throws IOException{ GetPlanFactory planFactory = new GetPlanFactory(); System.out.print('Enter the name of plan for which the bill will be generated: '); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String planName=br.readLine(); System.out.print('Enter the number of units for bill will be calculated: '); int units=Integer.parseInt(br.readLine()); Plan p = planFactory.getPlan(planName); //call getRate() method and calculateBill()method of DomesticPaln. System.out.print('Bill amount for '+planName+' of '+units+' units is: '); p.getRate(); p.calculateBill(units); } }//end of GenerateBill class. 

전기요금 청구서 다운로드 예

산출