Posts

Showing posts with the label state

Static Class vs. Singleton Class

I have explained two different implementation for making a class to Singleton, means restricting no of instance of a class to only one.You can refer previous posts Singleton Design Pattern by example & Alternative implementation for Singleton Class . Here by Static Class means a class that’s has only public static methods. Two different implementations as per previous post for restricting class instances to only one are making all constructor private referred as  Singleton  class and declaring all public methods as static.  Singleton class has several advantages over Static class pattern 1. A singleton class can extends class and implement interfaces , while Static class can not. 2. A singleton can be instantiated lazily or asynchronously while a static class is generally initialized when it is first loaded. 3.A singleton class can extended and its methods can be overridden. 4. The most important advantage is the singleton can be handled polymorphic ally withou...

State Design Pattern by Example

Image
State pattern falls under the category of Behavioral patterns. State design pattern comes in picture when a system’s behavior is depends on its own state or some other resource’s state. If an implementation is depends on the states, we end up with snarl of conditional statement every where in code. A very neat approach to deal with such situation is to separate out every state’s behavior and use them where ever they are applicable. The state pattern allows an object to alter its behavior when is internal state changes . The object is appeared to change its class. State pattern is a way to implement the same. Class Diagram : As above class diagram shows, System class holds state instance. As state of system changes , all handle request delegated to respective State’s concrete implementation. Example : Have an example of Vending machine. Vending machine has following states No Coin Inserted Coin Inserted Dispensing Empty Following diagram explain behavior...