All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dakusui.printables.PrintableConsumer Maven / Gradle / Ivy

There is a newer version: 6.0.1
Show newest version
package com.github.dakusui.printables;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public class PrintableConsumer implements Consumer {
  private final Consumer consumer;
  private final Supplier    formatter;

  public PrintableConsumer(Supplier formatter, Consumer consumer) {
    this.consumer = requireNonNull(consumer);
    this.formatter = requireNonNull(formatter);
  }

  @Override
  public void accept(T t) {
    consumer.accept(t);
  }

  public Consumer andThen(Consumer after) {
    Objects.requireNonNull(after);
    return createConsumer(
        () -> format("%s;%s", formatter.get(), after),
        (T t) -> {
          accept(t);
          after.accept(t);
        }
    );
  }

  @Override
  public String toString() {
    return formatter.get();
  }

  protected PrintableConsumer createConsumer(Supplier formatter, Consumer consumer) {
    return new PrintableConsumer<>(formatter, consumer);
  }

  public static class Builder {

    private final Consumer consumer;

    public Builder(Consumer predicate) {
      this.consumer = requireNonNull(predicate);
    }

    public Consumer describe(Supplier formatter) {
      return new PrintableConsumer<>(requireNonNull(formatter), consumer);
    }

    public Consumer describe(String description) {
      return describe(() -> description);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy