What is a software design pattern?
Ans: It is is a general, reusable solution to a commonly occurring problem in software design.
What are the Factory and Singleton patterns?
Ans: Instead of using a constructor, the Factory pattern uses a static method, traditionally called
getInstance, that returns an object.
When do you want to use the Factory pattern?
Ans: The Factory pattern is used in two situations: (a) when the
getInstance method might return objects from
an inheritance hierarchy of classes, (b) when objects are reused; when an object is needed, the
getInstance method first checks if an object is available to reuse.
If not, a new object is created using a private constructor.
Why is the Singleton pattern controversial?
Ans: Because only one instance of the class is created, every user wanting to use that object is
given a reference to it. This makes the object global; global objects are notoriously difficult to test
because it is hard to know who is using the object.
What is the difference between lazy and eager instantiation?
Ans: Lazy instantiation means wait until the object is used to instantiate it;
eager instantiation means that the object is created immediately when the
software using it starts up.
Observer Pattern
The Observer Pattern is facilitated by these two items:
the Observable class and the Observer interface.
The Observable class and the Observer interface are now depreciated in the Java Class Library. This is because they
are not considered to be "industrial strength."
Here is a UML diagram showing the relationship between the MessageBoard
and Student classes with the Observable class and the Observer interface.
The Student objects are the observers.
The MessageBoard object
must extend the Observable class to qualify as an observable.
contains a posted message that may be useful to the observers.
may add one or more observers (Student objects) with the addObserver method.
may delete observers with the deleteObservers method.
calls the setChange method to show that the message has been changed.
calls the notifyObservers method whenever the message is changed to notify
all the observers. Calling notifyObservers automatically calls its
clearChange
after all observers have been notified.
the notifyObservers method automatically calls the
update method of each
registered observer.
A Student object
must implement the Observer interface to qualify as observer.
supplies the required update method (which will be automatically called by
notifyObservers in Item 7 of the MessageBoard object).
in addition, each observer can go back to the observable to obtain additional
information.
The Strategy pattern encapsulates the strategy of an algorithm in an object.
The programmer can use this Strategy object without understanding the details of
the algorithm.