You are on page 1of 57

Table

of Contents
0
1
1.1
1.2
1.3
Iterator 1.4
1.5
1.6
1.7
1.8
2

howtocode.com.bd

| HowToCode | |


- , , ,
...

Like 18 Share

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives


4.0 International License.


BuzzWord

,


/ %

, %

Fighter class

public class Fighter


{
public int Health { get; set; }
public void ChangeMood(String mood)
{
switch (mood)
{
case "Angry":
SetAnggsiveBehavior();
break;
case "Defensive":
SetDefensiveBehavior();
break;
}
}
private void SetDefensiveBehavior()
{
Console.WriteLine("Defensive Mood");
}
private void SetAnggsiveBehavior()
{
Console.WriteLine("Angry Mood");
}
}

Health Fighter ChangeMood()


Switch
Switch Angry SetAnggsiveBehavior()
Defensive SetDefensiveBehavior()

CllientCode Fighter class

class Program
{
static void Main(string[] args)
{
var fighter = new Fighter();
var random = new Random();

fighter.Health = random.Next(1, 100);

if (fighter.Health <= 50)


{
fighter.ChangeMood("Defensive");
}
else if (fighter.Health > 50)
{
fighter.ChangeMood("Angry");
}

Console.ReadKey();
}
}

class library
Mood
OCP (Open Close Principle )
OCP class/entity

Fighter class switch case


OCP

Principle of Least Knowledge


Fighter class ,

SRP (Single Responsibility Principle)



class

IFighter
Fight()

public interface IFighter


{
void Fight();
}

class
IFighter

public class Aggresive : IFighter


{
public void Fight()
{
Console.WriteLine("Fighter is now in aggresive mood");
}
}

public class Defensive : IFighter


{
public void Fight()
{
Console.WriteLine("Fighter is now in defensie mood");
}
}

SRP

Principle of Least Knowledge OCP Fighter class


public class Fighter


