可以返回实现类实例的策略接口

时间:2018-01-15 19:34:51

标签: java

我有一个这种类型的

@Value(staticConstructor="of")
public class PolicyOne {

    public static Policy of (String scope ) {
        return PolicyOne(scope);
    }

    private final String scope;
}

可以创建像PolicyOne.of(“hello”)

这样的实例

我正在尝试实施战略设计模式。

如何在策略接口中为“of()”方法定义等效的抽象方法,以便在我将接口实现(PolicyOne或PolicyTwo)传递给另一个类时,它可以调用policyStrategy.of(“someValue” )

public interface PolicyStrategy {

      // what should be the method signature for “of” method?
      // return type needs be of the implementation class type

}

这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

如果实现类仅根据给定的“范围”字符串确定,using enums as factories将很好地解决您的问题。单击此linkIn文章可获得此问题的全面解决方案。但是,我已经摘录并将此解决方案应用于您的问题:

public class ReallyGreatPolicy implements Policy {}
public class TotalRipoffPolicy implements Policy {}

public enum PolicyType {
    ReallyGreat {
        @Override
        Policy createPolicy() {
            return new ReallyGreatPolicy();
        }
    } ,
    TotalRipoff {
        @Override
        Policy createPolicy() {
            return new TotalRipoffPolicy();
        }
    },
    ;
    abstract Policy createPolicy();

    public static Policy of (String scope ) {
        return PolicyFactory.valueOf(scope).createPolicy();
    }
}