Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

Decorator Pattern 예제 본문

Java/다양한 기능

Decorator Pattern 예제

Seung__ 2021. 11. 1. 21:23

1. Decorator Pattern


  • 자바의 입출력 스트림은 decorator pattern
  • 여러 decorator들을 활용하여 다양한 기능을 제공
  • 상속 보다 유연한 구현 방식
  • 데코레이터는 다른 데코레이터나 또는 컴포넌트를 포함해야 함
    • 데코레이터는 다른 데코레이터를 감싸거나 컴포넌트를 감싼다.
  • 지속적인 기능의 추가와 제거가 용이
  • decorator와 component는 동일한 것이 아님(기반 스트림 클래스가 직접 읽고 쓸 수 있음, 보조 스트림은 추가적인 기능 제공)
  • 즉 데코레이터를 통해 component의 메서드를 호출하고, 데코레이터는 부가기능을 제공.

 

 

 

2. 예제


  • Coffee
    • component = coffee
public class EtiopiaAmericano extends Coffee{

    @Override
    public void brewing() {

        System.out.println("Etiopia Americano");
    }
}
  • Decorator
    • Decorator 혼자 돌아갈 일 없으니 abstract로 
    • Decorator는 항상 component 또는 다른 Decorator 가 필요.
public abstract class Decorator extends Coffee{

    Coffee coffee;
    public Decorator(Coffee coffee){
        this.coffee = coffee;
    }

    @Override //데코레이터가 하는 일
    public void brewing() {
        coffee.brewing();
    }
}
public class Latte extends Decorator{

    public Latte(Coffee coffee) {
        super(coffee);
    }

    @Override
    public void brewing() {
        super.brewing();
        System.out.println("Adding Milk");
    }
}
public class Mocha extends Decorator{

    public Mocha(Coffee coffee) {
        super(coffee);
    }

    @Override
    public void brewing() {
        super.brewing();
        System.out.println("adding Mocha");
    }
}
public class CoffeeTest {


    public static void main(String[] args) {
       Coffee etiopiaCoffee = new EtiopiaAmericano();
       etiopiaCoffee.brewing();
        System.out.println("====================");

       Coffee etiopiaLatte = new Latte(etiopiaCoffee);
       etiopiaLatte.brewing();
        System.out.println("====================");

       Coffee etiopiaMochaLatte = new Mocha(new Latte(new EtiopiaAmericano()));
       etiopiaMochaLatte.brewing();
        System.out.println("====================");
    }
}
Etiopia Americano
====================
Etiopia Americano
Adding Milk
====================
Etiopia Americano
Adding Milk
adding Mocha
====================

 

 

3. GitHub : 211001 Decorator Pattern


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

'Java > 다양한 기능' 카테고리의 다른 글

Thread 클래스의 메서드  (0) 2021.11.02
Thread  (0) 2021.11.01
여러가지 입출력 클래스  (0) 2021.10.31
DataInput(Output)Stream, Serialization(직렬화)  (0) 2021.10.31
보조 스트림  (0) 2021.10.31
Comments