public class Main {
public static void main(String[] args) {
Employee graham = new Employee("Graham",
"CEO",
"Making excutive decisions");
Printer printer = new Printer();
graham.printCurrentAssignment(printer);
}
}
This way of solving the problem is totally fine and will not at this scale present any problem. However, being able to initialize the class from anywhere and having unnecessary arguments for any method will at scale become a problem in terms of maintenance and understanding the code.
Since we know that there is only one printer in the office, the public constructor becomes a dangerous opportunity for the system. What if a developer sits in another part of the code and do not have the printer object available? Well they could just initialize it and use it.
However, this means that we suddenly have two printer objects in the code, which does not reflect the real-world scenario. This may cause problems if we for example wanted to keep track of all pages printed by the single instance of the printer.
Let’s imagine that we one day in the future add another method to the employee class, which also requires a printer. Say this method allows the employee to print multiple copies of a given document, with appropriate names and titles for each employee for which it is intended for.
As we can see the methods can quickly expand its list of arguments. Some of these arguments makes sense to provide for this method specifically, but the printer object is not one of them. Zero arguments are the optimal number of arguments.
We know that there is only one printer available at the office, so is it really necessary to provide it as an argument. Let’s see how we can solve this problem by utilizing the singleton pattern.
graham.printCopiesOfDocumentForListOfEmp(printer,
5,
"Time schedule for the past five weeks"
listOfEmployees);