{
public int Health { get; set; }
private IFighter _fighter;
public void ChangeMood(IFighter fighter)
{
_fighter = fighter;
_fighter.Fight();
}

ClientCode

class Program
{
static void Main(string[] args)
{
var fighter = new Fighter();
var random = new Random();

fighter.Health = random.Next(1, 100);

if (fighter.Health <= 50)


{
fighter.ChangeMood(new Defensive());
}
else if (fighter.Health > 50)
{
fighter.ChangeMood(new Aggresive());
}

Console.ReadKey();
}
}

class library
Fighter class

class IFighter , Fight()


Fighter ChangeMood()

/ (
Sorting) switch if else

Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.


, new

Person class

public class Person


{
public String Name { get; set; }
public String Email { get; set; }
}

ClientCode

public static void Main(string[] args)


{
var person = new Person();
person.Name = "Person1";
person.Email = "xyz@mail.com";
Console.WriteLine("Name:{0} and Email:{1}", person.Name, person.Email);


new

Person class :P

public interface IClone


{
Object Clone();
}

class

Person class IClone


Clone Person
Person class

public class Person : IClone


{
public String Name { get; set; }
public String Email { get; set; }
public Object Clone()
{
var person = new Person
{
Name = Name,
Email = Email
};

return person;
}
}

public class Program


{
public static void Main(string[] args)
{
Person person = new Person();
person.Name = "Person";
person.Email = "xyz@mail.com";

Console.WriteLine("Before Cloning.......");
Console.WriteLine("Name:{0} and Email:{1}", person.Name, person.Email);

Person person1 = person.Clone() as Person;


Console.WriteLine("After Cloning..............");
Console.WriteLine("Name:{0} and Email:{1}", person1.Name, person1.Email);
}
}

10

Person class Clone


class

.NET MemberwiseClone()
Object class Protected

public class Person : IClone


{
public String Name { get; set; }
public String Email { get; set; }
public Object Clone()
{
return MemberwiseClone();
}
}

public class Program


{
public static void Main(string[] args)
{
Person person = new Person();
person.Name = "Person";
person.Email = "xyz@mail.com";

Console.WriteLine("Before Cloning.......");
Console.WriteLine("Name:{0} and Email:{1}", person.Name, person.Email);

Person person1 = person.Clone() as Person;


Console.WriteLine("After Cloning..............");
Console.WriteLine("Name:{0} and Email:{1}", person1.Name, person1.Email);
}
}

ShallowCopy
DeepCopy.

ShallowCopy ?? -

11

ShallowCopy ,
ShallowCopy
ShallowCopy

class Address Street

public class Address


{
public String Street { get; set; }
}

Person class

public class Person : IClone


{
public String Name { get; set; }
public String Email { get; set; }
public Address Address { get; set; }
public Person()
{
Address = new Address();
}
public Object Clone()
{
return MemberwiseClone();
}
}

Person class Address class

Person Address
Address

, Address
Address

12

public class Program


{
public static void Main(string[] args)
{
Person person = new Person();

person.Name = "Person";
person.Email = "xyz@mail.com";
person.Address.Street = "221B";

Person person1 = person.Clone() as Person;


person1.Address.Street = "221B Baker Street";

Console.WriteLine("After Cloning..............");
/*showing person1's Address in person object*/
Console.WriteLine("Street:{0}",person.Address.Street);
}
}

Address
Address Address


DeepCloning

DeepCloning:

DeepCloning MemberwiseClone()

13

public class Person : IClone


{
public String Name { get; set; }
public String Email { get; set; }
public Address Address { get; set; }
public Person()
{
Address = new Address();
}
public Object Clone()
{
//cloning member variable
Person person = this.MemberwiseClone() as Person;

//cloning reference object


person.Address = new Address();
person.Address.Street = this.Address.Street;
return person;
}
}

public class Program


{
public static void Main(string[] args)
{
Person person = new Person();

person.Name = "Person";
person.Email = "xyz@mail.com";
person.Address.Street = "221B";

Person person1 = person.Clone() as Person;


person1.Name = "Person";
person1.Email = "xyz@mail.com";
person1.Address.Street = "221B Baker Street";

Console.WriteLine("Before Cloning.......");
Console.WriteLine("Name:{0} and Email:{1}, Street:{2}", person.Name, person.Email, person

Console.WriteLine("After Cloning.......");
Console.WriteLine("Name:{0} and Email:{1}, Street:{2}", person1.Name, person1.Email, pers
}
}

ShallowCopy
( )

14

DeepCopy class
[Serializable] Person class clone()

[Serializable] Address class

[Serializable]
public class Address
{
public String Street { get; set; }
}

[Serializable] Person class

[Serializable]
public class Person : IClone
{
public String Name { get; set; }
public String Email { get; set; }
public Address Address { get; set; }
public Person()
{
Address = new Address();
}
public Object Clone()
{
using (Stream stream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, new Person());
stream.Seek(0, SeekOrigin.Begin);
return (Person)binaryFormatter.Deserialize(stream);
}
}
}

, DeepCopy

15

public class Program


{
public static void Main(string[] args)
{
Person person = new Person();

person.Name = "Person";
person.Email = "xyz@mail.com";
person.Address.Street = "221B";

Person person1 = person.Clone() as Person;


person1.Name = "Person";
person1.Email = "xyz@mail.com";
person1.Address.Street = "221B Baker Street";

Console.WriteLine("Before Cloning.......");
Console.WriteLine("Name:{0} and Email:{1}, Street:{2}", person.Name, person.Email, person

Console.WriteLine("After Cloning.......");
Console.WriteLine("Name:{0} and Email:{1}, Street:{2}", person1.Name, person1.Email, pers
}
}

Prototype Design Pattern

:)

16

, ,


/
C# class
class

Class

public class Calculator


{
public int GetSum(int[] numbers)
{
int sum = numbers.Sum();
return sum;
}
}

ClientCode Calculator class


public class Program


{
static void Main(string[] args)
{
var calculator = new Calculator();
int[] numbers = { 1, 2, 3, 4, 5 };
var sum = calculator.GetSum(numbers);
Console.WriteLine(sum);
}
}

17

DLL DLL
class

class

class Array
Array Collection Framework
List,Dictionary,HashTable

class
class

public class CalculatorAdapter


{
private readonly Calculator _calculator;
public CalculatorAdapter()
{
_calculator =new Calculator();
}

public int GetTotalSum(List<int> numbers)


{
int sum = _calculator.GetSum(numbers.ToArray());
return sum;
}
}

?? Calculator class
GetSum() GetTotalSum()
GetSum()
Array GetTotalSum()

Array
Array

ClientCode

18

class Program
{
static void Main(string[] args)
{
CalculatorAdapter calculator = new CalculatorAdapter();
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var sum = calculator.GetTotalSum(numbers);
Console.WriteLine(sum);
}
}

CalculatorAdapter Adapter
Calculator class Calculator class

Array
ClientCode


;)

Convert the interface of a class into another interface clients expect. Adapter lets
classes work together that couldnt otherwise because of incompatible interfaces.

19

Iterator

(
)

List

public class Facebook


{
private List userList;
public Facebook()
{
userList = new List();
userList.Add("Logical Forhad");
userList.Add("Rayhanur Rahman");
userList.Add("Maruf Khan");
userList.Add("Arif Raian");
userList.Add("Mahedi Mahfuj");
userList.Add("Atish Dipankar");
}
public List GetUserList()
{
return userList;
}
}

Array

Iterator 20

public class Twitter


{
private String[] userList;
private const int MAX_USER = 6;
public Twitter()
{
userList = new string[MAX_USER];
userList[0] = "_iLogical";
userList[1] = "Amit Seal Ami";
userList[2] = "Crackbrained Sakkhor";
userList[3] = "Bazlur Rahman Rokon";
userList[4] = "Sachine Tendulkar";
userList[5] = "Shane Watson";
}

public String[] GetUserList()


{
return userList;
}
}

Iterator 21

public class Program


{
static void Main(string[] args)
{
Facebook facebook = new Facebook();//concrete implementation
List<string> fbuserList = facebook.GetUserList();

Console.WriteLine("Facebook users........n");

for (int i = 0; i < fbuserList.Count; i++)


{
Console.WriteLine(fbuserList[i]);
}
Console.WriteLine("n");

Twitter twitter = new Twitter();//concrete implementation


String[] twitterUserList = twitter.GetUserList();
Console.WriteLine("Twitter users........n");

for (int i = 0; i < twitterUserList.Length; i++)


{
Console.WriteLine(twitterUserList[i]);
}

Console.ReadKey();
}
}

, , OOP
Code to interface not to implementation.



(
++ = ) OOP
Encapsulation ?
,



Iterator 22

public interface ISocialNetworking


{
bool HasNext();
Object Next();
}

class

public class FacebookIterator : ISocialNetworking


{
private List<String> userList;
private int _postion = 0;
public FacebookIterator()
{
userList = new List<string>();
userList.Add("Logical Forhad");
userList.Add("Rayhanur Rahman");
userList.Add("Maruf Khan");
userList.Add("Arif Raian");
userList.Add("Mahedi Mahfuj");
userList.Add("Atish Dipankar");
}
public bool HasNext()
{
return userList.Count() > _postion;
}

public object Next()


{
String element = userList.ElementAt(_postion++);

return element;
}
}

Iterator 23

public class TwitterIterator : ISocialNetworking


{
private String[] userList;
private const int MAX_USER = 6;
private int position = 0;
public TwitterIterator()
{
userList = new string[MAX_USER];
userList[0] = "_iLogical";
userList[1] = "Amit Seal Ami";
userList[2] = "Crackbrained Sakkhor";
userList[3] = "Bazlur Rahman Rokon";
userList[4] = "Sachine Tendulkar";
userList[5] = "Shane Watson";
}

public bool HasNext()


{
return userList.Length > position;
}

public object Next()


{
String element = userList[position++];
return element;
}
}

Iterator 24

public class Program


{
static void Main(string[] args)
{

Console.WriteLine("Facebook users........n");
ISocialNetworking iterator = new FacebookIterator();
while (iterator.HasNext())
{
Console.WriteLine(iterator.Next());
}
Console.WriteLine("n");

iterator = new TwitterIterator();


Console.WriteLine("Twitter users........n");
while (iterator.HasNext())
{
Console.WriteLine(iterator.Next());
}
Console.ReadKey();
}
}

Twitter class

(ISocialNetworking)

Twitter class

public class Twitter


{
private String[] userList;
private const int MAX_USER = 6;
public Twitter()
{
userList = new string[MAX_USER];
userList[0] = "_iLogical";
userList[1] = "Amit Seal Ami";
userList[2] = "Crackbrained Sakkhor";
userList[3] = "Bazlur Rahman Rokon";
userList[4] = "Sachine Tendulkar";
userList[5] = "Shane Watson";
}

public ISocialNetworking GetIterator()


{
return new TwitterIterator();
}
}

Iterator 25

Facebook class

public class Facebook


{
private List<String> userList;
public Facebook()
{
userList = new List<string>();
userList.Add("Logical Forhad");
userList.Add("Rayhanur Rahman");
userList.Add("Maruf Khan");
userList.Add("Arif Raian");
userList.Add("Mahedi Mahfuj");
userList.Add("Atish Dipankar");
}

public ISocialNetworking GetIterator()


{
return new FacebookIterator();
}
}

Iterator 26

public class Program


{
static void Main(string[] args)
{
ISocialNetworking iterator;

Facebook facebook = new Facebook();


Twitter twitter = new Twitter();

iterator = facebook.GetIterator();

Console.WriteLine("Facebook users........n");
while (iterator.HasNext())
{
Console.WriteLine(iterator.Next());
}
Console.WriteLine("n");

iterator = twitter.GetIterator();

Console.WriteLine("Twitter users........n");
while (iterator.HasNext())
{
Console.WriteLine(iterator.Next());
}
Console.ReadKey();
}
}

Iterator
Iterator .NET
IEnumerator , Collection

FacebookIterator ,TwitterIterator ISocialNetworking


Facebook Twitter class

Iterator 27

public class Facebook


{
private List<String> userList;
public Facebook()
{
userList = new List<string>();
userList.Add("Logical Forhad");
userList.Add("Rayhanur Rahman");
userList.Add("Maruf Khan");
userList.Add("Arif Raian");
userList.Add("Mahedi Mahfuj");
userList.Add("Atish Dipankar");
}

public IEnumerator GetIterator()//introducing IEnumurator


{
return userList.GetEnumerator();
}
}

public class Twitter


{
private String[] userList;
private const int MAX_USER = 6;
public Twitter()
{
userList = new string[MAX_USER];
userList[0] = "_iLogical";
userList[1] = "Amit Seal Ami";
userList[2] = "Crackbrained Sakkhor";
userList[3] = "Bazlur Rahman Rokon";
userList[4] = "Sachine Tendulkar";
userList[5] = "Shane Watson";
}

public IEnumerator GetIterator()//introducing IEnumurator


{
return userList.GetEnumerator();
}
}

Iterator 28

public class Program


{
static void Main(string[] args)
{
IEnumerator iterator;//changed

Facebook facebook = new Facebook();


Twitter twitter = new Twitter();

iterator = facebook.GetIterator();

Console.WriteLine("Facebook users........n");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current);
}
Console.WriteLine("n");

iterator = twitter.GetIterator();

Console.WriteLine("Twitter users........n");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current);
}
Console.ReadKey();
}
}

