引言
在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
--菜鸟教程定义
理解:看完上面这段话其实还是有点迷糊的,说白了,策略模式就是面向对象中一种多态的表现。把代码灵活化,优雅吧。
不知道是不是因为我没理解,我感觉没啥写的,主要还是灵活运用,根据实际场景设计,
作用我认为就是,把一个个算法看作单独的,封装起来,可以自由替换到代码中去,
贴代码吧。。。
Main.java
public class Main {
public static void main(String[] args) {
//定义两种类的对象,分别实现Comparable 和 Comparator
//Comparable
Cat[] cats = new Cat[]{new Cat(10,10),new Cat(5,5),new Cat(12,12)};
//Comparator,需要自定义比较器,然后排序的时候把比较器也传过去,也就是策略模式
Dog[] dogs = new Dog[]{new Dog(10),new Dog(5),new Dog(12)};
Sorter1.sort1(cats);
Sorter2<Dog> sorter2 = new Sorter2();
sorter2.sort2(dogs,new DogComparator());
Arrays.asList(cats).forEach(System.out::println);
Arrays.asList(dogs).forEach(System.out::println);
}
}
public class Dog {
int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Dog(int price) {
this.price = price;
}
@Override
public String toString() {
return "Cat2{" +
"price=" + price +
'}';
}
}
public class DogComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
if(o1.price>o2.price) {
return -1;
}else if(o1.price<o2.price){
return 1;
}else {
return 0;
}
}
}
public class Sorter2<T> {
public void sort2(T[] arr,Comparator<T> comparator){
for (int i = 0; i < arr.length; i++) {
int minPos = i;
for (int j = 0; j < arr.length; j++) {
minPos = comparator.compare(arr[j],arr[minPos]) == -1 ? j : minPos;
}
swap(arr,i,minPos);
}
}
void swap(T[] arr, int i, int j){
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public interface Comparator<T> {
int compare(T t, T t1);
}
public interface Comparable<T> {
int compareTo(T o );
}
public class Cat implements Comparable<Cat>{
int weigh,height;
public Cat(int weigh, int height){
this.weigh = weigh;
this.height = height;
}
@Override
public String toString() {
return "Cat{" +
"weigh=" + weigh +
", height=" + height +
'}';
}
@Override
public int compareTo(Cat o) {
if(this.weigh>o.weigh) {
return -1;
}else if(this.weigh<o.weigh){
return 1;
}else {
return 0;
}
}
}
public class Sorter1 {
public static void sort1(Comparable[] arr){
for (int i = 0; i < arr.length; i++) {
int minPos = i;
for (int j = 0; j < arr.length; j++) {
minPos = arr[j].compareTo(arr[minPos]) < 0 ? j : minPos;
}
swap(arr,i,minPos);
}
}
static void swap(Comparable[] arr,int i ,int j){
Comparable temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}