0

この基本的な質問に対処してください。

私はabstract class C1別のもの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には抽象メソッドが含まれていますC21とC22の呼び出し元は異なりますが、これらのクラスのgetCaller();メソッドにのみ渡されるパラメーターによって識別できます。start(p1,p2)

start(p1,p2)両方のクラスで同様のことを行います。C21とC22の唯一の違いは、実装getCaller()が固定されており、とにかくstartのパラメーターから抽出できることです。そこで、C21とC22の代わりに単一のクラスを作成することにしました。

そのように作成することはできません。メソッドのパラメーターを入力して(から呼び出される)で返すことができる抽象変数とプライベート変数setCaller()を作成したかったのです。final methodcallerclass C1startgetCaller()abstract class C0

これは正しいアプローチですか?これのためのより良い方法やパターンはありますか?

4

1 に答える 1

1

C21とC22の唯一の違いは、getCaller()の実装です。これは固定されており、startのパラメーターからとにかく抽出できます。

変更する必要があるのは1つのメソッドだけなので、抽象ととのペアではC1なく、単一の非抽象実装を使用する方が適切です。あなたはこのようなことをすることができます:C1C21C22

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

public Caller getCaller() {
    return caller;
}

に加えて継承する他のクラスがある場合はC21C22抽象を保持し、上記の実装で非抽象を追加するC1ことをお勧めします。C1C2

于 2013-02-03T13:55:38.140 に答える