[Design pattern] Factory method πŸ–², (Creational patterns)

홍정완·2021λ…„ 7μ›” 14일
0

Design pattern

λͺ©λ‘ 보기
3/7
post-thumbnail

Factory method

  • μΈν„°νŽ˜μ΄μŠ€λ‘œ 객체듀을 μ •μ˜ν•˜κ³ , νŒ©ν† λ¦¬κ°€ μΈμŠ€ν„΄μŠ€λ₯Ό 생성




μž₯점

  • 객체λ₯Ό μƒμ„±ν•˜λŠ” μ½”λ“œλ₯Ό λΆ„λ¦¬μ‹œν‚΄μœΌλ‘œ ν΄λΌμ΄μ–ΈνŠΈ μ½”λ“œμ™€ 결합도(μ˜μ‘΄μ„±)λ₯Ό πŸ‘‡
    πŸ‘‰ μ½”λ“œ λ³€κ²½ μ‹œ, 객체 생성 클래슀만 μˆ˜μ • κ°€λŠ₯

  • μΈν„°νŽ˜μ΄μŠ€λ₯Ό λ°”νƒ•μœΌλ‘œ μœ μ—°μ„±κ³Ό ν™•μž₯성이 λ›°μ–΄λ‚œ μ½”λ“œ κ΅¬ν˜„ κ°€λŠ₯

  • 객체의 μžλ£Œν˜•μ΄ ν•˜μœ„ ν΄λž˜μŠ€μ— μ˜ν•΄ κ²°μ •
    πŸ‘‰ ν™•μž₯ 용이

  • SOLID 원칙 쀑 DIP(Dependency Inversion Principle, 의쑴 관계 μ—­μ „ 원칙) 성립


단점

  • 생성할 객체의 μ’…λ₯˜κ°€ λ§Žμ•„μ§ˆμˆ˜λ‘, 클래슀 λ˜ν•œ πŸ‘†



ꡬ쑰




Code


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

    Shape shape1 = shapeFactory.getShape("CIRCLE");
    shape1.draw();

    Shape shape2 = shapeFactory.getShape("RECTANGLE");
    shape2.draw();
  }
}

πŸ‘‰ Factoryμ—μ„œ λ§Œλ“€μ–΄λ‚Ό μƒν’ˆλ“€μ„ μ •μ˜

public interface Shape {
  void draw();
}
public class Circle implements Shape {

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

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

πŸ‘‰ μƒν’ˆλ“€μ„ λ§Œλ“€μ–΄ 내보낼 νŒ©ν† λ¦¬ μ •μ˜


public class ShapeFactory {

  public Shape getShape(String shapeType) {
    if (ShapeType.equalsIgnoreCase("CIRCLE"))
      return new Circle();
    else if (ShapeType.equalsIgnoreCase("RECTANGLE"))
      return new Rectangle();
    else
      return null
  }
}
profile
μŠ΅κ΄€μ΄ μ „λΆ€λ‹€.

0개의 λŒ“κΈ€