图解设计模式-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!");
    }
}

 

全部评论

相关推荐

10-13 17:47
门头沟学院 Java
wulala.god:图一那个善我面过,老板网上找的题库面的
点赞 评论 收藏
分享
ArisRobert:统一解释一下,第4点的意思是,公司按需通知员工,没被通知到的员工是没法去上班的,所以只要没被通知到,就自动离职。就是一种比较抽象的裁员。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务