티스토리 뷰

Java

Decorator + Composite Pattern

techbard 2016.07.21 21:03

Composite.zip



# ISummable.java


public interface ISummable {

    int getSumUp();

    void setNumber(int number);

}



# Zero.java


public class Zero implements ISummable {


    @Override

    public int getSumUp() {

return 0;

    }


    @Override

    public void setNumber(int number) {

    }

}



# Number.java


public class Number implements ISummable {

    ISummable mSummable;

    private int number;


    public Number(ISummable summable) {

this.mSummable = summable;

    }


    @Override

    public void setNumber(int number) {

this.number = number;

    }


    @Override

    public int getSumUp() {

return this.number + mSummable.getSumUp();

    }

}



# Main.java


public class Main {


    public static void main(String[] args) {

ISummable c = new Zero();

c = new Number(c);

c.setNumber(1);

c = new Number(c);

c.setNumber(2);


c = new Number(c);

c.setNumber(-2);

System.out.println(c.getSumUp());

    }

}



# 결과


1


댓글
댓글쓰기 폼
공지사항
Total
400,094
Today
2
Yesterday
64
«   2019/03   »
          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            
글 보관함