Docsity

Singleton Design Pattern: Implementation and Key Concepts, Exams of Computer Science

Partial preview of the text

Download Singleton Design Pattern: Implementation and Key Concepts and more Exams Computer Science in PDF only on Docsity!

1 /

  1. How do we edit a class that hasn't a singleton pattern to be a singleton pattern?
  2. What is the purpose of the getInstance method?

2 /

  1. First you make sure that you select the class that has to follow that pattern.
  2. Then you make the constructor private.
  3. Create a field of that class private static. (DO NOT INITIATE IT) so Basically if you have a class Player and there can only be one instance. Then the constructor should be private Player(String name) {...} Field: above constructor

private static Player player;

  1. This instance should be not initiated in the constructor, but rather in the getInstance method. the get instance method should be like public static Player getInstance() { if(object == null) { object = new Player(name);// THIS INITIATES THE CLASS } return object; //if it is not null, then just return it. } Then you can access this class through Classname.getInstance(); It should return you the ONE instance of the class that it gets. If it is null, then it initiates a new Instance of that class otherwise it returns the value of the field.