Iterator
Collection :)

:)

Iterator 29

CodeReuse

Response enum
enum

public enum Response


{
Approved,
Denied
}

/
Approve
Approve interface Approve
Response enum
Employee interface IApprover :

30

public interface IApprover


{
Response Approve(Employee employee);
}

??
class class
Employee . Name Days. Employee class

public class Employee


{
public String Name { get; set; }
public int Days { get; set; }
public Employee(String name, int days)
{
Name = name;
Days = days;
}
}

interface interface implement


TeamLeader ProjectManager Employee

IApprover implement TeamLeader ProjectManager


class TeamLeader class

public class TeamLeader : IApprover


{
public Response Approve(Employee employee)
{
if (employee.Days == 1)
return Response.Approved;
return Response.Denied;
}
}

ProjectManager class

31

public class ProjectManager : IApprover


{
public Response Approve(Employee employee)
{
if (employee.Days <= 3 && employee.Days >= 1)
return Response.Approved;
return Response.Denied;
}
}

TeamLeader ProjectManager Approve Employee


TeamLeader Denied
Approved ProjectManager

ClientCode

public class Program


{
public static void Main(string[] args)
{
Employee employee = new Employee("Forhad", 4);

IApprover approver = new TeamLeader();

Response responses = approver.Approve(employee);

if (Response.Approved != responses)
{
approver = new ProjectManager();
responses = approver.Approve(employee);
if (Response.Approved == responses)
{
Console.WriteLine("Request Granted Have A nice journey Mr:{0}", employee.Name);
}
else
{
Console.WriteLine("Sorry Your Request was not granted Mr:{0}", employee.Name);
}
}
else
{
Console.WriteLine("Request Granted Have A nice journey Mr:{0}", employee.Name);
}

}
}

