February 23, 2020

Abstract class vs Interface


Abstract class vs Interface: 

1. A class can implement any number of interfaces but a subclass can at most use only one abstract class.
2. An abstract class can have non-abstract Methods(concrete methods or full method definition) while in case of Interface all the methods has to be abstract.
3. An abstract class can declare or use any variables while an interface is not allowed to do so.

4. An abstract class can have constructor declaration while an interface can not do so.

5. An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface we can not declare any access modifier(including public) as all the members of interface are implicitly public.

=========================================================================

Dictionary vs Hashtable
 
Dictionary:

– Dictionary is a generic type which means we can use it with any data type.
– Only public static members are thread safe.
– It returns error if we try to find a key which does not exist.
– It is faster than a Hashtable because there is no boxing and unboxing.

Hashtable:

– Hashtable is not a generic type.
– All the members in a Hashtable are thread safe.
– It returns null if we try to find a key which does not exist.
– It is slower than dictionary because it requires boxing and unboxing.


SOLID design pattern

The SRP states that a class should have only a single reason to change. This responsibility should be entirely encapsulated by the class. The services of the class should be narrowly aligned with that responsibility.

The Open-Closed Principle (OCP) states that software entities (classes, modules, methods, etc.) should be open for extension, but closed for modification.

LSP – Liskov Substitution Principle  states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application.”
LSP states that any child class should only extend or modify behavior defined in the parent class, NOT introduce new behavior.


High level modules should not depend on low level modules; both should depend on abstractions. Abstractions should not depend on details.  Details should depend upon abstractions. 

Singleton Pattern vs Static Class

 

In simple words, Singleton is a pattern and not a keyword. The Singleton pattern has several advantages over static classes. A singleton allows a class for which there is just one, persistent instance across the lifetime of an application. That means, it created a single instance and that instance (reference to that instance) can be passed as a parameter to other methods, and treated as a normal object. While a static class allows only static methods and and you cannot pass static class as parameter.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.
A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR (common language runtime) when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded and it will lead to potential class loader issues.
Singleton class follow the Object Oriented Principles, so that singletons can be handled polymorphically without forcing their users to assume that there is only one instance. While static cannot.
Other differencess:
  1. Singleton Objects stored on heap while static class stored in stack.
  1. Singleton Objects can have constructor while Static Class cannot.
  1. Singleton Objects can dispose but not static class.
  1. Singleton Objects can clone but not with static class.
x

Break singleton using c#

public class Person
{
    private static Person _person = null;

    private Person()
    { }

    public string Name { get; }

    public static Person PersonObj
    {
        get
        {
            if (_person == null)
                _person = new Person();

            return _person;
        }
    }
}
now i can create two instances of this class by Serialization.
static void Main(string[] args)
{
    Person p = Person.PersonObj;
    string sss = Newtonsoft.Json.JsonConvert.SerializeObject(p);
    Person p1 = JsonConvert.DeserializeObject<Person>(sss);    
    if (p != p1)
    {
           // insert here 
    }
} 
Now after Serialization I have two different object. As the class is singleton how it can have two different objects ?
Discussion :


This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created. 
A singleton is a programming concept - not a language feature. Its perfectly possible to create code that creates instances of classes that - in theory - should only be created by a singleton factory. You don't even need to use serialization to achieve that - just use Activator.CreateInstance().
It might be helpful also to consider that your class constructor also doesn't have to get called; sure, if your call new MyClass() it will do, but deserialization doesn't have to call the constructor. Serialization as a concept stores and rehydrates the state of a class instance; so it doesn't need to obey other class instantiation concepts, like constructor scope or constructor logic.

Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we ceate clone of a singleton object, then it wil create a copy that is there are two instances of a singleton class, hence the class is no more singleton.

Design Pattern(s)

1. Creational Patterns

  Abstract Factory : Creates an instance of several families of classes

  Builder : Separates object construction from its representation

  Factory Method : It is tedious when the client needs to specify the class name while creating the objects. So, to resolve this problem, we can use the Factory Method design pattern. It provides the client with a simple way to create the object.

  Prototype : A fully initialized instance to be copied or cloned

  Singleton : A class of which only a single instance can exist

  BuilderSeparates object construction from its representation

2. Structural Patterns

  Adapter ==> Match interfaces of different classes

  Bridge ==> Separates an object’s interface from its implementation

  Composite ==> A tree structure of simple and composite objects

  Decorator ==> Add responsibilities to objects dynamically

  Facade ==> A single class that represents an entire subsystem

  Flyweight ==> A fine-grained instance used for efficient sharing

  Proxy ==> An object representing another object



3. Behavioral Patterns

   Chain of Resp. ==> A way of passing a request between a chain of objects

  Command ==> Encapsulate a command request as an object

  Interpreter ==> A way to include language elements in a program

  Iterator ==> Sequentially access the elements of a collection

  Mediator ==> Defines simplified communication between classes

  Memento ==> Capture and restore an object's internal state

  Observer ==> A way of notifying change to a number of classes

  State ==> Alter an object's behavior when its state changes

  Strategy ==> Encapsulates an algorithm inside a class

  Template Method ==> Defer the exact steps of an algorithm to a subclass

  Visitor ==> Defines a new operation to a class without change