An object is loosely coupled if it is dependent on only a few
other objects and/or the dependencies are abstract. In the Observer design pattern, the subject may have hundreds of observers (dependencies). In light of this, explain why the Observer design pattern is said to be loosely coupled.
In the Observer design pattern the subject object is loosely coupled
to its observers because it is dependent only on the abstract interface Observer, not on the actual instances of Observer. EXERCISE 2 Consider the code for the Singleton design pattern given below. Modify this code so that at most 5 instances are created and each instance can be individually referenced. public class Singleton { private static Singleton instance = null;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) { instance = new Singleton(); } return instance; } } EXERCISE 2: SOLUTION public class Multiton { private static readonly int _maxInstances = 5; private static Multiton[] instances = new Multiton[_maxInstances];
private Multiton() { }
public static Multiton getInstance(int index) {
if (index < 0 || index >= _maxInstances { return null; } if (instances[index] == null) { instances[index] = new Multiton(); } return instances[index]; } }
This pattern is called Multiton.
EXERCISE 2: IS THIS A SOLUTION? public class Singleton { private static Singleton instance = null; private int count = 0;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) { if (count < 5) { instance = new Singleton(); count++ } } return instance; } }