티스토리 뷰

Java

Strategy Pattern

techbard 2016.07.20 19:24

Strategy.zip



# ICalcStrategy.java


public interface ICalcStrategy {

    

    int calc(Data data);


}



# Data.java


public class Data {

    private int x, y;

    private ICalcStrategy iCalcStrategy;


    public Data(int x, int y, ICalcStrategy iCalcStrategy) {

this.x = x;

this.y = y;

this.iCalcStrategy = iCalcStrategy;

    }

    

    public int calc() {

return iCalcStrategy.calc(this);

    }


    public int getX() {

        return this.x;

    }


    public int getY() {

        return this.y;

    }

}



# CalcPlus.java


public class CalcPlus implements ICalcStrategy {


    @Override

    public int calc(Data data) {

return data.getX() + data.getY();

    }

}



# CalcMultiply.java


public class CalcMultiply implements ICalcStrategy {


    @Override

    public int calc(Data data) {

return data.getX() * data.getY();

    }

}



# CalcMinus.java


public class CalcMinus implements ICalcStrategy {


    @Override

    public int calc(Data data) {

return data.getX() - data.getY();

    }

}



# Main.java


public class Main {


    public static void main(String[] args) {


Data dataPlus = new Data(1, 2, new CalcPlus());

Data dataMultiply = new Data(3, 4, new CalcMultiply());

Data dataMinus = new Data(1, 2, new CalcMinus());


System.out.println(dataPlus.getX() + " plus " + 

dataPlus.getY() + " is " + dataPlus.calc());

System.out.println(dataMultiply.getX() + " multiply " + 

dataMultiply.getY() + " is " + dataMultiply.calc());

System.out.println(dataMinus.getX() + " minus " + 

dataMinus.getY() + " is " + dataMinus.calc());

    }

}



# 결과


Plus: 3

Multiply: 2

Minus: -1



댓글
댓글쓰기 폼
공지사항
Total
394,932
Today
3
Yesterday
28
«   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  
글 보관함