Design Patterns Avi Roth Malam Team CTO. Agenda Industry Best Practice C# advanced features Object...

Preview:

Citation preview

Design PatternsDesign Patterns

Avi RothMalam TeamCTO

AgendaAgenda

• Industry Best Practice• C# advanced features • Object Oriented design guidelines • Chosen Design Patterns• Q&A• Summary

Boku: Programming for Kids

PDC Announcement….PDC Announcement….

ScienceArt

GameEngineering

Programming

?

Programming is…Programming is…

• Electrical engineering

• Building Engineering

• Food Engineering

• Mechanical Engineering

• Industrial Engineering ???

• Software engineering ???

Engineering typesEngineering types

• License is not required

• Hit & Try

• Results Oriented

• No standards / regulatory

• WHAT is more important than HOW

But Software Engineering….But Software Engineering….

Object Oriented

Design Guidelines !

Market down alertMarket down alert

• Pull vs. Push• Peer 2 Peer (no mediator)• Decoupling• Develop plug-ins

Stock Market Down

Send SMS

SMS

E-mail

Newspaper

public void StockValueChanged(string StockName){    SMSSender MySMS = new SMSSender();    MySMS.SendSMS("Microsoft daily change is 5%");    MySMS.SendSMS("Google daily change is -7.5%");}

public void StockValueChanged(string StockName){    SMSSender MySMS = new SMSSender();    MySMS.SendSMS("Microsoft daily change is 5%");    MySMS.SendSMS("Google daily change is -7.5%");}

Implementation – Take #1Implementation – Take #1

• Problems:

• Add more actions.

• Classes are highly coupled.

Design PrincipleDesign Principle

Program to an interface,

not to an implementation.

• Program to an interface

• Program to an Implementation

Animal myAnimal = new Dog();myAnimal.makesound();

 Dog d = new Dog();d.bark();

Design PrincipleDesign Principle

Strive for loosely coupled

designs betweens objects

that interact

Observer – 2Observer – 2ndnd Try Implementation Try Implementation

public interface ISubject

  {

    void RegisterObserver(IObserver o);

    void RemoveObserver(IObserver o);

    void NotifyObservers(string message);

  }

ObserverObserver– Take #2– Take #2public interface IObserver{

void Update(string Message);}

class SMSSender : IObserver{   public void SendSMS(string Message)   {      Console.WriteLine("SMS update: " + Message);   }   public void Update(string Message)   {        SendSMS(Message);  }    }

class Bank_SecondTry : Isubject{

Observer 2Observer 2ndnd Try Implementation Try Implementation

private IList<IObserver> observers = new List<IObserver>();   public void RegisterObserver(IObserver subscriber)   {      observers.Add(subscriber);   }

   public void RemoveObserver(IObserver subscriber)  {      observers.Remove(subscriber);  }

  public void NotifyObservers(string SubjectMsg)  {     foreach (IObserver observer in observers) {       observer.Update(SubjectMsg);       }   }

Observer 2nd Try ImplementationObserver 2nd Try Implementationstatic void Main(string[] args){   Bank_SecondTry MyBank = new Bank_SecondTry();    Monitor MyMonitor = new Monitor();    NewsDesk MyNewsDesk = new NewsDesk();    SMSSender MySMSSender = new SMSSender();     MyBank.RegisterObserver(MyMonitor);    MyBank.RegisterObserver(MyNewsDesk);    MyBank.RegisterObserver(MySMSSender);     MyBank.NotifyObservers();}

Observer - definitionObserver - definition

The Observer Pattern defines a one-to-

many Dependency between objects so that

when one object changes state, all of its

dependents are notified and updated

automatically.

.NET Observer Implementation.NET Observer Implementation

public class Bank : Isubject{

public delegate void UpdateStockValueHandler(string MyMsg);

public event UpdateStockValueHandler UpdateStockValueEvent;

public void Notify(){  if (UpdateStockValueEvent != null) {    UpdateStockValueEvent("Microsoft changes today …“);  }}

.NET Observer Implementation.NET Observer ImplementationBank MyBank = new Bank();

Monitor myMonitor = new Monitor();NewsDesk MyNewsDesk = new NewsDesk();SMSSender MySMSSender = new SMSSender(); MyBank.UpdateStockValueEvent += new Bank.UpdateStockValueHandler(myMonitor.Update);

MyBank.UpdateStockValueEvent += new Bank.UpdateStockValueHandler(MyNewsDesk.Update);

MyBank.UpdateStockValueEvent += new Bank.UpdateStockValueHandler(MySMSSender.Update); MyBank.Notify();

MyBank.UpdateStockValueEvent += delegate(string s)       { Console.WriteLine("the message..."); };

Open a new bankOpen a new bank

Account

Solider Student Family Business

Open

Deposit

Balance

Calc…

Open

Deposit

Balance

Calc…

Open

Deposit

Balance

Calc…

Open

Deposit

Balance

Calc…

Bank Class DiagramBank Class Diagram

Bank Class DiagramBank Class Diagram

Improve the bankImprove the bank

• Support mortgage

• Override to nothing in

unnecessary classes??

OpenMortgage

Improve the bank ???Improve the bank ???

InterfaceInheritance

Design PrincipleDesign Principle

Identify the aspects of your

application that vary

and separate them from

what stays the same.

Design PrincipleDesign Principle

Favor composition

over Inheritance.

“HAS A” is better

than “IS A”

StrategyStrategy

StrategyStrategy

public class BusinessAccount : Account {

Strategy ImplementationStrategy Implementation

  public  BusinessAccount()   {   this.MortgageBehavior = new MortgageEasy(); this.MoneyTransferBehavior = new

TransferInternational();   }   public void StartMortgage()  {      this.MortgageBehavior.StartMortgage();    }

    public void TransferMoney()   {      this.MoneyTransferBehavior.MoneyTransfer();    }

Strategy ImplementationStrategy Implementationpublic class FamilyAccount : Account{  public FamilyAccount()  {

this.MortgageBehavior = new MortgageForFamilies2009();

this.MoneyTransferBehavior = new TransferInBank();

  }    public void StartMortgage()   {      this.MortgageBehavior.StartMortgage();   }

Principle of Least Knowledge Principle of Least Knowledge

Don’t talk

to strangers

Open Closed PrincipleOpen Closed Principle

Classes should be Open to

Extensibility and Closed

to Modifications

State MachineState Machine

Delay

Pause

State MachineState Machinepublic string DeleteLoan(){  switch(state)  {    case PAUSED:       actionResponse = "can't deleted paused…";       // dont change state       break;    case PAYMENTS:                 actionResponse = "First, return loan";       // don't change state       break;    case REQUEST:       actionResponse = "DELETED!";       // change state        break;     case DELAY:       actionResponse = "First, return loan";      // don't change state      default:

• Efficiency• Scan 50%• Preserve state

• Modularity• Add new state• Add new actions

State 1State 2State 3State 4State 5action1action1action1action1action1action2action2action2action2action2action3action3action3action3action3action4action4action4action4action4action5action5action5action5action5

Manage LoansManage Loans

Method (= action)

per state

Manage LoansManage Loans

Manage LoansManage Loanspublic class PauseState : IState  {    Loan MyLoan;     public PauseState(Loan MyLoan) 

    public string DeleteLoan()

    public string CalcInterest()     public string FinalizedLoan()     public string PauseLoan()

Manage Loans – Manage Loans – cont.cont.

    public double CalcInterest ()    {        // since pause, add... and ... and ...        return "the interest is ....";    }  public string DeleteLoan()    {      return "First, return the loan";      // don't change state    }     public string PauseLoan()    {      return "already paused....";    }

MyState.CalcInterest ();

MyState.DeleteLoan();

HoldingsHoldings

• Changes• Regulation – risk assessment• Tax

Savings

Financial

FXStocks

Assets

…BuildingsCash

Saving Class ModelSaving Class Model

class Savings { IList<Saving> _savings = new List<Saving>();         public void Attach(Saving Saving)        {            _savings.Add(Saving);        }         public void Detach(Saving Saving)        {            _savings.Remove(Saving);        }     }

SavingsSavings

• Operations are defined on structures

• Operations and structures are defined

separately

• Perform new operations on elements

without changing classes

• Internal vs. External

VisitorVisitor

External ImplementationExternal Implementationforeach (object item in collection)   {    if (item is StockSaving)      {        StockSaving itm = item as StockSaving;      // do Stock specific calculations     }      else if (item is FXSaving)     {        FXSaving itm = item as FXSaving;      // do FX specific calculations      }      else if (item is Building)      {          Building itm = item as Building;      // do Building specific calculations      }

Saving / ElementSaving / Element

VisitorVisitorabstract class Element{ public abstract void Accept(Ivisitor visitor);}

class Saving : Element{  public string Name { get; set; }  public double Amount { get; set; }  public int NumOfDays { get; set; }   public override void Accept(IVisitor visitor)  {      visitor.Visit(this);  }}

interface Ivisitor{     void Visit(CashSaving element);     void Visit(FXSaving element);     void Visit(Building element);}class RiskAnalyzerVisitor : Ivisitor{   public void Visit(CashSaving element)   {     CashSaving Saving = element as CashSaving;      // do specific ...  }    public void Visit(Building element)   {      Building MyBuilding = element as Building;      // do specific ...   }    }

class Savings { IList<Saving> _savings = new List<Saving>();         public void Attach(Saving Saving)……        public void Detach(Saving Saving)……                  public void Accept(IVisitor visitor)        {            foreach (Saving e in _savings)            {                e.Accept(visitor);            }            Console.WriteLine();        }    }

class Savings { IList<Saving> _savings = new List<Saving>();         public void Attach(Saving Saving)……        public void Detach(Saving Saving)……         

        static void Main(string[] args)        {            // Setup Saving collection             Savings e = new Savings();            e.Attach(new StockSaving());            e.Attach(new CashSaving());            e.Attach(new FXSaving());             // Savings are 'visited'             e.Accept(new IncomeVisitor());            e.Accept(new RiskAnalyzerVisitor());

VisitorVisitor

Extension MethodsExtension Methodspublic static class Common{   public static int CalcTax(this Element elm)   {        return 123; // calc....   }}

Decorator Observer Singleton Command Factory Adapter Proxy MVCStateStrategyNEW ???NEW ???

public void DoesntMatter (int something) {     Account MyAccount;     if (something == 1)     {         MyAccount = new StudentAccount();     }else     {         MyAccount = new FamilyAccount();     }     MyAccount.DoSomething();}

Decorator Observer Singleton Command Factory Adapter Proxy MVCStateStrategy Anti PtrnIn Class FactoryIn Class Factory

public void DoesntMatter1 (int something) {     Account MyAccount;     MyAccount = factory(something);     MyAccount.DoSomething();}

public void factory (int something){                if (something == 1)     {          MyAccount = new StudentAccount();     }else     {          MyAccount = new FamilyAccount();     }}

Decorator Observer Singleton Command Factory Adapter Proxy MVCStateStrategy Anti PtrnFactory MethodFactory Method

public void DoesntMatter2 (int something) {    Account MyAccount;    MyAccount = AccountFactory(something);   MyAccount.Print();} public abstract Account AccountFactory(int type);

Template MethodTemplate Method

Decorator Observer Singleton Command Factory Adapter Proxy MVCStateStrategy Anti PtrnFactory MethodFactory Method

public void DoByOrder (int something) {    Account MyAccount;

  MyAccount.Step1();   MyAccount.Step2();   MyAccount.Step3();   MyAccount.Step4();} public abstract Void Step1(int type);public abstract Void Step3(int type);

Account’s

Method

Decorator Observer Singleton Command Factory Adapter Proxy MVCStateStrategy Anti PtrnTemplate Method / Partial MethodsTemplate Method / Partial Methods

public partial class Account{        partial void Step1();        partial void Step2();        partial void Step3();         public void AllSteps()        {            Step1();            Step2();            Step3();        }}

Decorator Observer Singleton Command Factory Adapter Proxy MVCStateStrategy Anti PtrnTemplate Method / Partial MethodTemplate Method / Partial Method

public partial class Account{    partial void Step1()    {       //Step1 implementation     }}

public partial class Account    {        partial void Step2()        {        }         partial void Step3()        {        }

איך לבחור?

Selecting the right Design PatternSelecting the right Design Pattern

Q & AQ & A

• A successful programmer uses 2 primary tools:• good programming language • design patterns• Patterns help you learn from other’s

successes, instead of your own failures Mark Johnson (cited by B. Eckel)

SummarySummary

• WWW.DoFactory.COM

Additional InformationAdditional Information

Related SessionsRelated SessionsDEV403 - A Deep Dive into LINQערן שרעבי16:00 – 17:15 Galil Hall

DEV404 - Hardcore C#: Hidden Power and Flexibilityפבל יוסיפוביץ09:00 – 10:30 Galil Hall

PNL01 - .Net Architecture קובי כהן14:30 – 15:40 Sharon Hall

© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.

The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after

the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Recommended