0

请处理这个基本问题。

我有一个abstract class C1which 扩展了另一个abstract class C0并被多个扩展sub-classes (C21 and C22)

@Component
public abstract class C0 {
    protected abstract String getCaller();  
//Some other methods.
}

.

public abstract class C1 extends C0 {
//Set of methods which are used by children and then calls methods of C0 which then use getCaller();
}

.

    @Controller
    public class C21 extends C1 {

    @RequestMapping(value = "abc", method = RequestMethod.GET)
    public String start(@RequestParam(value = "kw", required = true) String p1,
            @RequestParam(value = Constant.REQUEST_PARAM_KEYWORDID, required = true) long p2) throws Exception {
//Some processing and calls controllers defined in abstract class C1
        return "200";
    }


    @Override
    protected String getCaller() {
        return "C21";
    }

}

.

@Controller
public class C22 extends C1 {

    @RequestMapping(value = "abc", method = RequestMethod.GET)
    public String start(@RequestParam(value = "kw", required = true) String p1,
            @RequestParam(value = Constant.REQUEST_PARAM_KEYWORDID, required = true) long p2) throws Exception {
//Some processing and calls controllers defined in abstract class C1
        return "200";
    }


    @Override
    protected String getCaller() {
        return "C22";
    }

}

C0 包含一个抽象方法getCaller();C21 和 C22 的调用者是不同的,但它们可以通过传递给start(p1,p2)这些类的唯一方法的参数来识别。

start(p1,p2)在两个课程中都做类似的事情。C21 和 C22 的唯一区别是其实现getCaller()是固定的,并且无论如何都可以从 start 的参数中提取。所以,我决定创建单个类而不是 C21 和 C22。

我不能这样创建setCaller(),我想在抽象中创建final method一个私有变量,它可以用方法的参数填充并返回(从 调用)。callerclass C1startgetCaller()abstract class C0

这是正确的方法吗?有没有更好的方法或模式呢?

4

1 回答 1

1

Only difference in C21 and C22 is the implementation of getCaller() which is fixed and can anyways be extracted from parameters of start.

Since you have to change only a single method, you will be better off with a single non-abstract implementation C1 instead of an abstract C1 and a pair of C21 and C22. You can do something like this:

Caller caller;
public start(SomeType1 p1, SomeType2 p2, SomeType3 p3) {
    caller = new Caller(p1, p2, p3);
    ...
    // Do other stuff
}

public Caller getCaller() {
    return caller;
}

In case there are other classes in addition to C21 and C22 inheriting C1, you may want to keep your C1 abstract, and add a non-abstract C2 with an above implementation.

于 2013-02-03T13:55:38.140 回答