11 Ağustos 2022 Perşembe

GoF - Strategy Örüntüsü - Functional Java

Giriş
Strategy arayüzü yerine Functional Programming'den gelen closure da kullanılabilir. Açıklaması şöyle.
Some patterns became anti-pattern or irrelevant (e.g. the strategy pattern lost all value after Java 8 due to the Supplier interface)
Ancak arada önemli bir fark var. Strategy arayüzü tek bir metoddan ibaret olmayabilir. Bu durumda closure yetersiz kalıyor.

Örnek - Sadece Consumer
Şöyle yaparız
private HashMap<String, Consumer> map = new HashMap<>();

public Demo() {
  map.put("csv", response -> doDownloadCsv());
  map.put("excel", response -> doDownloadExcel());
  map.put("txt", response -> doDownloadTxt());
}

@GetMapping("/exportOrderRecords")
public void downloadFile(User user, HttpServletResponse response) {

  String fileType = user.getFileType();
  Consumer consumer = map.get(fileType);
  if (consumer != null) {
    consumer.accept(response);
  } else {
    doDownloadCsv();
  }
}
Örnek - 
Şöyle yaparız
interface Picker<T> {
  T pick(CameraControls settings, LightMeter meter);
}

@lombok.Getter
@lombok.RequiredArgsConstructor
enum Mode {

    MANUAL(Picker::apertureFixed, Picker::shutterFixed),
    APERTURE_PRIORITY(Picker::apertureFixed, Picker::pickShutter),
    SHUTTER_PRIORITY(Picker::pickAperture, Picker::shutterFixed);

    private final Picker<Aperture> aperturePicker;
    private final Picker<Shutter> shutterPicker;
}

@lombok.Value
class CameraControls {

    Mode mode;

     Aperture pickAperture(LightMeter meter) {
        return mode.getAperturePicker().pick(...);
    }

    Shutter pickShutter(LightMeter meter) {
        return mode.getShutterPicker().pick(...);
    }
}

Hiç yorum yok:

Yorum Gönder