読者です 読者をやめる 読者になる 読者になる

Proxyパターン

% find . -name "*.java" -print0 |xargs -0 cat                                []
public class Main {

	public static void main(String[] args) {
		// Printable p = new PrinterProxy("Alice");
		Printable p = new PrinterProxy("Printer");
		p.setPrintName("Alice");
		System.out.println(p.getPrinterName());
		p.setPrintName("Bob");
		p.print("日本語");
	}

}
public interface Printable {
	void setPrintName(String name);

	String getPrinterName();

	void print(String string);
}
public class Printer implements Printable {
	private String name;

	public Printer() {
		heavyJob("Printerのインスタンスを生成中");
	}

	public Printer(String name) {
		this.name = name;
		heavyJob("Printerのインスタンスを生成中");
	}

	private void heavyJob(String string) {
		System.out.println(string);
		for (int i = 0; i < 5; i++) {
			try {
				Thread.sleep(1000);
				System.out.println(".");
			} catch (Exception e) {

			}
		}
		System.out.println("完了");
	}

	@Override
	public void setPrintName(String name) {
		this.name = name;
	}

	@Override
	public String getPrinterName() {
		return name;
	}

	@Override
	public void print(String string) {
		System.out.println("==== " + name + " ====");
		System.out.println(string);

	}

}
public class PrinterProxy implements Printable {
	private String name;
	private Printable real;
	private String className;

	public PrinterProxy() {

	}

	public PrinterProxy(String className) {
		this.className = className;
	}

	@Override
	public synchronized void setPrintName(String name) {
		if (real != null) {
			real.setPrintName(name);
		}
		this.name = name;
	}

	@Override
	public String getPrinterName() {
		return name;
	}

	private synchronized void realize() {
		if (real == null) {
			// real = new Printer(name);
			try {
				@SuppressWarnings("rawtypes")
				Class clazz = Class.forName(className);
				real = (Printable) clazz.newInstance();
				real.setPrintName(name);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void print(String string) {
		realize();
		real.print(string);
	}

}
Alice
Printerのインスタンスを生成中
.
.
.
.
.
完了
==== Bob ====
日本語