4

私のコードスニペットは次のとおりです。

public void execute(Parameters params) {
    Long requestType = params.getRequestType();
    // Based on the requestType the name of the project would be different
    getName(requestType); 
    // Same as above
    getDescription(requestType) 
    // Project here is a collection of different requests
    Long projectId = createProject(name, description) 
    RequestContents requestContents = params.getRequestContents();
    for(RequestContent requestcontent : requestcontents) {
        Long requestId = createRequest(name, description, projectId);
        updateRequest(requestId, requestContent1);
    }
    // Based on the  requestType, mail content would differ 
    String mailContent = getMailContent(requestType, projectId) 
    sendMail(mailContent); 
}

sendMail関数、createProject、の出力はにcreateRequest依存するrequestTypeため、これらの関数は複数のif-else条件を持つことになります。これを避けるために、このクラスをモデル化する正しい方法は何ですか?

4

4 に答える 4

3

1つの方法は、AbstractRequest抽象メソッドなどを持つ抽象クラスを作成し、それぞれが異なる実装を持ついくつかの具体的なサブクラスなどを持つ ことです。彼らはそれを戦略パターンと呼んでいると思います。sendMailcreateProjectRequestType1 RequestType2sendMail

于 2012-11-04T17:12:20.880 に答える
1

二重ディスパッチを使用:

public class Sender {

    public void sendMail(RequestType1 requestType, String mailContent) {
        // some impl
    }
    public void sendMail(RequestType2 requestType, String mailContent) {
        // some impl
    }
    public void sendMail(RequestType3 requestType, String mailContent) {
        // some impl
    }
}

それから

sender.sendMail(requestType, mailContent);

呼び出される実際のメソッドは、オブジェクトのタイプに基づいて実行時に決定されますrequestType。見えない「もし」ではありません。


これらのメソッドを単純にローカルに実装することもできますが、それは混乱を招き、読みにくくなります。この懸念を別のクラスに分割することをお勧めします。

于 2012-11-04T17:12:47.057 に答える
0

requestType が文字列値の有限セットである場合、それに対応する Enum を作成できます。

enum RequestType{
    type1,type2,...;
}

次に、if-else をよりコンパクトな switch-case に変換できます。

switch (RequestType.valueOf(requestType)){
    case type1:
        ....
    break;
    case type2:
        ...
    break;
    ...
    default:
}

コードから、requestType は long であり、直接切り替えることができます。

switch (requestType){
    case type1:
        ....
    break;
    case type2:
        ...
    break;
    ...
    default:
}
于 2012-11-04T17:14:06.560 に答える
0

なぜ if-else 条件を execute() メソッド自体に入れ、それに基づいて他のメソッドを呼び出し、関連するパラメーターを渡さないのですか。このようにして、sendmail、createproject、createrequest の汎用関数を作成します。

于 2012-11-04T17:14:35.753 に答える