【问题标题】:Strategy pattern with return value带返回值的策略模式
【发布时间】:2018-02-28 10:50:51
【问题描述】:
我尝试按策略模式创建付款。但是我读过的所有文章都是这样的:
public interface PayStrategy {
void pay(BigDecimal paymentAmount);
}
但是如果我需要返回Single<RestResponse<PaymentResponse>>?这是正确的方法吗?
public interface PayStrategy {
Single<RestResponse<PaymentResponse>> pay(BigDecimal paymentAmount);
}
在任何真实系统中,支付请求都会返回结果
【问题讨论】:
标签:
java
android
design-patterns
strategy-pattern
【解决方案1】:
我会建议你在通用返回类型中实现你的问题陈述,如下所示:
public interface IPayStrategy<T> {
T Pay();
}
public class PayStrategy1 :IPayStrategy<int> {
public int Pay() { }
}
public class PayStrategy2 :IPayStrategy<String> {
public String Pay() { .. }
}
public class Context<T> {
private IPayStrategy<T> payStrategy;
public setStrategy(IPayStrategy<T> strategy) { this.payStrategy = strategy; }
public T doPayment() {
return payStrategy.Pay();
}
}
【解决方案2】:
在我看来这是正确的,因为合同的定义取决于您,如果您同意所有策略必须返回类型为 Single<RestResponse<PaymentResponse>> 的结果,对我来说这是正确的