java/RAII/src/cz/frantovo/priklady/raii/Zdroj.java
author František Kučera <franta-hg@frantovo.cz>
Fri, 15 May 2020 20:32:37 +0200
changeset 59 d6614ad97bed
parent 25 95be94124ce9
permissions -rw-r--r--
LV2: modul zesilovače, dle oficiálního příkladu, ale bez závislosti na Pythonu – stačí gcc a make
     1 /**
     2  * RAII v Javě
     3  * Copyright © 2014 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package cz.frantovo.priklady.raii;
    19 
    20 /**
    21  *
    22  * @author Ing. František Kučera (frantovo.cz)
    23  */
    24 public class Zdroj implements AutoCloseable {
    25 
    26 	private final String název;
    27 	private final boolean chybaVytváření;
    28 	private final boolean chybaDělání;
    29 	private final boolean chybaZavírání;
    30 
    31 	public Zdroj(String název, boolean chybaVytváření, boolean chybaDělání, boolean chybaZavírání) throws ChybaVytváření {
    32 		this.název = název;
    33 		System.err.println("Vytváříme: " + this + " chyba=" + chybaVytváření);
    34 		this.chybaVytváření = chybaVytváření;
    35 		this.chybaDělání = chybaDělání;
    36 		this.chybaZavírání = chybaZavírání;
    37 
    38 		if (this.chybaVytváření) {
    39 			throw new ChybaVytváření(this);
    40 		}
    41 	}
    42 
    43 	public void něcoDělej() throws ChybaDělání {
    44 		System.err.println("Něco děláme: " + this + " chyba=" + chybaDělání);
    45 
    46 		if (chybaDělání) {
    47 			throw new ChybaDělání(this);
    48 		}
    49 	}
    50 
    51 	@Override
    52 	public void close() throws ChybaZavírání {
    53 		System.err.println("Zavíráme: " + this + " chyba=" + chybaZavírání);
    54 
    55 		if (chybaZavírání) {
    56 			throw new ChybaZavírání(this);
    57 		}
    58 	}
    59 
    60 	@Override
    61 	protected void finalize() throws Throwable {
    62 		try {
    63 			System.err.println("Finalizujeme: " + this);
    64 		} finally {
    65 			super.finalize();
    66 		}
    67 	}
    68 
    69 	@Override
    70 	public String toString() {
    71 		return getClass().getSimpleName() + " [" + název + "]";
    72 	}
    73 
    74 }