Saturday, December 20, 2008

Design patterns (Java Concepts)

What is a singleton?
A: A singleton class is one in which instantiation is restricted to ensure that only one instance is created for the current Java Virtual Machine. Singletons usually have a private default constructor, to prevent direct instantiation, and a static method to obtain a "new" reference to the single instance. On its first call, the static instance method creates the object using a private constructor and stores a static reference to it for all subsequent calls.

What happens to singletons when two JVMs are running?
A: There is only one instance of a true singleton in a single virtual machine. If two virtual machines are running, two separate and independent instances of a singleton exist. If the singleton in question is governing access to the same system resource, there may be conflicts between the two systems, which is why the singleton design pattern is not ideal in this scenario

How do I format my price correctly?
A: Whenever you need to represent quantities that have specific formatting and equivalence requirements, it is best to use the Quantity design pattern. For a Money type, you can associate a Currency with the amount and can deal with all rounding issues in one class. Your money and currency types can then use generic rendering methods to show the amount however you choose.

What is a factory method?
A: A factory method is typically used to obtain a new instance of a class, which may be one of several alternate implementations. The return type of a factory method is an interface or superclass type, which gives it the freedom to govern the actual class that is returned through polymorphism. This design pattern enables the factory to control and encapsulate the logic used to decide which instance to return.

How should I create an immutable class?
A: An immutable class is one whose field values cannot be altered after instantiation, so all variable values must be assigned in the constructor and may therefore be declared final. By definition an immutable class should not have any modifier methods, but you must also be careful that the constructor and accessor methods do not expose mutable field references.

No comments:

Post a Comment

Bookmark and Share
Join the TrafficZap Exchange