32

ClientCode ??

Employee OOP Inheritance IApprover


TeamLeader IApprover Approve()
Employee Pass Approve
Response enum Response enum

Response Approved Emplyee Greetings


Response Denied ProjectManager
Employee
Greetings Approve

ClientCode Employee
,


ClientCode
( if else) J


/ /

IAppover
(
) HandOver ,

Responsibility Chaining

IApprover

public interface IApprover


{
Response Approve(Employee employee);
IApprover NextApprover { get; set; }
}

TeamLeader class

33

public class TeamLeader : IApprover


{
public Response Approve(Employee employee)
{
if (employee.Days == 1)
return Response.Approved;
return NextApprover.Approve(employee);
}

public IApprover NextApprover { get; set; }


}

TeamLeader NextApprover
NextApprover.Approve(employee);

ProjectManager

public class ProjectManager : IApprover


{
public Response Approve(Employee employee)
{
if (employee.Days <= 3 && employee.Days >= 1)
return Response.Approved;
return NextApprover.Approve(employee);
}
public IApprover NextApprover { get; set; }
}

ResourceManager class

public class ResourceManager : IApprover


{
public Response Approve(Employee employee)
{
if (employee.Days >= 7)

return Response.Approved;

return NextApprover.Approve(employee);
}
public IApprover NextApprover { get; set; }
}

