問題

我的服務實現如下: –

 package Java8.controller;

import java.util.function.Function;

public class ServiceImpl implements ITicket {

    Function<Integer,Double> ticketCal;

    public ServiceImpl(Function<Integer,Double> ticketCal){
        this.ticketCal= ticketCal;
    }

    @Override
    public double calculateFare(int quantity) {
        return ticketCal.apply(quantity);
    }

}

 

以下是我建立的戰略: –

回收機票戰略:-

 package Java8.controller;

import java.util.function.Function;

public interface ReclinerTicketStrategy {

    default Function<Integer,Double> reclinerTicketStrategy(){

        return (noOfTickets)->{
            return noOfTickets * 200.00;
        };
    }
}

 

貴賓機票戰略:-

 package Java8.controller;

import java.util.function.Function;

public interface VipTicketStrategy {

    default Function<Integer,Double> vipTicketStrategy(){

         return (noOfTickets)->{
             return noOfTickets*400.00;
        };

    }
}

 

以下是使用策略的主類: –

 package Java8.controller;

public class Main implements ReclinerTicketStrategy {

    public Main(){

        ITicket ticketsVip = new ServiceImpl(reclinerTicketStrategy());
        System.out.println(ticketsVip.calculateFare(5));

}

    public static void main(String args[]){
        Main main = new Main();
    }


}


 

我的問題是這是否是將戰略函式作為預設方法放在介面中的正確方法?或者有更好的方法嗎?

  最佳答案

戰略應該實現服務所需的抽象.在這種情況下,服務需要Function<Integer,Double>,所以戰略將是...

 class ReclinerTicketStrategy implements Function<Integer,Double> {
    @Override
    public Double apply(Integer noOfTickets) {
        return noOfTickets * 200.0;
    }
}
 

然後將服務例項化為,
2001年12月31日終了的兩年期收入和支出及準備金和基金結餘變動報表 ITicket reclinerTicket = new ServiceImpl(new ReclinerTicketStrategy());

當然,如果你不需要重用策略,那麼lambda就足夠了。
2001年12月31日終了的兩年期收入和支出及準備金和基金結餘變動報表 ITicket reclinerTicket = new ServiceImpl(noOfTickets -> noOfTickets * 200.0);

  相同標籤的其他問題

javadesign-patternsjava-8functional-programming