001/*******************************************************************************
002 * This software is provided as a supplement to the authors' textbooks on digital
003 * image processing published by Springer-Verlag in various languages and editions.
004 * Permission to use and distribute this software is granted under the BSD 2-Clause
005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause).
006 * Copyright (c) 2006-2023 Wilhelm Burger, Mark J. Burge. All rights reserved.
007 * Visit https://imagingbook.com for additional details.
008 ******************************************************************************/
009package imagingbook.common.util;
010
011import java.io.ByteArrayOutputStream;
012import java.io.PrintStream;
013
014/**
015 * <p>
016 * Classes which require a complex {@code toString()} method should implement this interface, which requires the single
017 * method {@link #printToStream(PrintStream)}, e.g.,
018 * </p>
019 * <pre>
020 * public void printToStream(PrintStream strm) {
021 *     strm.format("...", ...);
022 * }
023 * </pre>
024 * <p>
025 * Note that this interface cannot override the default {@link Object#toString()} method directly. If needed, this
026 * should be done in the implementing class by using the pre-defined {@link #printToString()} method:
027 * </p>
028 * <pre>
029 * public String toString() {
030 *      return printToString();
031 * }
032 * </pre>
033 *
034 * @author WB
035 * @version 2021/09/17
036 */
037public interface PrintsToStream {
038        
039        /**
040         * This method writes a description of this object to the specified
041         * {@link PrintStream}.
042         * 
043         * @param strm the output stream to print to
044         */
045        public void printToStream(PrintStream strm);
046
047        /**
048         * Convenience method to save some boilerplate code. Calls {@link #printToStream(PrintStream)} to produce a
049         * description string for this object. The {@link #printToString()} method can also be used by implementing classes
050         * to override the standard {@link Object#toString()} method, e.g.,
051         * <pre>
052         * &#64;Override
053         * public String toString() {
054         *      return this.printToString();
055         * }
056         * </pre>
057         *
058         * @return the string representation of this object as defined by {@link #printToStream(PrintStream)}
059         */
060        public default String printToString() {
061                ByteArrayOutputStream bas = new ByteArrayOutputStream();
062                try (PrintStream strm = new PrintStream(bas)) {
063                        this.printToStream(strm);
064                }
065                return bas.toString();
066        }
067
068}