Singleton
Singleton ensures that at most one instance of a class exists at any given time.
public class SingletonDemo { private static SingletonDemo instance = null; //set the constructor private private SingletonDemo() { } public static synchronized SingletonDemo getInstance() { if (instance == null) { instance = new SingletonDemo(); } return instance; } }
Factory
The implementation is really simple
- The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
- The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class).
- The client uses the products as abstract products without being aware about their concrete implementation.
The advantage is obvious: New shapes can be added without changing a single line of code in the framework(the client code that uses the shapes from the factory). As it is shown in the next sections, there are certain factory implementations that allow adding new products without even modifying the factory class.
public class ProductFactory{ public Product createProduct(String ProductID){ if (id==ID1) return new OneProduct(); if (id==ID2) return return new AnotherProduct(); // so on for the other Ids return null; //if the id doesn't have any of the expected values } }