# Strategy

January 3, 2022

``````class SortedIntegers {
private List<Integer> integers = new ArrayList<>();

// 只是插入排序
for(var i = 0; i < integers.size(); i++) {
var to = insertTo(i);
if(to != -1) {
}
}
}

private int insertTo(Integer elemIdx) {
var elem = integers.get(elemIdx);
for(var i = 0; i < elemIdx; i++) {
if(integers.get(i) > elem) {
return i;
}
}
return -1;
}

List<Integer> integers() {
return integers;
}
}

public class Main {
public static void main(String[] args) {
var integers = Arrays.asList(10, 9, 1, 2, 5, 3, 8, 7);
var sorted = new SortedIntegers();
for(var integer : integers) {
}
// [1, 2, 3, 5, 7, 8, 9, 10]
out.println(sorted.integers());
}
}
``````

## 排序的策略

``````    ...
for(var i = 0; i < integers.size(); i++) {
var to = insertToDescending(i);
if(to != -1) {
}
}
}

private int insertToDescending(Integer elemIdx) {
var elem = integers.get(elemIdx);
for(var i = 0; i < elemIdx; i++) {
if(integers.get(i) < elem) {
return i;
}
}
return -1;
}
...
``````

``````package cc.openhome;

import java.util.*;

interface IntegerComparator {
int compare(Integer i, Integer j);
}

class SortedIntegers {
private List<Integer> integers = new ArrayList<>();
private IntegerComparator comparator;

SortedIntegers(IntegerComparator comparator) {
this.comparator = comparator;
}

...

private int insertTo(Integer elemIdx) {
var elem = integers.get(elemIdx);
for(var i = 0; i < elemIdx; i++) {
// 透過 comparator 比較
if(comparator.compare(integers.get(i), elem) > 0) {
return i;
}
}
return -1;
}

List<Integer> integers() {
return integers;
}
}

public class Main {
public static void main(String[] args) {
var integers = Arrays.asList(10, 9, 1, 2, 5, 3, 8, 7);
// 指定 Comparator 作為排序策略
var sorted = new SortedIntegers((i, j) -> i - j);
for(var integer : integers) {
}
System.out.println(sorted.integers());
}
}
``````

## 可抽換的演算策略

Strategy 模式的名稱，代表該模式的成形過程，來自於觀察到演算流程中，可區分不變的演算樣版，以及會變動的特定演算。