Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Sunday, February 19, 2023

Dependency Injection 2

What is Dependency Injection

  • Produce a loosely coupled code
  • Any change in the class without affecting other object.
  • Type of DI
    • Constructor Injection
      • parameter to inject dependencies in a class
      • One parameterized constructor but no default constructor and you need to pass specified values to the constructor


    • Setter Injection
      • through properties of a class


    • Interface-based injection
      • through method


  • Advantage
    • Maintainability
      • maintain code structure, single principle
    • Flexibility
      • loosely coupled code, flexible to use different ways.
    • Testability
      • easy to do unit testing
    • Readability
      • Logic in constructor.













Tuesday, August 16, 2016

Static Constructor

performed once only. 
It is called automatically before the first instance is created or any static members are referenced.
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running
public class MyClass
 {
     public MyClass()
     {
         Console.WriteLine("Is Class Constructor");
     }

     static MyClass()
     {
         Console.WriteLine("Is Static Constructor");
     }

     public void method()
     {
         Console.WriteLine("Method A");
     }

     public static void methodStatic()
     {
         Console.WriteLine("Method Static");
     }
 }


 static void Main(string[] args)
 {
     MyClass classA = new MyClass();
     MyClass classB = new MyClass();
     classA.method();
     classB.method();

     MyClass.methodStatic();

     Console.ReadLine();

 }

Result :
Is Static Constructor
Is Class Constructor
Is Class Constructor
Method A
Method A
Method Static

Sunday, August 14, 2016

Prototype Pattern

Clone - Create new objects from the existing instance of the object. It does not affect the original object when any changes.

Shadow Clone - Only Self Class was cloned. (Child Class No Clone)
Deep Clone - Self and Child Class was cloned.


public Customer GetClone()
{
     Customer customer;
     customer = (Customer)this.MemberwiseClone();
     customer.address = (Address)address.GetClone();

     return customer;
}

public Address GetClone()
{
     Address address;
     address = (Address)this.MemberwiseClone();

     return address;
 }

Customer customerB = null;

customerB = customerA.GetClone();

Abstract Factory Pattern

Abstract Factory Pattern is a super-factory which creates others factory.
Animal Factory is a super- factory.
SeaAnimalFactory and LandAnimalFactory is a derived-factory.


Friday, August 12, 2016

Builder Design Pattern

Builder pattern builds a complex object by using a step by step approach. Builder interface defines the steps to build the final object


Builder 
  • This is an interface which is used to define all the steps to create a product 
  • E.g. IVehicleBuilder
ConcreteBuilder
  •  This is a class which implements the Builder interface to create complex product. 
  • E.g. HeroBuilder & HondaBuilder
Product
  • This is a class which defines the parts of the complex object which are to be generated by the builder interface.
  • E.g. Vehicle
Director
  • This is a class which is used to construct an object using the Builder interface.
  • E.g. Vehicle Creator

When to use it?
  • Need to create an object in several steps (a step by step approach).
  • The creation of objects should be independent from the way the object's parts are assembled.
  • Runtime control over the creation process is required.
http://www.dotnet-tricks.com/Tutorial/designpatterns/6aMR040613-Builder-Design-Pattern---C

Factory Design pattern

problem Without Factory :
  • A lot new Keyword, need to add  a lot code in future.
  • Client know all the invoice type.


public interface IInvoice
{
    void print();

}    

public class InvoiceWithoutHeader : IInvoice
{
    public void print()
    {
        Console.WriteLine("Invoice Without Header");
    }
}

public class InvoiceWithHeader : IInvoice
{
    public void print()
    {
        Console.WriteLine("Invoice With Header");
    }
}

public class FactoryInvoice
{
      public static IInvoice GetInvoice(int invoiceType)
      {
        IInvoice result = null;

        switch (invoiceType)
        {
            case 1:
                result = new InvoiceWithHeader();
                break;
            case 2:
                result = new InvoiceWithoutHeader();
                break;
            default:
                break;
        }
        return result;
       }
}


static void Main(string[] args)
{
            IInvoice invoice;
            invoice = FactoryInvoice.GetInvoice(1);
            invoice.print();

            IInvoice invoice2;
            invoice2 = FactoryInvoice.GetInvoice(2);
            invoice2.print();

            Console.ReadLine();
}



