后端小树林数据结构和算法

策略模式

2019-01-03  本文已影响0人  奔跑的蛙牛

在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
策略模式中专门有一个对象封装算法,以便于在运行时调用不通算法
实现一个策略模式

  1. 对一组对象按照其相关字段进行排序
  2. 排序采用简单的插入排序
  3. 封装一个transtion对象去实现排序规则算法(仔细看transtion封装的代码)
package com.snail.basic;

import java.util.Comparator;

public class Insertion {
    public static void sort(Object[] a, Comparator c){
        int N = a.length;
        for (int i = 1; i < N; i++) {
            for (int j = i; j >0 && less(c,a[j],a[j-1]); j--) {
                exch(a,j,j-1);
            }
        }
    }
    public static boolean less(Comparator c,Object v,Object w){
        return c.compare(v,w)<0;
    }
    public static void exch(Object[] a,int i,int j){
        Object t = a[i];
        a[i]=a[j];
        a[j]=t;
    }
    public static void main(String[] args) {
        // 随意几个对象 包含who when amount 等字段,按照不同字段排序
        Object[] a = new Object[5];
        Insertion.sort(a,new Transaction.WhoOrder());
        Insertion.sort(a,new Transaction.WnenOrder());
        Insertion.sort(a,new Transaction.HowMuchOrder());

    }
}
package com.snail.basic;

import java.util.Comparator;
import java.util.Date;

public class Transaction {
    private final String who = null;
    private final Date when = null;
    private final double amount = 0.0;
    public static class WhoOrder implements Comparator<Transaction>{
        @Override
        public int compare(Transaction v, Transaction w) {
            return v.who.compareTo(w.who);
        }
    }
    public static class WnenOrder implements Comparator<Transaction>{
        @Override
        public int compare(Transaction v, Transaction w) {
            return v.when.compareTo(w.when);
        }
    }
    public static class HowMuchOrder implements Comparator<Transaction>{
        @Override
        public int compare(Transaction v, Transaction w) {
            if(v.amount < w.amount) return -1;
            if(v.amount > w.amount) return +1;
            return 0;
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读