Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- 프로그래머스 옹알이 java
- time complexity
- 프로그래머스 연속된 수의 합 java
- sort
- 백준 14391
- 백준 16935
- 프로그래머스 네트워크 java
- Math.ceil()
- 백준 4375
- Algorithm
- java 내림
- Math.floor()
- java
- 백준 18290
- java 반올림
- 네트워크
- 백준 16927
- Codility
- 프로그래머스 도둑질 java
- Arrays
- mysql
- 코딩테스트
- 백준 11723
- 백준 15661
- 백준 17425
- 프로그래머스 숫자의 표현 java
- 0으로 채우기
- 자바
- 알고리즘
- java 올림
Archives
- Today
- Total
취미처럼
[DP] 팩토리 패턴 본문
팩토리 패턴(Factory Pattern)
객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴이자 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴
상위 클래스와 하위 클래스가 분리되기 때문에 느슨한 결합을 가지며 상위 클래스에서는 인스턴스 생성 방식에 대해 전혀 알 필요가 없기 때문에 더 많은 유연성을 갖게 된다.
또한 객체 생성 로직이 따로 떼어져 있기 때문에 코드를 리팩터링하더라도 한 곳만 고칠 수 있으니 유지 보수성이 증가한다.
abstract class Coffee {
public abstract int getPrice();
@Override
public String toString(){
return "This coffee is "+ this.getPrice();
}
}
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();
}
}
}
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;
}
}
public class Main{
public static void main(String []args){
Coffee latte = CoffeeFactory.getCoffee("Latte", 2000);
Coffee ame = CoffeeFactory.getCoffee("Americano",1000);
System.out.println("Factory latte ::"+latte);
System.out.println("Factory ame ::"+ame);
}
}
'Design Pattern' 카테고리의 다른 글
[DP] 옵저버 패턴 (0) | 2021.03.19 |
---|---|
[DP] 전략 패턴 (0) | 2021.03.19 |
[DP] 싱글톤 패턴 (0) | 2021.03.19 |
[DP] DIP (0) | 2021.03.19 |
[DP] ISP (0) | 2021.03.19 |
Comments