34

/
TeamLeader,ProjectManager,ResourceManager
RequestHandler class
/

RequestHandler class

public class RequestHandler : IApprover


{
public Response Approve(Employee employee)
{
return NextApprover.Approve(employee);
}
public IApprover NextApprover { get; set; }
}

RequestHandler
Redirect

private static IApprover CreateChain()


{
IApprover handler = new RequestHandler();
IApprover approver1 = new TeamLeader();
IApprover approver2 = new ProjectManager();
IApprover approver3 = new ResourceManager();
handler.NextApprover = approver1;
approver1.NextApprover = approver2;
approver2.NextApprover = approver3;
return handler;
}

RequestHandler
TeamLeader,ProjectManager,ResourceManager

Handler NextApprover ( Redirect )TeamLeader


(approver1) , TeamLeader NextApprover (
Redirect ) ProjectManager , ProjectManager
ResourceManager Chaining

35

RequestHandler

ClientCode

public class Program


{
private static IApprover CreateChain()
{
IApprover handler = new RequestHandler();
IApprover approver1 = new TeamLeader();
IApprover approver2 = new ProjectManager();
IApprover approver3 = new ResourceManager();
handler.NextApprover = approver1;
approver1.NextApprover = approver2;
approver2.NextApprover = approver3;
return handler;
}

public static void Main(string[] args)


{
var employee = new Employee("Forhad", 7);

IApprover handler = CreateChain();

Response response = handler.Approve(employee);

if (response == Response.Approved)
{
Console.WriteLine("Have A nice Journey Mr:{0}", employee.Name);
}
else if (response == Response.Denied)
{
Console.WriteLine("Sorry Mr:{0} We are busy now", employee.Name);
}
Console.ReadLine();
}
}

