Skip to content

Instantly share code, notes, and snippets.

@rcaneppele
Last active November 21, 2018 14:43
Show Gist options
  • Save rcaneppele/bfa95d0da1288a0f03a93728a11515e3 to your computer and use it in GitHub Desktop.
Save rcaneppele/bfa95d0da1288a0f03a93728a11515e3 to your computer and use it in GitHub Desktop.
Exemplo de uso dos principios SOLID
public interface Escritor {
void escrever(String linha);
}
public class EscritorArquivo implements Escritor {
private final String caminho;
public EscritorArquivo(String caminho) {
if (caminho == null) {
throw new IllegalArgumentException("caminho nao pode ser null!");
}
this.caminho = caminho;
}
@Override
public void escrever(String linha) {
try(PrintStream ps = new PrintStream(new FileOutputStream(caminho, true), true)) {
ps.println(linha);
} catch (Exception e) {
throw new RuntimeException("erro ao escrever no arquivo: " +e);
}
}
}
public class EscritorConsole implements Escritor {
@Override
public void escrever(String linha) {
System.out.println(linha);
}
}
public interface Leitor {
String ler();
}
public class LeitorArquivo implements Leitor {
private final Scanner scanner;
public LeitorArquivo(String caminho) {
if (caminho == null) {
throw new IllegalArgumentException("caminho nao pode ser null!");
}
try {
this.scanner = new Scanner(new FileInputStream(caminho));
} catch (Exception e) {
throw new RuntimeException("erro ao ler arquivo: " + e);
}
}
@Override
public String ler() {
try {
return scanner.nextLine();
} catch (NoSuchElementException e) {
return null;
}
}
}
public class LeitorConsole implements Leitor {
private final Scanner scanner;
public LeitorConsole() {
this.scanner = new Scanner(System.in);
}
@Override
public String ler() {
try {
return scanner.nextLine();
} catch (NoSuchElementException e) {
return null;
}
}
}
public class Main {
public static void main(String[] args) {
Solid solid = new Solid();
solid.executar(new LeitorArquivo("input.txt"), new EscritorConsole());
}
}
public class Solid {
public void executar(Leitor leitor, Escritor escritor) {
String linha = leitor.ler();
while (linha != null) {
if ("exit".equalsIgnoreCase(linha)) {
break;
}
escritor.escrever(linha);
linha = leitor.ler();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment