ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바 디자인 패턴(2)_팩토리 패턴
    Java 2023. 11. 6. 16:57

    팩토리 패턴

    • 객체 생성 부분을 떼어내 추상화한 패턴
    • 상속 관계에 있는 두 클래스 중에 상위 클래스가 뼈대를 결정하고 하위 클래스가 객체 생성에 구체적인 내용을 결정
    • 상위 클래스는 인스턴스 생성 방식을 알 필요가 없어 유연성을 가진다.
    • 객체 생성 로직이 따로 있기 때문에 코드를 리팩터링해도 한 부분만 고치기 때문에 유지보수성이 증가한다.

     

    // 상위 클래스인 CoffeeFactory에서 Latte, Americano 같은 하위클래스의 구체적인 내용을 통해 가격을 산출
    abstract class Coffee {
        public abstract int getPrice();
        
        @Override
        public String toString() {
            return "coffee price : " + this.getPrice();
        }
    }
    
    class DefaultCoffee extends Coffee {
        private int price;
        
        public DefaultCoffee() {
            this.price = -1;
        }
        
        @Override
        public int getPrice() {
            return this.price;   
        }
    }
    
    class Latte extends Coffee {
        private int price;
        
        public Latte(int price) {
            this.price = price;
        }
        
        @Override
        public int getPrice() {
            return this.price;   
        }
    }
    
    class Americano extends Coffee {
        private int price;
        
        public Americano(int price) {
            this.price = price;
        }
        
        @Override
        public int getPrice() {
            return this.price;   
        }
    }
    
    class CoffeeFactory {
        public static Coffee getCoffee(String type, int price) {
            if ("Latte".equalsIgnoreCase(type)) {
                return new Latte(price);
            } else if ("Americano".equalsIgnoreCase(type)) {
                return new Americano(price);
            } else {
                return new DefaultCoffee();
            }
        }
    }
    
    public class HelloWorld{
    
         public static void main(String []args){
            System.out.println(CoffeeFactory.getCoffee("Latte", 2000)); // coffee price : 2000
            System.out.println(CoffeeFactory.getCoffee("Americano", 1000)); // coffee price : 1000
         }
    }

     

     

    출처)

    책 : 면접을 위한 CS 전공지식 노트

Designed by Tistory.