Java Tutorial/Spring/Decouple

Материал из Java эксперт
Перейти к: навигация, поиск

Closed Coupled

File: Main.java



import java.io.PrintStream;
public class Main {
  public static void main(String[] a) {
    MessageData source = new MessageData("Hello, world");
    MessageReporter destination = new MessageReporter();
    destination.write(System.out, source.getMessage());
  }
}
final class MessageData {
  private final String message;
  public MessageData(String message) {
    this.message = message;
  }
  public String getMessage() {
    return message;
  }
}
class MessageReporter {
  public void write(PrintStream out, String message) {
    out.println(message);
  }
}





Decouple With Interface

File: Main.java



public class Main {
  public static void main(String[] a) {
    MessageData source = new SimpleMessageData("Hello, world");
    MessageReporter destination = new StdoutMessageReporter();
    destination.write(source.getMessage());
  }
}
interface MessageReporter {
  void write(String message);
}
interface MessageData {
  String getMessage();
}
class StdoutMessageReporter implements MessageReporter {
  public void write(String message) {
    System.out.println(message);
  }
}
class SimpleMessageData implements MessageData {
  private final String message;
  public SimpleMessageData() {
    this("Hello, world");
  }
  public SimpleMessageData(String message) {
    this.message = message;
  }
  public String getMessage() {
    return this.message;
  }
}





Spring Style Decouple

File: helloworld-context.properties



source.(class)=SimpleMessageData
destination.(class)=StdoutMessageReporter