반응형

Design Pattern - Factory Pattern


(원문 위치 : http://www.tutorialspoint.com/design_pattern/factory_pattern.htm )

팩토리 패턴은 자바에서 가장 많이 사용되는 디자인 패턴중 하나이다. 이 디자인 패턴의 형태는 이 패턴이 객체를 생성하는 최선의 방법중 하나를 제공하는 것으로써 생성적 패턴에 포한된다.

팩토리 패턴에서 클라이언트에 생성로직을 노출하지 않고 객체를 생성하고 공통 인터페이스를 사용하여 새롭게 생성된 객체를 참조한다.


Implementation

Shape 인터페이스를 생성하고 Shape 인터페이스를 구현하는 클래스를 실체화한다. 팩토리 클래스 ShapeFactory는 다음 단계에 정의된다.

FactoryPatternDemo, demo 클래스는 Shape객체를 얻기위해 ShapeFacotry를 사용할 것이다. 이는 필요한 객체의 형태를 얻기 위해 ShapeFactory로 정보를 전달할 것이다.

Factory Pattern UML Diagram

Step 1

인터페이스를 생성한다.

Shape.java

public interface Shape {
   void draw();
}

Step 2

동일한 인터페이스를 구현하는 구체적인 클래스를 생성한다.

Rectangle.java

public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

Square.java

public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}

Circle.java

public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

주어진 정보에 기초한 구체적인 클래스의 객체를 성성하기 위한 팩토리를 생성한다.

ShapeFactory.java

public class ShapeFactory {
	
   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }		
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
}

타입같은 정로를 전달하는 것으로 구체적인 클래스의 객체를 얻기위한 팩토리를 사용한다.

FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}

Step 5

결과를 확인한다.

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.


반응형

+ Recent posts