728x90
반응형
팩토리 메서드 패턴(Factory Method Pattern)

 

https://refactoring.guru/design-patterns/factory-method

Factory Method Pattern은 객체를 생성하기 위한 패턴 중 하나입니다.

객체 생성을 담당하는 별도의 클래스(Factory)를 두어, 객체 생성 과정을 캡슐화하고,

객체를 생성하는 책임을 분리하여 유연성과 확장성을 높이는 방법입니다.

 

즉, 클라이언트에서는 객체 생성을 요청하고, Factory에서는 요청에 맞는 객체를 생성하여 반환합니다.

이를 통해 객체 생성 과정이 변해도 클라이언트에 영향을 미치지 않도록 하는 것이 목적입니다.

 

Factory Method Pattern은 상속을 이용하여 객체 생성을 처리하기 때문에,

상속 구조를 가진 클래스들에게 적용하기 용이합니다.

또한 객체 생성 코드를 중앙화함으로써 코드의 가독성과 유지보수성을 높일 수 있습니다.

 

예를 들어, 게임에서 유닛을 생성하는데, 유닛의 종류에 따라 각기 다른 클래스를 생성해야 할 경우,

Factory Method Pattern을 이용하여 유닛 생성 과정을 캡슐화하고,

각 유닛 클래스에서는 생성에 대한 책임을 가지지 않고, Factory에서 생성된 유닛을 반환받아 사용하면 됩니다.

 

다음은 Factory Method Pattern을 구현한 예제 코드 입니다.

interface Animal {
    void makeSound();
}

class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("멍멍");
    }
}

class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("야옹");
    }
}

interface AnimalFactory {
    Animal createAnimal();
}

class DogFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}

class CatFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
}

public class Main {
    public static void main(String[] args) {
        AnimalFactory dogFactory = new DogFactory();
        AnimalFactory catFactory = new CatFactory();

        Animal dog = dogFactory.createAnimal();
        Animal cat = catFactory.createAnimal();

        dog.makeSound(); // 멍멍
        cat.makeSound(); // 야옹
    }
}

 

위 코드에서 'Animal' 인터페이스는 동물의 기본적인 기능을 정의하고

'Dog'와 'Cat' 클래스는 'Animal' 인터페이스를 구현합니다.

 

그리고 'AnimalFactory' 인터페이스는 'Animal' 인터페이스를 생성하는 메서드를 정의하며,

'DogFactory'와 'CatFactory' 클래스는 'AnimalFactory' 인터페이스를 구현합니다.

 

'Main' 클래스에서는 'DogFactory'와 'CatFactory' 객체를 생성한 후,

'createAnimal()' 메서드를 호출하여 각각의 'Animal' 객체를 생성합니다.

생성된 'Animal' 객체는 'makeSound()' 메서드를 호출하여 동물의 소리를 출력합니다.

이렇게 팩토리 메서드 패턴을 사용하여 객체를 생성하면,

클라이언트 코드에서 객체를 직접 생성하는 것보다 유연하고 확장성이 높은 코드를 작성할 수 있습니다.

728x90
반응형

'Language > Java' 카테고리의 다른 글

Observer Pattern  (0) 2023.04.14
Singleton Pattern  (0) 2023.04.14
Java - super, super()  (0) 2023.04.13
Java - Code Sample  (0) 2023.04.13
Java - Exception  (0) 2023.03.27

+ Recent posts