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

Factory Design pattern

Factory design pattern provides you an interface creating a single object, but let subclass decide which class to instantiate. This pattern is used most frequently when we are having common functionality with different methods for different objects.

In that scenario, we will create an interface with defining common functionality which will be implemented by the classes. A class will be defined which will be used to identify which class to be instantiated for the object.

For example, We have to create reading utility and we are having 3 different kind of files 1st is pdf, 2nd is doc and 3rd is txt file. On all the files we have to perform open operation but way to open the file will be different. In this case we will create an Interface will contain OpenFile Operation. There will be classes for each file type and the classes will be implementing the factory interface(Example is given in C# Code Example.

C# Code Example:

Overview of inheritance with C# : part 2

Overriding

If we create base class method to virtual and override the method of the derived class, now when we instantiate the base class object to derived class and call the method with respect to the object then method of derived class will be invoked.

Sample Code

Overview of inheritance with C# : part 1

When base class and derived class both have same method but base class's method is not virtual, and derived class's method is not overridden, then if we instantiate the object of base class to derived class and call the method with respect to the object created, the method written in base class will be invoked.

Sample code

namespace Inheritance { class Program { static void Main(string[] args) { BaseDemo bd = new DerivedDemo(); bd.PrintString(); Console.ReadLine(); } } class BaseDemo { public BaseDemo() { } public void PrintString() { Console.WriteLine("Base Demo Invoked"); } } class DerivedDemo : BaseDemo { public DerivedDemo() { } public void PrintString() { Console.WriteLine("Derived Demo Invoked"); } } }
Output
Base Demo Invoked

Compilation of above code will generate warning that
"Warning 1 'Inheritance.DerivedDemo.PrintString()' hides inherited member Inheritance.BaseDemo.PrintString()'. Use the new keyword if hiding was intended."

Abstract Class v/s Interface

Introduction 

In this article I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

What is an Abstract Class?