Chaining ??

Chaining Chain

return NextApprover.Approve(employee);
Response.Denied Chain Chain
Responsibility Chain Chain
Exception ( :) ) Null Exception :)

Chain , Chain Responsibility , Responsibility


Chain Of Responsibility

36

, :)

37

Subject
Observer . Observer
Subject . Subject
Observer Observer Subject

GOF Observer Pattern Define a one-to-many dependency between


objects so that when one object changes state, all its dependents are notified and updated
automatically.

Subject Observer Subject


Automatically Observer

Subscribe
Subscribe


, ??

Subscriber
Subject GetNotification()

38

public interface ISubscriber


{
void GetNotification(String postTitle);
String Name { get; set; }
}

Moderator
Moderator Subscriber. Moderator ISubscriber
:

public class Moderator : ISubscriber


{
public String Name { get; set; }
public Moderator(String name)
{
Name = name;
}
public void GetNotification(String postTitle)
{
Console.WriteLine("Hello Mr:{0} A new post named {1} has been posted in the blognyou need
}
}

User ISubscriber

public class User : ISubscriber


{
public String Name { get; set; }
public User(String name)
{
Name = name;
}
public void GetNotification(String postTitle)
{
Console.WriteLine("Hey {0} Checkout the new post named {1}", Name, postTitle);
}
}

Blog Subscriber

39

public class Blog


{
private String _postTitle;
public String PostTitle
{
get
{
return _postTitle;
}
set
{
if (_postTitle != value)
{
_postTitle = value;
NotifySubscribers();
}
}
}
private void NotifySubscribers()
{
ISubscriber observer = new User("Forhad");
observer.GetNotification(_postTitle);
observer = new Moderator("Modu");
observer.GetNotification(_postTitle);
}
}

Getter Setter Setter



NotifySubscribers()
NotifySubscribers() ISubscriber
User Moderator GetNotification()

ClientCode :

public class Program


{
public static void Main(string[] args)
{
Blog blog = new Blog ();
blog.PostTitle = "ObserverPattern";
Console.ReadLine();
}
}

40

Blog NotifySubscribers()
Blog Subscriber

CMS
ClassLibrary
(DLL) DLL Obfuscated Code
Decompile/Reverse Engineering

CMS Subscriber Administrator


Subscriber DLL
Subscriber Subscriber Blog class
Administrator class Blog class NotifySubscribers()
GetNotification() Subscriber
DLL Blog class PostTitle
DLL

DLL
SOLID OCP (Open Closed Principle)

OCP /

Blog class NotifySubscribers()


Subscriber

ClassLibrary

NotifySubscribers()
ClientCode
Blog
Subscriber
Subscribe() ISubscriber

NotifySubscribers()
Blog
Subscriber Blog class
Subscriber ISubscriber
class Subscriber ISubscriber

Subscribe() ISubscriber ISubscriber


ClientCode Subscriber

41

NotifySubscribers() ISubscriber GetNotification()


GetNotification() Blog class _postTitle
Blog class

public class Blog


{
private String _postTitle;
private readonly List<ISubscriber> _subscribers;

public Blog()
{
_subscribers = new List<ISubscriber>();
}
public String PostTitle
{
get
{
return _postTitle;
}
set
{
if (_postTitle != value)
{
_postTitle = value;
NotifySubscribers(_subscribers);
}
}
}

public void Subscribe(ISubscriber subscriber)


{
_subscribers.Add(subscriber);
}

private void NotifySubscribers(List<ISubscriber> subscribers)


{
foreach (ISubscriber subscriber in subscribers)
{
subscriber.GetNotification(_postTitle);
}
}
}

ClientCode

42

public class Program


{
public static void Main(string[] args)
{
Blog blog = new Blog();

blog.Subscribe(new Moderator("Modu"));

blog.Subscribe(new User("Forhad"));

blog.PostTitle = "Observer Pattern";

Console.ReadLine();
}
}

ClassLibrary Subscriber
class ISubscriber ClientCode Blog
Subscribe Subscriber
Blog Subscriber Subscriber
Blog Blog
UnSubscribe Subscribe ISubscriber
Subscriber

Blog class class


Blog class

Unsubscribe

43

public class Blog


{
private String _postTitle;
private readonly List<ISubscriber> _subscribers;

public Blog()
{
_subscribers = new List<ISubscriber>();
}
public String PostTitle
{
get
{
return _postTitle;
}
set
{
if (_postTitle != value)
{
_postTitle = value;
NotifySubscribers(_subscribers);
}
}
}

public void Subscribe(ISubscriber subscriber)


{
_subscribers.Add(subscriber);
}

public void UnSubscribe(ISubscriber subscriber)


{
_subscribers.Remove(subscriber);
}

private void NotifySubscribers(List<ISubscriber> subscribers)


{
foreach (ISubscriber subscriber in subscribers)
{
subscriber.GetNotification(_postTitle);
}
}
}

ClientCode

44

public class Program


{
public static void Main(string[] args)
{
Blog blog = new Blog();

ISubscriber user = new User("DemoUser");


ISubscriber moderator = new User("Modu");
blog.Subscribe(moderator);
blog.Subscribe(user);
blog.PostTitle = "Observer Pattern";

blog.UnSubscribe(moderator);//we unsubscribed themoderator


blog.PostTitle = "Singleton";
Console.ReadLine();
}
}

Blog class

IObservable:

public interface IObservable


{
void Subscribe(ISubscriber subscriber);
void UnSubscribe(ISubscriber subscriber);
void NotifySubscribers(List<ISubscriber> subscribers);
}

45

public class Blog : IObservable


{
private String _postTitle;
private readonly List<ISubscriber> _subscribers;
public Blog()
{
_subscribers = new List<ISubscriber>();
}
public String PostTitle
{
get
{
return _postTitle;
}
set
{
if (_postTitle != value)
{
_postTitle = value;
NotifySubscribers(_subscribers);
}
}
}

public void Subscribe(ISubscriber subscriber)


{
_subscribers.Add(subscriber);
}

public void UnSubscribe(ISubscriber subscriber)


{
_subscribers.Remove(subscriber);
}

public void NotifySubscribers(List<ISubscriber> subscribers)


{
foreach (ISubscriber subscriber in subscribers)
{
subscriber.GetNotification(_postTitle);
}
}

ClientCode :)

DLL Interface ,
class , ClientCode
Subscriber Blog

Observer Design Pattern.

46

Subject ( Blog)
( PostTitle) Push Observer
Pull Push Pull Java
.Net API Java .Net class
interface

Java .Net Observer Pattern


( , )

MVC Architectural Pattern Model View


Observable Observer Observer Pattern.


:P

47


, BFC BFC
, BFC
, BFC
BFC
/ BFC
BFC

,

public class Store


{
public int Id { get; set; }
public String Name { get; set; }
public int Profit { get; set; }
}

/ City class

48

public class City


{
public List<Store> StoreList { get; private set; }
public int Id { get; set; }
public String Name { get; set; }

public City()
{
StoreList = new List<Store>();
}

public void RemoveStore(Store store)


{
StoreList.Remove(store);
}

public void AddStore(Store store)


{
StoreList.Add(store);
}

public int GetCityProfit()


{
int totalProfit = 0;
foreach (Store store in StoreList)
{
totalProfit += store.Profit;
}
return totalProfit;
}
}

, City class BFC



GetCityProfit() City

49

class Program
{
public static void Main(string[] args)
{
var store1 = new Store
{
Id = 1,
Name = "Malibagh BFC",
Profit = 2
};
var store2 = new Store
{
Id = 2,
Name = "Gulshan BFC",
Profit = 5
};

var city = new City


{
Id = 10,
Name = "Dhaka"
};
city.AddStore(store1);
city.AddStore(store2);
int totalProfit = city.GetCityProfit();
Console.WriteLine("Total Profit of {0} city is : {1}", city.Name, totalProfit);
Console.ReadLine();
}
}

BFC

, BFC
City Class Division Class
City Add/Delete GetDivisionProfit() City
Division class

50

public class Division


{
public List<City> CityList { get; private set; }

public int Id { get; set; }


public int Profit { get; set; }
public Division()
{
CityList = new List<City>();
}

public void AddCity(City city)


{
CityList.Add(city);
}

public void RemoveCity(City city)


{
CityList.Remove(city);
}

public int GetDivisionProfit()


{
int totalProfit = 0;
foreach (City city in CityList)
{
foreach (Store store in city.StoreList)
{
totalProfit += store.Profit;
}
}
return totalProfit;
}
}

51

public class Program


{
public static void Main(string[] args)
{
var store1 = new Store
{
Id = 1,
Name = "Malibagh BFC",
Profit = 2
};
var store2 = new Store
{
Id = 2,
Name = "Gulshan BFC",
Profit = 5
};

var city = new City


{
Id = 10,
Name = "Dhaka"
};
city.AddStore(store1);
city.AddStore(store2);

var division = new Division


{
Id = 1,
Name = "Rajshahi"
};

division.AddCity(city);
int totalProfit = division.GetDivisionProfit();
Console.WriteLine("Total Profit of {0} division is : {1}", division.Name, totalProfit);
Console.ReadLine();
}
}

,
, ,
( BFC KFC )

Class hierarchy
Division City Division

hierarchy
(City Division ,
- ) ,

52

Store,City Division Add, Remove


Calculation

public interface IProfitable


{
int GetProfit();
void AddChild(IProfitable profitable);
void RemoveChild(IProfitable profitable);
int Id { get; set; }
String Name { get; set; }
}

Store class

public class Store : IProfitable


{
public int Profit { get; set; }
public int Id { get; set; }
public String Name { get; set; }
public int GetProfit()
{
return Profit;
}
public void AddChild(IProfitable profitable)
{
throw new NotImplementedException();
}
public void RemoveChild(IProfitable profitable)
{
throw new NotImplementedException();
}
}

Store class Leaf, AddChild RemoveChild


Unimplemented City class IProfitable

53

public class City : IProfitable


{
public int Id { get; set; }
public String Name { get; set; }
public List<IProfitable> StoreList { get; private set; }
public City()
{
StoreList = new List<IProfitable>();

}
public int GetProfit()
{
int totalProfit = 0;

foreach (IProfitable store in StoreList)


{
totalProfit += store.GetProfit();
}

return totalProfit;
}

public void AddChild(IProfitable profitable)


{
if (profitable is Store)
StoreList.Add(profitable);

}
public void RemoveChild(IProfitable profitable)
{
if (profitable is Store)
StoreList.Remove(profitable);
}
}

,City class AddChild RemoveChild


, City class Store Division class
City Division class

54

public class Division : IProfitable


{
public int Id { get; set; }
public String Name { get; set; }
public List<IProfitable> CityList { get; private set; }
public Division()
{
CityList = new List<IProfitable>();
}
public int GetProfit()
{
int totalProfit = 0;
foreach (IProfitable city in CityList)
{
totalProfit += city.GetProfit();
}
return totalProfit;
}
public void AddChild(IProfitable profitable)
{
if (profitable is City)
CityList.Add(profitable);
}
public void RemoveChild(IProfitable profitable)
{
if (profitable is City)
CityList.Remove(profitable);
}
}

City class Division class , Class ,


GetProfit() Class
GetProfit()

55

public class Program


{
public static void Main(string[] args)
{
IProfitable store1 = new Store
{
Id = 1,
Name = "Malibagh BFC",
Profit = 2
};
IProfitable store2 = new Store
{
Id = 2,
Name = "Gulshan BFC",
Profit = 5
};

IProfitable city = new City


{
Id = 10,
Name = "Dhaka"
};
city.AddChild(store1);
city.AddChild(store2);

IProfitable division = new Division


{
Id = 1,
Name = "Rajshahi"
};
division.AddChild(city);
int totalProfit = division.GetProfit();
Console.WriteLine("Total Profit of {0} division is : {1}", division.Name, totalProfit);
Console.ReadLine();
}
}

:)

56

57

You might also like