Tuesday, August 9, 2016

Struct VS Class

Structure(Struct)
structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
Classes and Structures have the following basic differences:
  • classes are reference types and structs are value types.
  • structures do not support inheritance.
  • structures cannot have default constructor.
Use When :
  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable. (No Change)
  • It will not have to be boxed frequently

8) Class vs Struct

When to Use Struct :
1. Small
2. Logically an immutable value (no Change)
3. There's a lot of them

Differences:
classes are reference types


static void Main(string[] args)
{
    MyClass myclass = new MyClass();
    myclass.I = 3;
    MyClass myClass2 = myclass;
    myclass.I = 4;
    Console.WriteLine("Class : {0},{1}", myclass.I, myClass2.I);

    MyStruct myStruct = new MyStruct();
    myStruct.I = 3;
    MyStruct myStruct2 = myStruct;
    myStruct.I = 4;
    Console.WriteLine("Struct : {0},{1}", myStruct.I, myStruct2.I);

    myclass.J = 3;
    myclass.ClassMod(myclass);
    myStruct.J = 3;
    myStruct.StructMod(myStruct);
    Console.WriteLine("{0},{1}", myclass.J, myStruct.J);
   
    Console.ReadLine();
}

public class MyClass
{
    public int I;
    public int J;

    public void ClassMod(MyClass mc)
    {
        mc.J += 100;
        Console.WriteLine(mc.J);
    }
}

public struct MyStruct
{
    public int I;
    public int J;

    public void StructMod(MyStruct ms)
    {
        ms.J += 100;
        Console.WriteLine(ms.J);
    }
}

Result :

Class : 4,4
Struct : 4,3
103
103
103,3

Abstract vs Virtual

Abstract - no implementation (no body) ,
                 MUST overridden,
                 Child cannot call base.method(), because Abstract Method no body,
                 only for Abstract Class.
                 semicolon at end.

Virtual- MAY implementation,
              Can overridden, if you like to use child method , u can write it ,else it will use base method.
              Virtual Method Can call base.method(), straight call base class method

abstract class A
{
public virtual int testVrtual()
    {
       return 0;
    }
    
    public abstract int test();

}

Public and static constructor

public constructor - users of the class can call that constructor (opposite is private).

static constructor  -  not belongs to an instance of a class but to the class itself. it is called once, automatically (.NET runtime itself ), when the class is used for the first time. No need public or private since cannot called manually.

If you have Public and static constructor together, static constructor will run 1st. When refresh it , static constructor would not run.

public class Bus
{
    public static int busNo = 0;

    static Bus()
    {
        Console.WriteLine("Woey, it's a new day! Drivers are starting to work.");
    }

    public Bus()
    {
        busNo++;
        Console.WriteLine("Bus #{0} goes from the depot.", busNo);
    }
}


class Program
{
    static void Main(string[] args)
    {
        Bus busOne = new Bus();
        Bus busTwo = new Bus();
    }

    // Output:
    // Woey, it's a new day! Drivers are starting to work.
    // Bus #1 goes from the depot.
    // Bus #2 goes from the depot.
}

Tuesday, August 2, 2016

Parent obj = new child() c# (Polymorphism)

public class A
    {
        public A()
        {
            Console.WriteLine("A");
        }
        public virtual void method()
        {
            Console.WriteLine("AM");
        }

    }
    public class B : A
    {
        public B()
        {
            Console.WriteLine("B");

        }
        public new void method()
        {
            Console.WriteLine("BM");

        }
    }

      Always Declare Behind (Parent) 1st

B obj = new A(); X
A obj = new B(); output A B AM, because linking to virtual A method. New void or normal void also is this result

B obj = new B(); output A B BM, direct call B method

A < B = B is A (Child is Parent)
Child obj = new Parent() is not possible, Parent is not Child

If change to public override void method()
All output is A B BM

Why want call like this? Why not call A obj = new A();
Because you want to use all these child classes through the interface / methods defined on your parent class.
·
http://www.akadia.com/services/dotnet_polymorphism.html
http://www.codeproject.com/Articles/816448/Virtual-vs-Override-vs-New-Keyword-in-Csharp