Popular Posts

Dec 25, 2012

Design Patterns

Creational Patterns

Abstract Factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Ensure a class only has one instance, and provide a global point of access to it.

Structural Patterns

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Decouple an abstraction from its implementation so that the two can vary independently.
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Use sharing to support large numbers of fine-grained objects efficiently.
Provide a surrogate or placeholder for another object to control access to it.

Behavioral Patterns

Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Template Method
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.
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Source: unknown

The S.O.L.I.D. Design Principles

The S.O.L.I.D. design principles are a collection of best practices for object-oriented design.

Single Responsibility Principle (SRP)

The principle of SRP is closely aligned with SoC. It states that every object should only have one
reason to change and a single focus of responsibility. By adhering to this principle, you avoid the
problem of monolithic class design that is the software equivalent of a Swiss army knife. By having concise objects, you again increase the readability and maintenance of a system.

Open-Closed Principle (OCP)

The OCP states that classes should be open for extension and closed for modification, in that you
should be able to add new features and extend a class without changing its internal behavior. The
principle strives to avoid breaking the existing class and other classes that depend on it, which
would create a ripple effect of bugs and errors throughout your application.

Liskov Substitution Principle (LSP)

The LSP dictates that you should be able to use any derived class in place of a parent class and have it behave in the same manner without modification. This principle is in line with OCP in that it ensures that a derived class does not affect the behavior of a parent class, or, put another way, derived classes must be substitutable for their base classes.

Interface Segregation Principle (ISP)

The ISP is all about splitting the methods of a contract into groups of responsibility and assigning interfaces to these groups to prevent a client from needing to implement one large interface and a host of methods that they do not use. The purpose behind this is so that classes wanting to use the same interfaces only need to implement a specific set of methods as opposed to a monolithic interface of methods.

Dependency Inversion Principle (DIP)

The DIP is all about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces. It promotes the mantra of coding to an interface rather than an implementation, which increases flexibility within a system by ensuring you are not tightly coupled to one implementation.

Source: unknown

Dec 11, 2012

Object Serialization - C#

Writing data to the disk as text is always dangerous. Any user can open the text file and easily read the data. With Object Serialization.

Serialization is the process of converting complex objects into stream of bytes for storage. Deserialization is its reverse process, that is unpacking stream of bytes to their original form. The namespace which is used to read and write files is System.IO. For Serialization we are going to look at the System.Runtime.Serializationnamespace. The ISerializable interface allows to make any class Serializable.

- Create a console project.add a class named it Employee
[Serializable()] //Set this attribute to all the classes that you define to be serialized
    public class Employee : ISerializable
        public int EmpId;
        public string EmpName;

        //Default constructor
        public Employee()
            EmpId = 0;
            EmpName = null;

        //Deserialization constructor.
        public Employee(SerializationInfo info, StreamingContext ctxt)
            //Get the values from info and assign them to the appropriate properties
            EmpId = (int)info.GetValue("EmployeeId", typeof(int));
            EmpName = (String)info.GetValue("EmployeeName", typeof(string));

        //Serialization function.
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
            //You can use any custom name for your name-value pair. But make sure you
            // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
            // then you should read the same with "EmployeeId"
            info.AddValue("EmployeeId", EmpId);
            info.AddValue("EmployeeName", EmpName);

 static void Main(string[] args)
            //Create a new Employee object
            Employee mp = new Employee();
            mp.EmpId = 204;
            mp.EmpName = "Jubayer";

            // Open a file and serialize the object into it in binary format.
            // EmployeeInfo.osl is the file that we are creating. 
            // Note:- you can give any extension you want for your file
            // If you use custom extensions, then the user will now 
            //   that the file is associated with your program.
            Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();

            Console.WriteLine("Writing Employee Information");
            bformatter.Serialize(stream, mp);

            //Clear mp for further usage.
            mp = null;

            //Open the file written above and read values from it.
            stream = File.Open("EmployeeInfo.osl", FileMode.Open);
            bformatter = new BinaryFormatter();

            Console.WriteLine("Reading Employee Information");
            mp = (Employee)bformatter.Deserialize(stream);

            Console.WriteLine("Employee Id: {0}", mp.EmpId.ToString());
            Console.WriteLine("Employee Name: {0}", mp.EmpName);

Download Code