-
Notifications
You must be signed in to change notification settings - Fork 2
/
StrategyPattern.java
117 lines (94 loc) · 2.41 KB
/
StrategyPattern.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.util.Arrays;
/*
* This program is an example of the use of the Strategy design pattern.
* Strategy allows to define different operation implementations for different
* situations. In the example we want to sort arrays, but want to choose the
* algorithm depending on its size.
*/
/*
* This is the main class of the program. It uses the Sorter client.
*/
public class StrategyPattern {
public static void main(String args []) {
int[] test1 = {9,8,7,6,5,4,3,2,1,0};
int[] test2 = new int[200];
for (int i=0; i<test2.length; i++)
test2[i] = 200-i;
Sorter sorter = new Sorter();
sorter.setStrategy(new BubbleSortStrategy());
sorter.sort(test1);
System.out.println("test1: ");
printArray(test1);
sorter.setStrategy(new MergeSortStrategy());
sorter.sort(test2);
System.out.println("test2: ");
printArray(test2);
}
public static void printArray(int[] array) {
String output = "";
for (int i=0; i<array.length; i++)
output += " "+array[i]+" ";
System.out.println(output);
}
}
/*
* This interface generalizes the Strategies for different logics
*/
interface SortStrategy {
public void sort(int[] array);
}
/*
* Strategy that implements bubblesort. Thought for small datasets.
*/
class BubbleSortStrategy implements SortStrategy {
@Override
public void sort(int[] array) {
// int lowestIndex;
// for (int i=0; i<array.length; i++) {
// lowestIndex = i;
// for (int j=0; j<array.length; j++) {
// if (array[j] < array[lowestIndex]) {
// lowestIndex = j;
// int aux = array[i];
// array[i] = array[lowestIndex];
// array[j] = aux;
// }
// }
// }
//int[] sorted2 = sorter.sort(test2);
int n = array.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(array[j-1] > array[j]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
}
/*
* Strategy that implements mergesort (from the Collections utility). Thought
* for big datasets.
*/
class MergeSortStrategy implements SortStrategy {
@Override
public void sort(int[] array) {
Arrays.sort(array);
}
}
/*
* This class represents the client that uses the strategies accordingly to the
* situation
*/
class Sorter {
SortStrategy strategy;
public void sort(int[] array) {
strategy.sort(array);
}
public void setStrategy(SortStrategy strategy) {
this.strategy = strategy;
}
}