策略模式

master
terry 3 years ago
parent bf4fe52eb3
commit 7167eb5b1e

@ -5,7 +5,7 @@ package singleton;
* , * ,
* */ * */
public class Singleton6 { public class Singleton6 {
private static Singleton6 INSTANCE; private static volatile Singleton6 INSTANCE;
private Singleton6() { private Singleton6() {
} }

@ -0,0 +1,26 @@
package strategy;
public class Cat implements Comparable<Cat>{
private int weight;
private int height;
public Cat(int weight, int height) {
this.weight = weight;
this.height = height;
}
@Override
public String toString() {
return "Cat{" +
"weight=" + weight +
", height=" + height +
'}';
}
@Override
public int compareTo(Cat c) {
if(this.weight < c.weight) return -1;
else if(this.weight > c.weight) return 1;
else return 0;
}
}

@ -0,0 +1,8 @@
package strategy;
public class CatHeightComparator implements Comparator<Cat>{
@Override
public int compareTo(Cat t1, Cat t2) {
return 0;
}
}

@ -0,0 +1,8 @@
package strategy;
public class CatWeightComparator implements Comparator<Cat>{
@Override
public int compareTo(Cat t1, Cat t2) {
return 0;
}
}

@ -0,0 +1,5 @@
package strategy;
public interface Comparator<T> {
int compareTo(T t1, T t2);
}

@ -0,0 +1,23 @@
package strategy;
public class Dog implements Comparable<Dog>{
int food;
public Dog(int food) {
this.food = food;
}
@Override
public String toString() {
return "Dog{" +
"food=" + food +
'}';
}
@Override
public int compareTo(Dog d) {
if(this.food < d.food) return -1;
else if(this.food > d.food) return 1;
else return 0;
}
}

@ -0,0 +1,10 @@
package strategy;
public class DogComparator implements Comparator<Dog>{
@Override
public int compareTo(Dog d1, Dog d2) {
if(d1.food < d2.food) return -1;
else if(d1.food > d2.food) return 1;
else return 0;
}
}

@ -0,0 +1,29 @@
package strategy;
import java.util.Arrays;
public class Sorter<T> {
public void sort(T[] arr, Comparator<T> comparator){
for (int i = 0; i < arr.length - 1; i++) {
int minPos = i;
for (int j = i+1; j < arr.length; j++) {
minPos = comparator.compareTo(arr[j], arr[minPos]) == -1 ? j : minPos;
}
swap(arr, i, minPos);
}
}
private void swap(T[] arr, int i, int minPos) {
T temp = arr[i];
arr[i] = arr[minPos];
arr[minPos] = temp;
}
public static void main(String[] args) {
Dog[] dogs = new Dog[]{new Dog(5), new Dog(1), new Dog(6)};
Cat[] cats = new Cat[]{new Cat(6,2), new Cat(3,4), new Cat(5,5)};
Sorter<Dog> sorter = new Sorter<>();
sorter.sort(dogs, new DogComparator());
System.out.println(Arrays.toString(dogs));
}
}
Loading…
Cancel
Save