Bibi's DevLog πŸ€“πŸŽ

[Java] νŒ©ν† λ¦¬ λ©”μ†Œλ“œ νŒ¨ν„΄(기초) λ³Έλ¬Έ

πŸ–₯ BE λ°±μ—”λ“œ/Java μžλ°”

[Java] νŒ©ν† λ¦¬ λ©”μ†Œλ“œ νŒ¨ν„΄(기초)

λΉ„λΉ„ bibi 2021. 3. 2. 23:43

νŒ©ν† λ¦¬ λ©”μ†Œλ“œ

νŒ©ν† λ¦¬ λ©”μ†Œλ“œ νŒ¨ν„΄ Factory Method Pattern μ΄λž€?

μžλ°” λ””μžμΈνŒ¨ν„΄μ˜ ν•˜λ‚˜λ‘œ, 객체 생성을 λŒ€μ‹  μˆ˜ν–‰ν•΄ μ£ΌλŠ” 곡μž₯에 λΉ„μœ ν•  수 μžˆλ‹€.

객체λ₯Ό 직접 μƒμ„±ν•˜λŠ” λŒ€μ‹ , λ©”μ†Œλ“œλ₯Ό 톡해 κ°„μ ‘μ μœΌλ‘œ 생성 ν›„ λ°˜ν™˜ν•˜λŠ” 방식.
(κ°„μ ‘μ μœΌλ‘œ 객체λ₯Ό λŒ€μ‹  생성해 μ£ΌλŠ” λ©”μ†Œλ“œλ₯Ό νŒ©ν† λ¦¬λ©”μ†Œλ“œλΌκ³  ν•œλ‹€)

μž₯점

  • 생성할 클래슀λ₯Ό 미리 μ•Œμ§€ λͺ»ν•΄λ„ νŒ©ν† λ¦¬ ν΄λž˜μŠ€κ°€ 객체 생성을 λ‹΄λ‹Ήν•΄ μ€€λ‹€.
  • 객체의 μžλ£Œν˜•μ΄ ν•˜μœ„ν΄λž˜μŠ€μ— μ˜ν•΄ κ²°μ •λœλ‹€ - ν™•μž₯이 μš©μ΄ν•˜λ‹€
  • ν™•μž₯μ„± μžˆλŠ” 전체 ν”„λ‘œμ νŠΈλ₯Ό ꡬ성할 수 μžˆλ‹€.
  • λ™μΌν•œ ν˜•νƒœλ‘œ ν”„λ‘œκ·Έλž˜λ°μ΄ κ°€λŠ₯ν•˜λ‹€.

단점

  • 객체가 λŠ˜μ–΄λ‚  λ•Œ λ§ˆλ‹€ ν•˜μœ„ν΄λž˜μŠ€λ₯Ό μž¬μ •μ˜ν•΄μ•Ό ν•˜λ―€λ‘œ λΆˆν•„μš”ν•œ λ§Žμ€ ν΄λž˜μŠ€κ°€ 생성될 수 μžˆλ‹€.

예제

Shape.java

public interface Shape {
    void draw();
}

Circle.java

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Circle - draw() Method.");
    }
}

Rectangle.java

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle - draw() Method.");
    }
}

Square.java

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Square - draw() Method.");
    }
}

ShapeFactory.java

public class ShapeFactory {
    // νŒ©ν† λ¦¬ λ©”μ†Œλ“œ - 객체 생성 ν›„ λ°˜ν™˜
    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;
    }
}

FactoryPatternTest.java

public class FactoryPatternTest {
    public static void main(String[] args) {
        // νŒ©ν† λ¦¬ ν΄λž˜μŠ€μ—μ„œ 객체λ₯Ό 생성 ν›„ λ°˜ν™˜
        ShapeFactory shapeFactory = new ShapeFactory();

        Shape shape1 = shapeFactory.getShape("CIRCLE");
        shape1.draw(); // Circle λ©”μ†Œλ“œ 호좜

        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        shape2.draw(); // Rectangle λ©”μ†Œλ“œ 호좜

        Shape shape3 = shapeFactory.getShape("SQUARE");
        shape3.draw(); // Square λ©”μ†Œλ“œ 호좜
    }
}

좜처 : ν‹°μŠ€ν† λ¦¬ λΈ”λ‘œκ·Έ. κ°μ‚¬ν•©λ‹ˆλ‹€!