java 模拟简单打印机功能_java 单例模式模拟打印机打印任务

1.打印机报错处理类

package com.pattern06.singleton.sample03;

public class PrintSpoolerException extends Exception {

public PrintSpoolerException() {

super();

}

public PrintSpoolerException(String message, Throwable cause) {

super(message, cause);

}

public PrintSpoolerException(String message) {

super(message);

}

public PrintSpoolerException(Throwable cause) {

super(cause);

}

}

2.打印机类

package com.pattern06.singleton.sample03;

public class PrintSpoolerSingleton {

private static PrintSpoolerSingleton instance = null;

private PrintSpoolerSingleton() {

}

public static PrintSpoolerSingleton getInstance() throws PrintSpoolerException {

if(instance == null) {

System.out.println("创建打印池......");

instance = new PrintSpoolerSingleton();

} else {

throw new PrintSpoolerException("打印出正在工作中......");

}

return instance;

}

public static void stop() {

instance = null;

}

public void manageJobs() {

System.out.println("管理打印池任务!");

}

}

3.测试类

package com.pattern06.singleton.sample03;

public class Client {

public static void main(String[] args) throws PrintSpoolerException {

PrintSpoolerSingleton p1,p2,p3;

//创建打印池

p1 = PrintSpoolerSingleton.getInstance();

//使用打印池

p1.manageJobs();

//停止打印池

PrintSpoolerSingleton.stop();

p2 = PrintSpoolerSingleton.getInstance();

p2.manageJobs();

//没有把打印池停止就直接获取打印池会报错

p3 =PrintSpoolerSingleton.getInstance();

}

}


版权声明:本文为weixin_32059509原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。