Programming

많은 'if else'문을보다 깔끔한 방법으로 변환

procodes 2020. 7. 28. 22:06
반응형

많은 'if else'문을보다 깔끔한 방법으로 변환


이 질문에는 이미 답변이 있습니다.

내 코드

mimeType

는가 어떤

MIME

유형과 같은지 감지합니다.있는 경우 특정 변환을 수행합니다.

public void convertToMp3(File src, File target,String mimeType){
    if(mimeType.equals("audio/mpeg")){
        ...
    }else if(mimeType.equals("audio/wav")){
        mp3ToWav();
    }else if(mimeType.equals("audio/ogg")){
        ...
    }else if(...){
    ... //More if and else here
}

 

다른 if

이 많기 때문에 코드를 줄였습니다. 많은

if

else

또는

else if

을 제거하는 데 적합한 디자인 패턴은 무엇입니까 ?


 

Converter

인터페이스를 가질 수 있습니다 . 그런 다음 다음과 같이 각 Mimetype에 대한 클래스를 만들 수 있습니다.

public interface Converter {

    public void convertToMp3();
    public void convertToOgg();

}

public class MpegConverter implements Converter {

    public void convertToMp3() {
        //Code here
    }

    public void convertToOgg() {
        //Code here
    }

}

각 변환기마다 이와 같은 클래스가 필요합니다. 그런 다음 다음과 같이 맵을 설정할 수 있습니다.

Map<String, Converter> mimeTypeMap = new HashMap<String, Converter>();

mimeTypeMap.put("audio/mpeg", new MpegConverter());

그런 다음

convertToMp3

방법이 다음 과 같이됩니다.

Converter converter = mimeTypeMap.get(mimeType);
converter.convertToMp3();

이 방법을 사용하면 나중에 다른 변환기를 쉽게 추가 할 수 있습니다.테스트되지 않은, 아마 컴파일되지는 않지만 아이디어를 얻습니다.


JDK7 이전을 사용하는 경우 모든

MIME

유형에 대해 열거 형을 추가 할 수 있습니다 .

  public static enum MimeTypes {
      MP3, WAV, OGG
  }

  public class Stuff {
      ...
      switch (MimeTypes.valueOf(mimeType)) {
          case MP3: handleMP3(); break;
          case WAV: handleWAV(); break;
          case OGG: handleOGG(); break;
      }
  }

그리고 스택 오버플로 질문을 살펴 가지고

변환 문자열 열거 형 - 자바

열거로 문자열을 변환하는 방법에 있습니다.


전략 디자인 패턴과 a

Map

를 사용하여 적절한 전략으로 전달하십시오. 특정에 대한 변환 외에 추가 기능이 필요

mimeType

하거나 변환기가 크고 복잡한 코드이고 각 변환기를 자체

.java

파일 에 배치하려는 경우에 특히 유용 합니다.

 interface Convertor {
    void convert(File src, File target);
 }

 private static void convertWav(File src, File target) {
    ...
 }

 ...

 private static final Map< String, Convertor > convertors = new ...;
 static {
    convertors.put("audio/wav", new Convertor {
       void convert(File src, File target) {
          convertWav(src, target);
       }
    });
    convertors.put("audio/ogg", new Convertor {
       void convert(File src, File target) {
          convertOgg(src, target);
       }
    });
    ...
 }

 public void convertToMp3(File src, File target, String mimeType){
     final Convertor convertor = convertors.get(mimeType);
     if (convertor == null ) {
        ...
     } else {
        convertor.convert(src, target);
     }
 }

 

각 경우에 대해 동일한 방법을

실행하는 경우 상태 패턴을 확인해야합니다


If you are using JDK 7, you can use switch-case construct:

See: Why can't I switch on a String?

For prior versions, if-else is the only choice.


It's definitely a Strategy design pattern. But you have a big problem in your general design. It's not a good programming habit to use String to identify a type. Simply because it's easily editable and you can make a grammar mistake and spend all the afternoon looking for a programming mistake. You can avoid using map<>.

I suggest the following:

  1. Extend class File. The new class adds a new attribute FileType and a new method convertTo(FileType) to class File. This attribute holds its type: “audio” , “wav”... and again don't use String, Use Enum. In this case I called it FileType. Extend File as much as you want: WavFile, AudioFile...
  2. Use a Strategy dp to create your converters.
  3. Use a Factory dp to initialize the converters.
  4. Since every File knows its own type and the target type (use convertTo() method to specify the target type) it will call the factory to get the correct Converter automatically!!!

This design is scalable and you can add as much as you need FileType and converters. The answer you vote for is misleading!!!! There is a big difference between coding and hacking.


If you are not using Java 7 you could create an enum and use that value with a switch case. You then only need to pass the enum value (rather than a file, I don't why you are doing that). It would look neater too.

These should help with what you want to do:

 [Java Enum Examples][1] - 
 [Java Switch Case examples][2]

참고URL : https://stackoverflow.com/questions/14136721/converting-many-if-else-statements-to-a-cleaner-approach

반응형