티스토리 뷰

Command03.zip



# ICalc.java


public interface ICalc {

    void calc(Data data);

}



# Data.java


public class Data {

    private int x, y = 0;


    public Data(int x, int y) {

this.x = x;

this.y = y;

    }


    public int getX() {

        return x;

    }


    public int getY() {

        return y;

    }

}



# Plus.java


public class Plus implements ICalc {


    @Override

    public void calc(Data data) {

int x = data.getX();

int y = data.getY();

System.out.println("plus: " + (x + y));

    }

}



# Minus.java


public class Minus implements ICalc {


    @Override

    public void calc(Data data) {

int x = data.getX();

int y = data.getY();

System.out.println("minus: " + (x - y));

    }

}




# Multiply.java


public class Multiply implements ICalc {


    @Override

    public void calc(Data data) {

int x = data.getX();

int y = data.getY();

System.out.println("multiply: " + (x * y));

    }

}



# CalcManager.java


import java.util.ArrayList;


public class CalcManager {

    private ArrayList<ICalc> calcs = new ArrayList<>();

    

    public void execute(Data data) {

System.out.println("x: " + data.getX());

System.out.println("y: " + data.getY());

System.out.println("==========");

for (ICalc calc : calcs) {

   calc.calc(data);

}

    }

    

    public void add(ICalc calc) {

if (!calcs.contains(calc)) {

   calcs.add(calc);

}

    }

}



# Main.java


public class Main {

    public static void main(String[] args) {

Data data = new Data(3, 4);


CalcManager cm = new CalcManager();

cm.add(new Plus());

cm.add(new Minus());

cm.add(new Multiply());

cm.execute(data);

    }

}



# 결과


x: 3

y: 4

==========

plus: 7

minus: -1

multiply: 12


댓글
댓글쓰기 폼
공지사항
Total
395,135
Today
3
Yesterday
41
«   2018/11   »
        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  
글 보관함