Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Sunday, June 9, 2013

Published 1:14 AM by with 0 comment

Abstract Classes C#

Abstract


The abstract modifier can be used with classes, methods, properties, indexers, and events.
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.
Abstract classes have the following features:
  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
Abstract methods have the following features:
  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:
public abstract void MyMethod();

  • The implementation is provided by an overriding method, which is a member of a non-abstract class.
  • It is an error to use the static or virtual modifiers in an abstract method declaration.
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • It is an error to use the abstract modifier on a static property.
  • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I 
{
   void M();
}
abstract class C: I 
{
   public abstract void M();
}

Example

In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().
// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC   // Abstract class
{
   protected int x = 100; 
   protected int y = 150;
   public abstract void MyMethod();   // Abstract method

   public abstract int GetX   // Abstract property
   {
      get;
   }

   public abstract int GetY   // Abstract property
   {
      get;
   }
}

class MyDerivedC: MyBaseC
{
   public override void MyMethod() 
   {
      x++;
      y++;   
   }   

   public override int GetX   // overriding property
   {
      get 
      {
         return x+10;
      }
   }

   public override int GetY   // overriding property
   {
      get
      {
         return y+10;
      }
   }

   public static void Main() 
   {
      MyDerivedC mC = new MyDerivedC();
      mC.MyMethod();
      Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);    
   } 
}
Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.



// C#
abstract class WashingMachine
{
   public WashingMachine()
   {
      // Code to initialize the class goes here.
   }

   abstract public void Wash();
   abstract public void Rinse(int loadSize);
   abstract public long Spin(int speed);
}

// C#
class MyWashingMachine : WashingMachine
{
   public MyWashingMachine()
   {  
      // Initialization code goes here.    
   }

   override public void Wash()
   {
      // Wash code goes here.
   }

   override public void Rinse(int loadSize)
   {
      // Rinse code goes here.
   }

   override public long Spin(int speed)
   {
      // Spin code goes here.
   }
}
Ref:http://msdn.microsoft.com/en-us/library/sf985hc5(v=vs.71).aspx
Read More

    email this       edit

Wednesday, May 8, 2013

Published 9:50 PM by with 0 comment

Template Method Pattern



Template Method Pattern

Definition
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

abstract class AbstractClass
    {
        public abstract void PrimitiveOperation1();
        public abstract void PrimitiveOperation2();

        public void TemplateMethod()
        {
            PrimitiveOperation1();
            PrimitiveOperation2();
            Console.WriteLine("Call Template Method");
        }
    }

    //Concrete Class A
    class ConcreteClassA : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("concreate A primi 1");
        }

        public override void PrimitiveOperation2()
        {
            Console.WriteLine("concreate A primi 2");
        }
    }

    //Concrete Class B
    class ConcreteClassB : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("concreate B primi 1");
        }

        public override void PrimitiveOperation2()
        {
            Console.WriteLine("concreate B primi 2");
        }
    }

//calling…
            //Template Method
            AbstractClass a = new ConcreteClassA();
            a.TemplateMethod();

            AbstractClass b = new ConcreteClassB();
            b.TemplateMethod();

Read More
    email this       edit
Published 1:44 AM by with 0 comment

Composite Pattern - [Structural Patterns]


Definition
[Download cs c#]
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

    //Component class
    abstract class Component
    {
        protected string name;

        public Component(string name)
        {
            this.name = name;
        }

        public abstract void Add(Component c);
        public abstract void Remove(Component c);
        public abstract void Display(int Dept);
    }

    //Composite Class
    class Composite : Component
    {
        private List<Component> _com = new List<Component>();

        public Composite(string name):base(name)
        {

        }
        public override void Add(Component c)
        {
            _com.Add(c);
        }
        public override void Remove(Component c)
        {
            _com.Remove(c);
        }
        public override void Display(int Dept)
        {
            Console.WriteLine(new String('-',Dept)+name);

            foreach (Component component in _com)
            {
                component.Display(Dept + 2);
            }
        }
    }

        //Leaf Class
        class Leaf : Component
        {
            public Leaf(string name):base(name)
            {

            }
            public override void Add(Component c)
            {
                Console.WriteLine("Can not add to a leaf");
            }
            public override void Remove(Component c)
            {
                Console.WriteLine("Can not remove from a leaf");
            }
            public override void Display(int Dept)
            {
                Console.WriteLine(new String('-', Dept) + name);
            }
        }


            //---Composite Calling...
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XAB"));

            root.Add(comp);
            root.Add(new Leaf("Leaf C"));

            // Add and remove a leaf
            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);

            // Recursively display tree
            root.Display(1);



Read More
    email this       edit

Sunday, May 5, 2013

Published 11:24 PM by with 0 comment

Observer Pattern - [Behavioral Patterns]


Observer Pattern 

[Download cs c#]

Definition

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.



    //Observer Class
    abstract class Observer
    {
        public abstract void Update();
    }


    //Subject Class
    abstract class Subject
    {
        private List<Observer> _observer = new List<Observer>();

        public void Register(Observer obs)
        {
            _observer.Add(obs);
        }

        public void Unregister(Observer obs)
        {
            _observer.Remove(obs);
        }

        public void Notify()
        {
            foreach (Observer obs in _observer)
            {
                obs.Update();
            }
        }
    }

    //StockMarket Class
    class StockMarket : Subject
    {
        private string _subjectState;

        public string SubjectState
 {
get
{
 return _subjectState;
}
set
{
 _subjectState = value;
}
}
    }


    //GoogleStockGadet Class
    class GoogleStockGadet  : Observer
    {
        private string _name;
        private string _observerState;
        private StockMarket _concreteSubject;

        public GoogleStockGadet(StockMarket conSubject, string name)
        {
            _concreteSubject = conSubject;
            _name = name;
        }

        public override void Update()
        {
            _observerState = _concreteSubject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState);
        }

        public StockMarket Subject
 {
 get
 {
return _concreteSubject;
 }
 set
 {
 _concreteSubject = value;
 }
 }
    }

    //MSNStockGadget Class
    class MSNStockGadget  : Observer
    {
        private string _name;
        private string _observerState;
        private StockMarket _concreteSubject;

        public MSNStockGadget(StockMarket conSubject, string name)
        {
            _concreteSubject = conSubject;
            _name = name;
        }

        public override void Update()
        {
            _observerState = _concreteSubject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState);
        }

        public StockMarket Subject
 {
get
{
return _concreteSubject;
}
Set
{
_concreteSubject = value;
}
 }
    }


    //YahooStockGadget Class
    class YahooStockGadget  : Observer
    {
        private string _name;
        private string _observerState;
        private StockMarket _concreteSubject;

        public YahooStockGadget(StockMarket conSubject, string name)
        {
            _concreteSubject = conSubject;
            _name = name;
        }

        public override void Update()
        {
            _observerState = _concreteSubject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState);
        }

        public StockMarket Subject
 {
 get
 {
 return _concreteSubject;
 }
 Set
 {
_concreteSubject = value;
 }
 }
    }

            //Calling...
            StockMarket s = new StockMarket();

            s.Register(new GoogleStockGadet(s, "X"));
            s.Register(new MSNStockGadget(s, "Y"));
            s.Register(new YahooStockGadget(s, "Y"));

            s.SubjectState = "ABC";
            s.Notify();


Read More
    email this       edit