设计模式-单例模式的应用
单例模式的应用
在操作系统中,打印池(Print Spooler)是一个用于管理打印任务的应用程序,通过打印池用户可以删除、中止或者改变打印任务的优先级,在一个系统中只允许运行一个打印池对象,如果重复创建打印池则抛出异常。现使用单例模式来模拟实现打印池的设计。用JAVA语言实现(C#控制台应用程序实现)该模式。绘制该模式的UML图。
【模式UML图】
【模式代码(JAVA语言实现)】
// PrintSpoolerSingleton.java:
package sdp.sy_4.singletonpattern;
public class PrintSpoolerSingleton {
private static PrintSpoolerSingleton instance;
private String name;
private PrintSpoolerSingleton(String name) {
this.name = name;
}
public static PrintSpoolerSingleton getInstance(String name) {
if( instance == null && !name.equals(null) ) {
instance = new PrintSpoolerSingleton(name);
}
return instance;
}
public void manageJobs() {
System.out.println(name+"...");
}
}
// PrintSpoolerMain.java:
package sdp.sy_4.singletonpattern;
import java.util.Scanner;
public class PrintSpoolerMain {
private static Scanner sc;
public static void main(String[] args) {
System.out.println("打印...");
try {
System.out.println("选择操作:");
System.out.println(" D ――Delete"); //删除任务
System.out.println(" S ――Suspension"); //中止任务
System.out.println(" C ――Change priorities"); //改变任务优先级
System.out.println(" E ――Exit"); //退出
sc = new Scanner(System.in);
while(true) {
switch (sc.next()) {
case "D":
PrintSpoolerSingleton DeletePrint = PrintSpoolerSingleton.getInstance("Delete");
DeletePrint.manageJobs();
break;
case "S":
PrintSpoolerSingleton SuspensionPrint = PrintSpoolerSingleton.getInstance("Suspension");
SuspensionPrint.manageJobs();
break;
case "C":
PrintSpoolerSingleton ChangePrioritiesPrint = PrintSpoolerSingleton.getInstance("Change priorities");
ChangePrioritiesPrint.manageJobs();
break;
case "E":
System.exit(1);
break;
default:
break;
}
}
} catch (Exception e) {
new PrintSpoolerException(e.getMessage());
}
}
}
// PrintSpoolerException.java:
package sdp.sy_4.singletonpattern;
public class PrintSpoolerException {
public PrintSpoolerException(String message) {
System.out.println(message);
}
}
【运行截图】