图解设计模式-Proxy模式
/**
* @ClassName: Printable
* @Author: Leo
* @Description: 打印功能的接口
* @Date: 2019/3/26 20:34
*/
public interface Printable {
/**
* 设置打印机名称
*/
void setPrinterName(String name);
/**
* 获取打印机名称
*
* @return
*/
String getPrinterName();
/**
* 打印指定字符串
*
* @param str
*/
void print(String str);
}
/**
* @ClassName: Printer
* @Author: Leo
* @Description: 打印机
* @Date: 2019/3/26 20:38
*/
public class Printer implements Printable {
private String name;
public Printer() {
heavyJob("正在生成 " + name + " 的实例:");
}
public Printer(String name) {
this.name = name;
heavyJob("正在生成 " + name + " 的实例:");
}
private void heavyJob(String msg) {
System.out.println(msg);
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i+1);
}
System.out.println("成功!");
}
@Override
public void setPrinterName(String name) {
this.name = name;
}
@Override
public String getPrinterName() {
return name;
}
@Override
public void print(String str) {
System.out.println("打印机 " + name + " 正在打印:\n" + str);
}
}
/**
* @ClassName: PrinterProxy
* @Author: Leo
* @Description: 打印机***
* @Date: 2019/3/26 20:46
*/
public class PrinterProxy implements Printable {
private String name;
private Printer printer;
public PrinterProxy(String name) {
this.name = name;
}
public PrinterProxy() {
}
@Override
public synchronized void setPrinterName(String name) {
if (printer != null) {
printer.setPrinterName(name);
}
this.name = name;
}
@Override
public String getPrinterName() {
return name;
}
@Override
public void print(String str) {
realize();
printer.print(str);
}
private synchronized void realize() {
if (printer == null) {
printer = new Printer(name);
}
}
}
/**
* @ClassName: Main
* @Author: Leo
* @Description:
* @Date: 2019/3/26 20:51
*/
public class Main {
public static void main(String[] args) {
Printable printable = new PrinterProxy("Leo");
printable.print("Hello World!");
}
}