Algorithm switching pattern
</ font>
The sample code is Compare two class instances A class that returns the comparison result as an int value Create with Strategy inheritance class
I haven't switched the algorithm The int value of the return value is expressed as an algorithm
Check with the following class structure
class | Explanation |
---|---|
interface Strategy | Define switching algorithm methods Method is sam.Compares two instances of class and returns the comparison result as an int value |
compare.class | Implement Strategy |
useStrategy.class | Used by user to execute switching algorithm |
sam.class | Target class to be compared |
user(Main.class) | Operation check |
interface_Strategy
interface Strategy{int compare(sam s1,sam s2);}
compare.class
class compare implements Strategy{
public int compare(sam s1,sam s2){
if(s1.i < s2.i){return 1;}else
if(s1.i == s2.i){return 0;}else{
return -1;
}
}
}
useStrategy.class
class useStrategy{
Strategy strategy = null;
useStrategy(Strategy st) {this.strategy=st;}
int compare(sam s1,sam s2){return strategy.compare(s1,s2);}
}
sam.class
class sam{
String str;
int i;
sam(String str,int i){
this.str = str;
this.i = i;
}
}
user(Main.class)
public static void main(String[] args){
sam sam1 = new sam("s1",3);
sam sam2 = new sam("s2",2);
compare com = new compare();
useStrategy us = new useStrategy(com);
System.out.println(us.compare(sam1,sam2));
}}
Recommended Posts