How To Use Behavioral Design Patterns In C# | Mark Farragher | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

How To Use Behavioral Design Patterns In C#

teacher avatar Mark Farragher, Microsoft Certified Trainer

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

14 Lessons (3h 14m)
    • 1. Behavioral design patterns

      1:53
    • 2. The gang of four and the 23 design patterns

      5:05
    • 3. The chain of responsibility pattern

      18:16
    • 4. The command pattern

      15:00
    • 5. The interpreter pattern

      18:11
    • 6. The iterator pattern

      16:58
    • 7. The mediator pattern

      16:39
    • 8. The memento pattern

      16:31
    • 9. The observer pattern

      18:02
    • 10. The state pattern

      17:25
    • 11. The strategy pattern

      15:10
    • 12. The template method pattern

      15:17
    • 13. The visitor pattern

      16:30
    • 14. Course recap

      2:53
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

68

Students

--

Projects

About This Class

e43aa0a0

In 1994 the "Gang of Four" published a book titled "Design Patterns: Elements of Reusable Object-Oriented Software". This book contains 23 fundamental software design patterns. It is regarded as the standard reference manual for object-oriented design theory and practice.

In this course I will teach you the 11 behavioral design patterns. You use these patterns to control how different parts of your application architecture interact with each other.

By the end of the course you will be fluent in all 11 behavioral design patterns. With this knowledge you will be well on your way to become a Senior Application Architect.

Why should you take this course?

You should take this course if you are a beginner or intermediate C# developer and want to take your career to the next level. Some of the patterns (e.g. 'Visitor') might sound very complicated, but all of my lectures are very easy to follow, and I explain all topics with clear code and many instructive diagrams. You'll have no trouble following along.

Or maybe you're working on the application architecture of a large project, and you need to create a robust design that is instantly clear to your team members? The patterns in this course will help you immensely.

Or maybe you're preparing for a C# related job interview? This course will give you an excellent foundation to answer any software architecture questions they might throw at you.

Meet Your Teacher

Teacher Profile Image

Mark Farragher

Microsoft Certified Trainer

Teacher

Mark Farragher is a blogger, investor, serial entrepreneur, and the author of 11 successful Udemy courses. He has been a Founder and CTO, and has launched two startups in the Netherlands. Mark became a Microsoft Certified Trainer in 2005. Today he uses his extensive knowledge to help tech professionals with their leadership, communication, and technical skills.

See full profile

Class Ratings

Expectations Met?
  • Exceeded!
    0%
  • Yes
    0%
  • Somewhat
    0%
  • Not really
    0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Behavioral design patterns: Let me ask you a question. Would you like to become a C sharp pattern? Architects. Okay, so I just made that word up. There is no pattern architects, but in my book, But I think that word means is that you are a senior developer with a keen understanding off software design patterns. If you are released developers or architects, this knowledge is essential for you to do your job. So in this course, I will help you learn the fundamental gun or Ford software design patterns. We're going to look at behavioral design patterns like the command pattern, the iterated pattern, the observer pattern and many others. So we're looking out of the famous offer design patterns off the gun off. Four book The Gun of Four book is basically the Bible off software design methodology on the patterns covered in the book are essential knowledge. If you're a developer, if your a C sharp developer, you really need to know these patterns. They are crucial. If you want to get promoted to lead developer or two architects as an architect, oil in the world A all day is assemble architectures from design patterns. So are you interested in becoming a C sharp pattern. Architects. Then this is the course for you have created this course for developers who want to take a career tour to the next level. For junior developers who want to become lead developer for lead developers who want to become architects until want to brush up their knowledge off the essential software design patterns to make an awesome impression in their next job interview. So thank you for listening on. I hope I'll be seeing you in the course. 2. The gang of four and the 23 design patterns: Okay, let's talk about design patterns. That's what, exactly is the design pattern in software engineering. A design pattern is a general reusable solution to a commonly a curing problem. It is a description or templates for how to solve a problem that can be used in many different situations. Patterns are formalized best practices that's the programmer can use to solve common problems when designing an application or system. A design pattern typically shows relationships on interactions between classes or objects, but without specifying the final application classes or objects that are involved. A good example is in operation when you need to get relatively step through each item in a list. You probably used the for each statements in C Sharp and think nothing about it. But behind the scenes, there's actually a lot going on. The C Sharp compiler creates a special object called on in numerator to implement the for each loop. On in numerator is an object specifically designed to step through items in a list. The in operator has a current property for reading the current item on a move next method to advance the current property to the next item. The move next method returns false when there are no more items. This is an implementation off a fundamental design pattern called It'll Raise her So each time when you need to get relatively step through a list, you can, of course, develop your own custom codes. But it's much better to use the standard. It's a razor pattern. This pattern was documented 21 years ago on generations of programmers have already used it and can vouch for its correctness. Design patterns also simplify teamwork with other developers. When you say we will use the iterated pattern, everybody knows what you're talking about, and you know exactly what kind of cold to expect when the pattern is implement. Is design patterns are kind off blueprints for a collection of classes on objects, relationships that work together to solve a common problem. They allow you to use simple names to describe large sections off your application. Architecture on this simplifies team developments enormously. Okay, now, in 1994 something very special happens. Four developers came together and they wrote a book on design patterns. They were there is dumber, Richard Hell, Ralph Johnson on John Philistines, and they became so famous that they are often simply referred to as the gang off four. The book they wrote was titles, design patterns, elements off reusable, object oriented software. And in the book they presented a very interesting theory. They claimed that they had discovered 23 fundamental design patterns on that all other patterns were simply combinations off these patterns. The book has bean enormously influential to the fields off software engineering, and today it is regarded as the standard reference manual for object oriented design theory and practice. If you want to become an application architects, you simply have to know all fundamental design patterns by heart. So in this course I will teach you the Final 11 gang for four patterns. This consists off all behavioral design patterns. You use behavioral patterns to structure how the different parts off your application architecture interact with each other. Are you ready? Let's get started 3. The chain of responsibility pattern: Okay, let's kick off this section with the first behavioral design pattern from the Favors gang or four design patterns book. This one is called Chain Off Responsibility. Pattern on It is a pattern you use when you want to avoid strong coupling between the sender off a request on its receiver by giving a list off receivers a chance to handle the request. It all starts with a quick summary off what we are trying to accomplish with this pattern. The chain off responsibility pattern is a good choice. When you are trying to accomplish the following, you are unable to match the sender off a request to its receiver at compile time. You want to map requests to multiple receivers. You want a request and forget architecture with a processing pipeline containing many possible requests. Receivers. Okay, let's go through the points one by one. The key concept off this design pattern is that your application architecture generates a stream off requests that must be handled by receiver objects. But the problem is that there is no clear one on one mapping between the centre off a request on the receiver off request. Perhaps the request receivers are configured on in Stan. She ate it at runtime using factory methods. Dad's a reads external configuration data, or maybe a single request sometimes needs to be handled by two or more receivers simultaneously. Or perhaps there are thousands off receivers on. It is simply not possible to have the center keep a reference to every single receiver. That Shane off responsibility pattern solves all of these problems. It sets up a request processing pipeline that is made up off a linked list off receivers. The clients drops new requests off at the entrance off the pipeline. Each receiver in the list examines the request, handles it if applicable, and then hands the request off to the next receiver in the list. The number and type off handler objects is not known in advance and can be configured dynamically. The chaining mechanism uses recursive composition to allow on unlimited number off handlers to be linked. But make sure there is a safety net to catch any requests which Gohan handled. The chain off responsibility pattern offers a number of benefits. First of all, one on one map. Ings between senders and receivers are not needed. Receivers can be configured dynamically as run time. More than one receiver can handle the request. Andi senders do not need to keep references to each receiver. Okay, so the main benefits off this design pattern is that you do not need hard Cody's map ings between senders and receivers. The number and type off receivers can be configured dynamically at runtime without breaking the pattern. Another advantage is that you can have multiple receivers handling the same request. Each receiver picks up the request, optionally modifies it. Andi hands it off to the next receiver. And finally, the pattern simplifies. Objects interconnections in your application architecture instead, off senders having to maintain references to all candidate receivers. Each center now only needs to keep a single reference to the heads off the pipeline, and each receiver only keeps a single reference to its immediate successor in the chain. The chain of responsibility pattern also has some disadvantages. There is a small performance penalty because each request needs to be passed down the chain of receivers, and the pattern increases the chance off. Unhand Aled requests. The performance disadvantage is relatively minor. Instead, off wiring up centres with their receivers directly. You are now using a chain off receivers instead. If the relevant receiver is all the way down the chain, then there will be a small overheads off redundant method calls. As the request is handed down the chain, this can negatively affect performance in Mission critical cold. Another disadvantage is that the pattern actually increases the odds off. Unhand aled requests. When you aren't manually wiring senders and receivers together, you can check at compile time that every request gets handled. But if the chain off receivers can be configured dynamically at runtime, then there is no way to guarantee that every request has a corresponding receiver. Incorrect configuration data can easily mess up the receiver pipeline. You need to be vigilant that every request always has at least one corresponding receiver in the pipeline. Here is the UML diagram off the chain off responsibility pattern. This is a fairly simple pattern, with only four participating glasses at the head off. The class diagram is the handler class, which acts as the abstracts based class for all requests receivers or hander's. The class defines one abstracts message called handle request, which will handle any incoming requests. The class also contains a protected reference to the next handler called successor. This reference connect the handler to the next handler in the chain. The reference will be no when we reach the final handler in the shame. There are two concrete's implementations off the handler based class called Concrete Handler one and Concrete under Two. Each concrete hander implements the handle request methods. So here's how that works. The clients calls the handle request message off the concrete founder at the head off the chain. The hander inspect the request to see if it's applies to this specific handler. If not, the handler passes the request on to the next handler in the chain by using the successor fields. If the handler is unable to process, the request on the successful fields turns out to be no. Then the 100 swords escalate the situation. He's gonna do this by calling a special escalation 100 so no one exception or log a warning or at our message. If the handler is able to process the request, then it performs whatever action is necessary to do so. Next, the handler inspects the request to see if it needs to be passed on. If so, it has the request to the next handler in the chain. But if not, then it simply doesn't nothing more. And the request stops propagating. At this point, I'm going to use the chain off responsibility pattern to implement a purchase bordering system. So in this example, I have a large company with executives that are authorized to buy stuff for the company. If you're a procurement manager, you were authorized to make purchases up to $10,000. But if you're the vice president's, then you can go much higher. Up to $25,000 on the CEO has the most spending power of all with an authorization to spend up to $100,000. So what happens when someone wants to buy something that costs more than $100,000? In our case, the CEO needs to call an executive meeting and get approval from the entire management team to make the purchase. So here's how you can visualize the company. I have a procurement pipeline that consists off the procurement manager. No vice president, I'm the CEO. New purchase requests are dropped off at the head off the chain with the manager. Anything the manager can't handle gets passed down the chain to the vice president, who then passes Unhand Aled requests to the CEO and anything the CEO can't handle is escalated by calling a meeting. I will implement the pattern with the following classes. Let's take a look at the coast. I'll start with E. P o Approval class. You can see here that it is a simple, abstract based class with a protected reference to the next approval in the chain called Successful Just like the UML diagram. There's also on abstract methods called process request, which you call to approve the purchase order. The methods expects a single decimal argument, which represents the total price off the purchase order. And here is the manager class. You can see that it derives from P o approval and implements the process request methods. The implementation is very simple. The handler checks the total price off the purchase order on passes the request up the chain if it exceeds $10,000. But if the price is $10,000 or less, then the handler processes the purchase order by writing a text to the console. And here is the vice president class. It is pretty much identical to the manager class. The only difference is the maximum authorized price. Here you can see that the vice president is authorized to approve anything costing $25,000 or less. And finally, here is the C E o class. The process request implementation checks the total price off the purchase order and processes. It's if it is $100,000 or less. But for anything above $100,000 the handler rights to the console that someone should invoke an executive meeting to approve the purchase. And here is the client's class called P O System. The class has a constructor that sets up a purchase order approval chain consisting of a manager, vice president and the CEO. And then we have this method here again called process requests, that receives a purchase order Request Ants passes it along to the head off the approval chain. Let me conclude with the main program, Mrs. Here, All it does is set up a new P O system. Instance on, then feeds three purchase orders into it. The first order costs $1000 the 2nd $20,000 under swords. $300,000. Okay, let me you run the program to prove to you that everything is working. I am compiling the cold now and I'm running the program. No. And there you go. The first order gets approved by the manager on the second order by the vice president, but the third order exceeds even the authority off the CEO who invokes an executive meeting to approve the purchase. Everything works. Okay, so here is a quick checklist you can use to implement that Shane off responsibility pattern . First, make sure you are unable to match the sender off a request to its receiver at compile time . Or that you want to map requests to multiple receivers. Then create an abstract based 100 class that declares the request interface creates Concrete's handler classes that implement the request interface. Have each handler past the request up the chain if needed. Define what should happen if no handler can process a request and finally creates a client class that sets up the chain off handlers and provides a message for submitting a request to the head off the chain. And here are some final comments. The chain off responsibility pattern can be combined with the compass its pattern. In this scenario, the chain off handlers is made up by the list Off answer stores of a given leaf requests are submitted at the leaf level and passed up to the components parent until they reach the rules components. The chain off responsibility pattern is part of a group of patterns that it shares with the command mediator and observer patterns. Each of these patterns allow you to decouple senders and receivers, but each pattern comes with different traders. You can combine the chain off responsibility pattern with the commands pattern and use command objects to represent requests. This will give you all the advantages off both the commands pattern on the chain off responsibility pattern. Okay, so here is a summary off what we have learned. The chain off responsibility pattern avoids strong coupling between the centre off a request, and it's receiver by giving a list off receivers a chance to handle the request. The pattern allows receivers to be configured dynamically at runtime, and more than one receiver can handle a request. A disadvantage off the pattern is that it increases the chance off. Unhand! Aled requests. The pattern is often combined with the compass. It's on commands, patterns 4. The command pattern: Here is the second behavioral design pattern from the famous Gamma Four Design Patterns book. This one is called Commands Pattern. Andi. It is a pattern you use when you want to encapsulate on operation as an object. L starts with a quick summary off what we're trying to accomplish with this pattern. The commands pattern is a good choice when you trying to accomplish the following. You have a client. Vance knows what needs to be done, and you have a receiver that has the resource is for doing it. You want to package operations into self contained objects and passed them from clients to receiver. Okay, let's go through these points one by one. The key intent off this pattern is that you have two distinct classes in your application architecture. A client's Onda receiver on the client's needs to invoke some kind off operation on the receiver objects the clients does not call. The receiver objects directly, but instead it creates a command objects. This is an object that defines the commands to be executed ons contains any required arguments. The clients then hands the command over to on in Voelker Objects, which executes the commands. The command is effectively a black box with a single execute methods when cold is in turn, calls low level receiver methods to perform the operation. Materializing commands into discrete objects means they can be transferred, shared, stored in a database ons otherwise instrumented or manipulated. Like any other objects, the commands pattern offers a number off benefits. The first benefits is that by materializing commands into objects, you gain the ability to store commands on. This allows you to queue operations or write them to a long file. And you can also store commands in an undue list, which allows you to implement undo on to redo operations. Another benefits is that the in Volker and receiver over commands are completely the couples you can change at runtime how a command is executed without the client's noticing. Here is the UML diagram off the commands pattern. The command class at the top off. The diagram acts as the abstract based class for all commands. It defines a single methods called executes, which will execute the command. There is a derived class called Concrete's commands, which inherits from commands on implements the execute methods. The class contains a reference to a receiver objects, calls well, receiver on it uses this reference in the execute methods you can see in the diagram that the concrete's commands class cools. A message called Action in the Receiver object to execute the command. The client class in Stan she hates the concrete's command on Initialize is it's with a receiver. Instance. It then hands me commands over to the invoke it objects. These objects finally executes the commands by calling its execute methods. In practice, you sometimes see the clients aren't invoca merged into a single object, which will both instance. Yet the commands invoke its execution. I am going to implement the commands pattern in a very simple culture Later application. My application will perform four mathematical operations. Addition. Subsection Division Sounds multiplication. I will use the commands pattern to implement each possible operation as a command objects by materializing the operations into discrete objects. I gained the ability to store the operations in an undue list on implements. On dual method, I will create a simple user interface, two input calculations which will act as the clients. The receiver will be a mathematical library that implements the four operations and keeps a running results, so I will implement the pattern with these classes. Okay, let's take a look at the codes. I will start with the must lib class, which acts as the receiver. It's a very simple class that declares four methods for the addition. Subtraction, multiplication on division operations. Each message expects a single integer arguments performs the request is calculation and updates on internal fields calls value. Now let's move on to the abstract operation class. You can see here that it is a very simple abstract class that sits up a single abstracts execute methods. This will be the message that executes the mathematical operations. And here is the Concrete's Commands class called Operation the Class and derives from abstract operation and implements the execute methods. So let's take a look at this constructor here. You can see that the constructor expects three arguments. The receiver off type must slip the mathematical operation to perform on the arguments to use the constructor stores. All three arguments in internal fields. When we look at the execute methods, you can see that the class uses the switch statements toe call the corresponding methods on the math library. Okay, Next is the interactive shell class which acts as the clients class. You can see here that there is a single run method that launches the shell. The class reads a single line from the console parses the input Aunt extract the operation on the arguments It then in Stan. She hates a command object from this data and passes it on to the calculator class. And here is the calculator class which acts as the in Volker. In this pattern, you can see here that there is a method called invoke which receives the commands on executed by calling its execute methods. But the calculator also stores the commands in this undo stack here on. By storing the commands, we gain the ability to introduce on undue operation. And here it is. The message pops the most recent commands from the stack. It then inverts the operation on executes in the modifies command. This will effectively undo that operation. Okay, let me run the program to prove that everything is working. I am compiling the codes now and I'm running the program now. Okay, so now the interactive shell is waiting for me to enter commands. I will start by adding 100 then subtracting 50 multiplying by 10 ons dividing by two, you can see the current value constantly updating from 0 to 1 hundreds to 50 to 500 finally to 250. Now I will undo the last three operations. I will press tilda ons the number three which the shell interprets as an undue off the last three operations. Here we go. And here is the results the calculator has undone. The final three operations on the current value has bean restored to 100. Everything works okay, Here is a quick checklist you can use to implement the commands pattern. First, create an abstract command base class with an execute methods, then creates one or more concrete's command classes that contain a receiver fields, plus a complete description off the operation to execute implements the execute method by using the receiver fields to call methods in the receiver objects. Instead, she eight's a new command. Objects for each deferred execution request hands the command objects over from the clients to the in Voelker and finally half the in. Volker decides when to execute the command. Okay, here are some final comments You can combine the commands pattern with the composites pattern, and this allows you to create Micro's. These are high level commands that are composed off a sequence off low level commands. The compass It's class represents the high level commands on its child's components by the low level commands. The command pattern is part of a group of patterns that it shares with the chain of responsibility mediator on observer patterns. Each of these patterns allow you to decouple senders and receivers, but each pattern comes with different tradeoffs. The chain off responsibility pattern can use command objects to represent requests as objects. This adds the benefits off queuing logging ons deferred execution to the benefits off the chain of responsibility pattern. Andi. You can combine the command pattern with the men mental pattern to maintain the current states often object on easily implements on undue operation. Okay to wrap up here is a summary off everything that we have learned in this lecture. The commands pattern in calculates operations as objects materializing commands into objects means they can be transferred, shared, stored Andi, otherwise instrumented or manipulated like any other objects. Now this lets you Q log, undo or redo commands and defer execution. The pattern can be combined with the chain off responsibility pattern to create chains off request handlers with Queuing Lanqing aunt and do capability. The pattern can also be combined with the accomplishes pattern to creates Mac Rose. 5. The interpreter pattern: This is the exert behavioral design pattern, and this one is called interpreter Pattern. It is a pattern you use when you are working on a problem that can be expressed in a domain specific language. The pattern provides an interpreter for that language. I'll start with a quick summary off what we're trying to accomplish with this pattern. The interpreter pattern is a good choice when you are trying to accomplish the following. You have multiple objectives that exists in a well defined on well understood domain. The objectives can be expressed with a simple language. Okay, let's go through these points. This pattern is off. Great help when we are working with so called domain specific languages, or D Sl's. A domain specific language is a simple language with its own grammar that describes a solution in a specific domain. A good example is SQL or structured query language. This is a custom language for retrieving on modifying data within the domain off a relational database. The language allows you to express complex operations. For example, a multi table join using a very simple grammar databases used on SQL Interpreter to validates aunt execute SQL queries. You can create your own custom language for any domain you want and use this pattern to build an interpreter. The interpreter codifies the language, grammar and syntax bulls and executes commands written in the language. The Interpreter pattern offers a number off benefits. First of all, the domain specific language provides a very compact representation for queries, commands or business rules. In the given domain. Complex operations that might require lots of executed ble coat can be represented with very simple key words or grammar rules. The pattern also introduces flexibility. The interpreter hides the complexity off the domain from the rest off the application architecture. If the domain changes for any reason, all you need to do is write a new interpreter to make your existing colds work with a new domain. The interpreter pattern also has a disadvantage. The interpreter masks the complexity off the problem domain from the rest. Off the application architecture clients only needs to express queries, commands or rules in a high level language, and they are completely shielded from the complexity off executing this language. So there is a risk that you are writing what appears to be an elegant aunts, compact language, expression but that the low level implementation off that expression is overly complex on does not perform well. Performance bottlenecks in domain specific languages can be very hard to track down. Here is the UML diagram off the interpreter pattern. The pattern uses a minimum off five classes at the center, off the diagram or three expression classes. The term expression in this pattern refers to a rule keywords operation or literal in the domain specific language. There are two kinds of expressions. A terminal expression is an expression that does not refer to any other expression. For example, in mathematical expressions, a number is a terminal expression. It's on independent symbol that does not relate to or operate on other parts of the expression. The other kind of expression is a non terminal expression. This is an expression that refers to one or more sub expressions in the language. A good example is the mathematical plus symbol. It adds to some expressions together, the one with the left off the plus symbol and the one on the right to build a basic mathematical expression interpreter. All you need to do is create one terminal expression class for a no medical constant and four non terminal expression classes for the plus minus multiply on division operators. Okay, back to the classes. The abstract expression acts as the base class for all other expression classes. In the language, you can see that there are two classes derived from abstract expression. They are terminal expression on non terminal expression. These corresponds to the two types of expressions we just discussed. Each expression class has an interpret method that executes the expression. The method receives a context which contains the global states Off the interpreter. Each expression performs a specific operation, and optionally reads and updates the global states to reflect that operation. Finally, we have the clients class. It holds a reference to the language context. On initialize is an expression three, which is a hierarchy off terminal aunts, non terminal expressions that define the syntax and grammar off the domain specific language To execute a language commands. All the client's needs to do is initialize the context ons provided in a call to the interpret methods off the top. Most expression in the expression tree that expression classical, then cool. The interpret methods off other expressions to process the language commands sometimes you see one extra class in the pattern called a partial. This is a special purpose class that parses the language and builds an expression tree from its I will show you a simple passer, in my example. So let me clarify the pattern a little further. By showing you a concrete example, I am going to build on interpreter for processing mathematical expressions to make it easy on myself. I am going to process reverse Polish notation. This is a mathematical language where all numbers get pushed on the stack on all mathematical operators process values. On that stack, for example, take the expression five plus 40 to minus 10 so we know the answer is 37 in reverse Polish notation. The expression looks like this. Five 42 10 minus plus. So here's how that works. First, the number five it's pushed on the stack, then the number 42 then the number 10. Next is the minus operator, which simply takes the two top most numbers on the stack, substrates them and pushes the results back on the stock. So in this case, the operator sub strapped 10 from 42 and pushes the number 32 back on the Stuck. Finally, the plus operator takes the two top most numbers on the stock, which are now £5.32 and after them together. So the final results is 37. I am going to build a very simple reverse Polish notation interpreter that's can interpret expressions with inside your numbers on one off the four basic operations Addition subsection multiplication. I'm Division I will implement in the pattern with these classes, notes the extra parcel class. I will add it to the solution so that I can interpret a string containing R P en expressions. Okay, let's take a look at the code. I will start with the abstract expression class, which is nothing more than an abstract based class that declares the interprets methods. You can see that the methods does not expect any arguments because my interpreter has no global states. The miss. It does return an integer, and this is the new medical result off the expression. And here is the number class, which is derived from abstract expression. You can see that it has a constructor for initializing the class with a specific integer. The interpret method simply returns that interview. Very simple. So let's move on to something more complicated. Here is the ads class. It has a constructor that expects to sub expressions to add together the interpret methods , calls the interpret methods off the two sub expressions to get their values on, then simply adds these values together and returns the results. All other non terminal classes work exactly the same way, but each uses different operator. Okay, and finally, here is the partial. There's a parse methods here that receives a string. This is the text representation off the R P en expression. The parcel splits the string on the space character, and it'll rage through each words. Anything that is not a mathematical operator is treated as an interview. The boxer farces the integer, creates a number expression and pushes its on an expression stock. Now look at this cold here. If the current words is a plus character, then the partial pops the top most two expressions off the expression stock creates a new ad expression with these two sub expressions ons pushes the at expression back on the stack , so this codes actively builds on expression tree by parsing the input string ons producing on expression three in memory To execute the expression. All I need to do is cool. Interprets on the top, most expression on the stack and captured the return value. Okay, let me run the program to prove that everything is working. Fine. I'm compiling the cold. No, on. No, I'm running program. Okay. The program is now asking me for an rpm expression. I will type the same one I used before. So 5 42 10 minus plus. And there you go. The answer is 37. Everything works. Here is a quick checklist you can use to implement the interpreter pattern. First decides if a domain specific language offers a justifiable return on investment, then define the grammar for the language map. Each grammar rule to an expression class organized the expression classes into a hierarchy similar to the complicit. Possum decides if you need a global interpreter state. If so, put it in the context class optionally not a partial to build an expression three from a language string. And finally, half the clients use either the parcel or a pre built expression tree to execute language commands. And here are some final comments if you are still wrapping your head around the code example I showed you, then here's a diagram that might make things more clear. I types of the following expression on the console. 5 42 10 minus plus. And this is the expression tree that the pressure made from it. You can see that the final act operation is at the top off the tree. By calling its interpret methods, I can execute the entire expression and get the final results off. 37 each non terminal expression in the tree recursive Lee calls the interpret methods off its sub expressions to assemble the final results. If the interpreter has a very complex global states, you might consider using the state pattern instead of the simple context objects. And for very large expression trees, you can consider using the flyways pattern to share instances of terminal expressions. Okay, so here is a summary off what we have learned. The Interpreter pattern provides an interpreter for a domain specific language. You can adds a part, sir, to build the expression tree from a language string. The pattern provides a very compact representation for queries, commands or business rules in the given domain, but it also masks the complexity off the problem domain from the rest off the application architecture, you can combine the interpreter pattern with the states or flyways patterns. 6. The iterator pattern: here is the fourth behavioral design pattern from the famous gang Afford design patterns Book. This one is called iterated Pattern on, and it is a pattern you use when you want to access the elements off a collection sequentially without exposing its underlying representation. I will start with a quick summary off what we're trying to accomplish with this pattern. The iterated pattern is a good choice when you are trying to accomplish the following. You have a collection off elements you want to sequentially access each element from start to finish. You want to hide the underlying representation off the collection. Let's go through the points one by one so two starts. We need to have a collection of elements. This could be a simple data structure, like a list what array. But it can also be another design pattern, like the composite pattern. The key concepts is that the collection has one or more elements. This starts under finish, and we wants to sequentially access each elements most built in data structures like of the array on the list already provide supports for alteration. We only need this buzzer to enable its oration on data structures, dance and do not support it out of the box. The iterated pattern offers a number of benefits. The most obvious benefit is that the pattern provides it aeration for data structures that themselves do not provide it. With the pattern in place, you can step through the data structure just as if it were any other collection or list. The pattern also lets you define more than one type of its aerator. For example, in a three data structure, you could implements both breaths first and depth. First, it aerators with this matter without polluting the data structure with methods for the difference kinds of traverse ALS. The pattern also provides for more than one pending traverse away on the same list. This allows you to use the iterated pattern in scenarios where multiple threads needs to access elements in the same shared collection. And finally, the pattern provides a uniformed interface for traversing many types off elements objects. This saves you from having to build distinct iterated er's for every possible data type. Here is the UML diagram off the iterated pattern. So here's how the pattern works. We have some kind off aggregates class in our code that contains a collection off elements that we want to sequentially access. The collection class is called Concrete's Aggregates. In this diagram on you confined, it's on the left off the middle. The picture. The concrete aggregates class is derived from an abstract based class called aggregates that sets up the iterated pattern interface. The base class defines a method called Creates iterated on the derived concrete aggregates class implements the message. The create It'll razor message returns a new Iterating instance. This is a specialized class for sequentially accessing each elements in the collection. We can find the interface off the iterated class in the top, right off the diagram in the abstract. It's aerator class this class and defines four members for accessing the elements in the collection first for resetting the iterated toe. The first elements in the collection, next for moving the iterated to the next element in the collection, is done for detecting. If we have reached the final elements in the collection, Ham's current item for retrieving the current elements with these four members, the clients can sequentially access each elements in the collection. A client's starts by calling first to move the iterated er to the first item in the collection. Then, for as long as the is done member is false. The clients reads the current item fields and calls next to move the iterated er toe the next elements you can see in the diagram. That's the abstract. Iterated based class defines the interface Aunt. There can be many concrete implementations off the iterated. One implementation called Concrete It's a razor is shown in the diagram. This is the class that is returns when you call The Creates its razor message on the concrete aggregates class. The dot net framework has a specific implementation off the iterated pattern that is pervasive throughout the entire base class library. Each collection class implements a special interface called I indomitable. This is the equivalent off the aggregates based class in the iterated pattern. The interface allows you to create an iterated ER for the collection. It's aerators in. The nets also have a special name. They are cools enorme aerators, and so the message to create one is not called create its aerator but gets the numerator in operators. Indoor nets use an interface instead of an abstract based class, and it provides the following fields for sequentially, accessing elements in a collection move next for moving the iterated er to the next element . This also moves on initialized it aerator to the first elements, and the message returns false. If there are no more elements available in the collection, um, currents for retrieving the current elements with these two members, the clients can't sequentially access each elements in the collection. A client's starts by calling Move next to move the iterated ER to the first item in the collection. The message will return false if the collection is empty. If the message returns true, the clients will keep reading the current fields and calling the move next methods until the messes returns false. You can see that the dot net implementation off the iterated interface is slightly more compact, using only two fields to achieve the same results. When you use the Ford each keywords in C short. The process that I just describes is exactly what happens behind the scenes. The C sharp compiler does allow the heavy lifting for you by creating a new in numerator instance on setting up a loop to sequentially call than move next message and read the current fields to access all elements in the collection. Okay, I am going to implements a very simple iterated er with the following classes. Let's take a look at the code. I will start with the concrete aggregates class called my collection. In my example, you can see that it is a simple class with three protected fields, cold field, a field be that's feel See aunt, a constructor for initializing these three fields I I'm going to create on in operator. So that's I can use the for each keywords to sequentially step through these three fields. So the first step is to implement the I innumerable interface. You can see up here in the class definition. That's I implement the interface. Hands down here is the get in numerator message which returns a new instance off the my collection in numerator. And here is the my collection in operator class. You can see that it implements I in operator. The implement is interface members are down here. I use a simple interred your state value to step through the three fields. Aunt, I use a switch statement in the current property to return the correct value. Now that both the indomitable aunts. I in numerator interfaces are implemented. I can access the collection with the for each statements. Check out this cold here. The main program message. I use a for each loop to directly access the fields in the my collection class. Justus, if this were a regular collection class Okay, let me run the program to prove that everything is working. I am compiling the codes. No, and I'm running the cold. No, There you go. All three field values appear on the console. Everything works. Here is a quick checklist You can use first implements the i innumerable interface on the collection class. Then design on in numerator class that implements the I a numerator interface. Have the I in honorable dots gets in numerator method return a new in numerator instance. Now it's finally have clients use a for each loop to sequentially access each elements in the collection. And here are some final comments. By combining the accomplish its pattern with the iterated pattern, you add it aeration support to a three data structure. The interpreter pattern uses a data structure very similar to the composite pattern. If for was every reason you need sequential access to every expression in the interpreter expression tree. Then you can combine the interpreter pattern with the iterated pattern to make this possible. If you need to create specific iterated hours, depending on external or runtime circumstances, then you can combine the iterated pattern with the factory message batter to create the correct type off iterated er in the gets in operator methods. You can also use the no mental pattern in combination with the iterated pattern on it. Aerator can use a memento to capture these states, often inspiration. The Little Razor stores the memento internally. Okay, so here is a summary off what we have. Lawrence. The iterated pattern provides sequential access to the elements off a collection without exposing its underlying representation. The iterated pattern is pervasive in the dot net framework, but it's aerators are called in operators. The I innumerable interface acts as the aggregates based class Sonthi I, in numerator interface, acts as the abstract. It's aerator class. The Net framework uses a compact. It's aerator interface with only two members. Currents sounds move next, you can combine the pattern with the interpreter or complicit pattern to provide sequential access to expressions that's complicit. You can combine the pattern with the factory method pattern to create custom iterated hours , depending on external or runtime information. 7. The mediator pattern: This is the fifth behavioral design pattern from the gang or four design patterns book. This one is called Mediator Pattern Andi. It is a pattern you use when you want to set up loose coupling between a group off objects by keeping them from referring to each other directly. I'll start with a quick summary off what we're trying to accomplish with this pattern. The mediator pattern is ago. Choice. When you are trying to accomplish the following, you have a group off objects that need to refer to each other. Exactly how the objects should interact is not known at compile time, or it may change and run time. You want to direct all interactions through an intermediary. Okay, let's go through the points one by one. The key issue is that you have a group of objects that needs to interact with each other. But the specific pattern off interaction is not known beforehand, or it can change on the fly, perhaps because you're adding or removing objects from the group at runtime or because the pattern off interaction between the objects changes due to external circumstances. If you try to cold this behavior into the objects directly, you will get a very complex spaghetti off references between objects. You will also need to add codes to each objects to keep the references of today's. Sure, you can put this code in a common base class, but what do you do if the objects in the group have different based classes? You don't want to duplicate cold. The mediator passer is the solution to this problem. Instead, off having the objects referred to each other directly, they instead only refer to the mediator. Each objects communicates its intense. Only to the mediator on it is the mediator, which then notifies other objects. The mediator acts as a communication hub between all objects. Hands keeps all objects references up two days. The mediator pattern offers a number of benefits. When you use the pattern, the objects no longer have to reference each other directly in projects with lots of objects. With complicated inter relations, the pattern will concentrate this complexity into a single mediator object. This simplifies your cold enormously. The pattern also helps you handle changes in the network off object references when the reference network needs to change. For whatever reason the mediator can handle is directly. The objects do not need to be aware off any change. This again simplifies your coat on. Prevents colds and duplication. The mediator pattern also has a disadvantage. You might be tempted to set up a mediator object to handle communication between all objects in your application architecture. You could set up a messaging framework or a service bus and have your entire application interact through this single communication hub. On paper, this seems like a very clean architectural. However, when you do this, you are concentrating all communication logic off an entire application into a single object. This object then effectively becomes a god object on all knowing and all seeing objects that manages all aspects off your application. A gold object is an anti pattern. When you are concentrating too much functionality into a single object, then you are no longer using the benefits, often object oriented architectures. You are also introducing a single point of failure on, and you were making your codes much harder to read and maintain. Here is the UML diagram off the mediator pattern. The communicating objects are called colleagues in the terminology. Off this pattern, there is one abstract based class called colleague that holds a reference to the mediator objects. We also have to concrete derived classes called concrete colleague, One armed concrete colleague, too. These classes inherit the mediator reference from the colleague based class. Note, by the way, that you do not need to derive all colleagues from the same base class. All you need to ensure is that each concrete colleague holds a reference to the mediator on that there is some kind of mechanism to initialize this reference. A parameter arised constructor is the most common way to do this. So if all of your concrete classes contain the reference on the constructor, then you do not need a common based class on the left. Off the diagram is the mediator hierarchy. There is an abstract based class called Mediator that defines common functionality. This is useful if you intend to have more than one mediator. The concrete's mediator class inherits from mediator and implements the mediator functionality. All logic pertaining to communication between the college classes is here. In this class, the concrete mediator holds references to every single colleague class. Andi can implement complex communication patterns between the colleagues. I am going to demonstrate the mediator pattern by writing a simple chat room application, I will sit up a single chest room where visitors can join and leave. Every time a visitor sends a message, it is broadcast to all current members in the chat room. You can see why I need the mediator pattern in this example. Rebels, the mediator class I would need each visitor to hold a reference to every other visitor in the chat room. The reference map would look like this. Every time someone enters the chatroom, I need to add the reference toe all other visitor objects. And every time someone leaves the chatroom, I have to remove the reference. That's a lot of work. Now look at the mediator pattern. All visitors simply holds a single reference to a mediator object. The mediator is responsible for keeping all objects references up to date. This simplifies the cold enormously. I will implement the pattern with the following classes. Okay, let's take a look at the code. I'll start with the abstract visitor class. You can see that it contains a field off type abstract chat room. This is the reference to the mediator object, and there's also the fields called name, which contains the name off the visitor. And here are the message declarations. There's a send method for sending a message to the chancel. You can see that the implementation simply calls the sends message off the chattel. There's also on abstract receive methods for receiving messages from other visitors. This method will be implemented indeed derived visitor class. There are two more methods. Enter and leave. These are for respectively entering and leaving the chance room. You can see from the implementation that these methods call the register on unregistered methods off the chat room class. The concrete implementation off the chancellor visitor is here. The class is simply called visitor and it derives from abstract visitor. There's a constructor here for initializing the name off the visitor. And here is the implementation off the receive methods. You can see that my codes simply writes the received message to the console. Okay, now let's take a look at the mediator classes. Here is the abstract chattering class, which is an abstract base class that defines three abstract methods sent, ready, sir and unregistered. There's also a field here called active Visitors. This feels contains a list off all the active visitors in the chat room. The concrete chattering class is here, simply called chat room. It derives from abstract chat room and implements all three methods. Let's take a look. I'll start with the register methods. You can see that it is very simple. All he does, he's adds the visitor to the list off active visitors in the chatroom. And here is the unregistered methods, which removes the visitor from the list. The send methods gets called when a visitor wants to send a message to the chance room. The implementation simply calls the receive methods for every active visitor in the chat room. And here is my main program class. The main program message sets up a chat room with three visitors. Tom Dick, That's Harry. Then Tom sends a message to everyone in the chatroom on both Dick and Harry would apply. Let me run the program to prove that everything is working. I am complaining the colds. No. And now I'm running the program. I'm There you go. Dick and Harry received Tom's message. Tom and Harry received dicks. Reply on. Tom and Dick received Harry's reply. Everything works okay, here is a quick checklist that you can use to implement the mediator pattern. First, identify a collection off interacting objects that would benefit from loose coupling, then encapsulates all objects. Interactions in a new media or class re factor. All colleague classes to only interact with the mediator object. And finally, half the mediator dynamically reconfigure the object interactions when necessary. And here are some final comments. The mediator and observer patterns are very similar, both decouple senders and receivers. The difference between them is that observer introduces more structure in the observer pattern. All participating objects are clearly separated into two groups, observers and subjects. The mediator pattern makes no assumptions about the roles of participating objects. Hans is therefore more flexible but also less reusable. You can also combine the mediator and observer patterns in this combines pattern. The mediator object is responsible for object interactions, and you use the observer pattern to register unregistered aunt communicate with participants. Okay, here is a summary off what we have learned. The mediator pattern sets up loose coupling between a group of objects by keeping them from referring to each other directly. The benefits off the mediator pattern is that it simplifies the map off references between participating objects. The disadvantage off the pattern is that the mediator can turn into a God object. The mediator and observer patterns are similar, but observer is more structures than mediator. This makes Mediator more flexible, but also less likely to be reusable. 8. The memento pattern: here is the sixth behavioral design pattern, and this one is called Mental Pattern. It is a pattern you use when you need to capture and externalize on objects internal state so that the objects can be restored to this state. Later I'll start with a quick summary off what we're trying to accomplish with this pattern . The mental pattern is a good choice when you are trying to accomplish the following. You want to capture on objects internal state so that the objects can be returned to the States later. You want to externalize the objects internal states in a safe manner. You want to promote, undo or restore functionality to full objects. Status. Okay, let's go through these points one by one. In this pattern, I am working with one or more objects with internal states in the terminology off the pattern. These objects are called the originators. The state information is private through the originator and must not be readable or right herbal by any other objects. However, this poses a problem. If I want to implement on, undo or restore operation on application, architecture with a new capability needs to keep a history list off away prior object states. The history list is owned by another object called the Caretaker. So to implement the undue operation, the caretaker needs to look up the corresponding state records in the history table and then apply it to the originator objects. But how do I do that if the object states is private and can only be accessed by the originator itself? The mo mental pattern solves this problem. A memento is a kind off rapper that encapsulates the state information and makes it suitable for exports a Mementos. Internal states can only be accessed by the originator, but the momentum object itself can be freely passed on to the caretaker objects. This pattern allows you to reads and update the states off the originator without making this state's publicly visible throughout your entire application architecture. The benefits off the memento pattern is that it provides a generic way to capture object states and store it somewhere else. The memento who wraps the object states information that makes it suitable for export, but it also protects the state information by ensuring that only the originator can access it. The mental objects can now be stored in an undue list or a history table without the caretaker objects requiring any knowledge about the state information itself. The momento acts as a black box that perfectly encapsulates a single state record. You can undo the originator to a previous state by handing the memento back to the originator. The originator will then crack open the mental objects, extract the internal state and loaded to implement the restored. Here is the UML diagram off the mo mental pattern. There are three classes participating in the mid mental pattern. The originator, which is the object with internal states. The caretaker, which is the object that controls when state is saved and restored. And the Memento, which is the state or rapper that is reds and written by the originator and handled by the caretaker. So let's start with the originator, the originator, as private states represented in the UML diagram with the private field called ST. There are also two methods creates momentum for creating a new momentum instance containing the current states and since my mental for restoring the states by using the provided mental instance. The Memento class also has a private state, fields, which contains a snapshot off the originator States at the time the momentum was created. There are also to get state on set state methods. The originator uses these methods to initialize, anouma, mental or read the states from an existing mental. And finally we have the caretaker objects. This can basically be any objects that needs to hold on to state information. The object has a reference to one or more momentum instances and calls the set memento methods off the originator objects whenever a restore needs to a cure, I am going to implement the momentum pattern by creating a simple document editor. My editor supports text inputs on a few basic HTML formatting operations. There is also a separate objects called documents history that maintains a complete history . Off the documents, Aunt supports a restored operation. I will implement the passer with these classes. Okay, let's take a look at the code. I will start with the documents class. You can see here that it is a class with a protected Stringfield called HTML. This fields will contain the full HTML text off the document contents on here are a couple of message for manipulating the content off the documents. There's an depends methods for a pending text to the documents. There's an italic missus that lets you former the entire documents in italics, and there is a bold methods that lets you format the entire documents in bolt Hands down. Here are the momentum methods the safe state methods captures the current state's off the documents, wraps it in a new document, state instance and returns the instance. So this is my mental objects. The complementary load states methods does the opposite. It receives a document state instance. In this parameter extract, the state information from this momentum ons assigns it to the HTML field, and this effectively implements a restore operation. And here is the document States Class, which acts as the mental objects. It's a very simple object with a single Stringfield here, which contains a snapshot off, the document states. There's also a public property here called states, which the documents class can use to read the state information. But did you notice the cool trick I used? Look here. The Safe States method creates anouma mental objects, but it returns the objects as a project type on the document State class here, it's actually embedded inside the document class and it's a private class, too. What's going on here? Well, this neat little trick makes the elemental completely unreadable to the outside world. By making the documents state class private ons local to a document, I ensure that it can only be accessed from inside the documents object itself. So now safe methods must return the memento as an untied object because the outside world cannot access the document states class declaration. So nobody except documents can cast the memento back to a document. State instance. Okay, now let's take a look at the documents history class. You can see here that it contains a list calls history that's contains the current and all preceding document states. There's a snapshots method here that creates eight men mental off the current's document states on stores it in the history list on this restore message here restores the documents to a specific states. You simply provides the index number off the history list records, and the object performs the restore to that specific states. That's finally here is the main program methods I starts and by initializing a new documents, filling it with text and then performing italic and bulls for mating operations on the text . You can see that I call the snapshot method after each operation to fill the history list. Then I restore the documents to history records one which will bring it back to unformed. It'd texts. But then I do another restore to history records too. And this brings the documents one step forward to italic text. Let me run the program to prove that everything is working. I'm combining the coast. No fans know I'm running the program. Here we go. There you have it. First I get unformed text and then I get the italic text. Everything works. Okay, Here is a quick checklist you can use to implement the no mental patter. First identify the originator class that needs to save and restore state. Then identify the caretaker class that needs to control when states is saved and restored. Creates a memento class with encapsulated state information. Add create memento on set mental methods to the originator class as finally half the caretaker take snapshots off the originator and in vogue restored operations. And here are some final comments. The biggest issue with this design pattern is how to ensure that the encapsulated state information in the memento class can only be reds by the originator class in C plus. Plus, you would use the friends keywords, but unfortunately, C Sharp has no direct equivalent. However, there are a couple of strategies you can use to shield access to the state information. You can use the same trick I used in the example. You make the memento, plus a private subclass off the originator and have the originator return momentum instances as untie popped objects. The caretaker will now not be able to cast the memento because it cannot access the private no mental class declaration. If you don't like nesting classes, then you can also make thema mental class internal. If the caretaker resides in another dot net assembly, it will not be able to access Lee Internal, the men's or class declaration. You often see the commands on DMA mental patterns used together, a commands can use a memento to maintain the states requires for performing on undue operation. And finally, Memento is often used together with its a writer, and it's a razor can use a memento to capture the states often inspiration. The iterated ER stores the memento internally Okay, so here is a summary off everything that we have learned in this lecture. The memento pattern lets you capture on objects internal states, so that is can later be restored to the state. The pattern provides a generic way to capture object states and store it somewhere else. You can either nest the memento class or make it internal to protect its contents. The mental pattern is often combines with the command and iterating patterns. 9. The observer pattern: This is the seventh behavioral design pattern from the famous gang before book. This one is called Observer Pattern. Andi. There's a pattern you use when you want to define a dependency between objects. So that's when one object changes. States all its dependence are notified on updated automatically. I will start with a quick summary off what we are trying to accomplish with this pattern. The observer pattern is a good choice when you are trying to accomplish the following you're objects coming groups in subjects with a fluids, internal states and observers that must be notified when subjects change state the number and type off. Observers can change dynamically at runtime. You once loose coupling between subjects and observers to AIDS scale ability. Let's go through the points one by one. So in this situation you have an application architecture with one or more subjects, objects with fluids, internal states, meaning the states can change at any given time. But you also have another group of objects that need to be notified. We never the subjects change. The easiest way to do this is by simply referencing the objects directly. Every subject references every observer whenever a subject changes. It calls the observers directly to notify them off the state's change. But there are two problems with this solution. First, you need to know every possible combination off subjects and observer. That's compile time. The solution breaks down. If observers can be dynamically added or removed at runtime and seconds, you are creating a very tight coupling between the subjects on the Observer's. These restricts this capability off your architecture. The observer pattern solves these problems. It provides a way to dynamically connect subjects and observers together instead off statically referencing the objects at compile time. The pattern allows you to do this as runtime, using attach and detach methods. There are two ways in which subjects objects can broadcast a change in their internal states to other parts of an application. The push model, where subjects directly call all observers on notify them off the change states or the pool model, where subjects signal that the state has changed on observers, then retrieve the changed states themselves. The observer pattern is a pool model, and it offers a number of benefits over the push model. First of all, the observer pattern is more flexible than the push model in the push model. These subjects needs to know exactly which observers needs the new states. But in the observer pattern, the subjects Onley signals that's new state information is available. The observers then decide on their own if they need to retrieve it or not. The pattern puts the cold that the sides, whether to retrieve the new state information exactly where it belongs in the Observer's. This also makes the pattern much more scalable than the push model. When you're adding new types off observers at run time, all you need to do is register them with the subject to make them work. Contrast this with the push model, where the knowledge on how to deal with new types off observers needs to be added to the subjects. The observer pattern creates a loose coupling between subjects and observers on this makes the application architecture much more scalable. The observer patter also has some disadvantages over the push model. For starters, it is slightly less efficient In the push model, the observers received both the notification or the change and the new state data in a single method cool in the observer pattern. However, these subjects only sends a notification. It is then off to the observers to retrieve the new state information. This requires one extra method call. Another disadvantage is that the passer has a fairly narrow focus. It cannot deal with subjects, states that rapidly changes or observers listening to multiple subjects. If these scenarios occur in your application architecture, you're going to have to modify the pattern. And finally, the pattern may introduce a memory leak. The subjects keeps references toe all active observers, so an active observer can never be garbage collected. Even when it goes out of scope, you have to explicitly unregistered The Observer to enable it to get garbage collected. If you forget this, you will clutter the with stale observers. Here is the UML diagram off the Observer Panter. So here's I would works. The subject is in the top left hand corner. Off the diagram. There's an abstract based class called Subject that declares three methods attach for attaching an observer to the subject. Detach for detention and observer from the subject Hands notified, which will notify all attached observers. There's also a concrete subject. Class calls concrete subjects, the class declares on internal state in a field called Subject States, and it contains a measure called Get States for Retrieving the State. The observers will call this message directly to retrieve the new states. The Observer is in the top right hand corner off the diagram. The abstract based class observer declares a single update method. The subjects will call this message directly to notify the observer that its state has changed. There's also a concrete observer cooled Concrete's Observer. The class tracks the subject states in an internal field called Observer States. The class also implements the update methods. The methods calls these subjects get state methods to retrieve the new state information on stores. It's in the observer States field. So here's how the complete sequence works. Any observer that wants to be notified registers itself with the subject by calling the attach methods. When the subject's changes, it will call the updates methods on all attached observers. Each observer will then call the get state methods to retrieve the new state and stories in the object states fields. This sequence ensures that all objects state fields stay in sync with these subjects, states fields the DOT net framework has a specific implementation off the observer pattern that is pervasive throughout the entire base class library. The framework uses events to implement the pattern. Here's how that works. Events are dynamic method references. You can point on events to a specific message on when you call the events. You what actually calling the underlying message to implement the Observer password. The first thing you need to do is declare a delegates with the correct events signature like this. The nice thing about this signature is that the first method arguments clearly identifies the subject, so there is no needs for the Observer to keep a reference to the subjects on the second method. Arguments is an optional data value. You can use these arguments to store the subject states. Do you remember the disadvantages off the observer pattern? It's less efficient than the push model. Andi. It's hard to have an observer. Listen to more than one subject. Well, this specific implementation solves both problems. Okay, the next thing you need to do is declare on events like this to make this work the updates methods needs to match this signature exactly like this. So now each observer can register it's update messes with the subject like this. When the subject calls the notify events, all the observers update methods are cools. If you have the subjects, puts the new states in the data value, then you do not need to make that seconds method. Call to retrieve the state. And if you connect one observer to several subjects, it's can use the first arguments to tell them apart. Okay, let me show you a very simple implementation. Off the pattern, I will build a simple timer class that notifies its observers once every second, I'll add an observer that writes the current time to the console. I am going to use the following classes. Let's take a look at the coast. So here is the timer class it contains one public event feels called notifying. This is the events that will know to try the observers every seconds. There's also start methods that uses the threads to fire the notify events once every second, and this is the observer class, it declares a message called updates that matches the signature off the notify events in the subject. The method writes the current time to the console, so all we need to do now is Register the console clocks, update message with the timers. Notify events to make the time. Actually, call the console clock. And this is where that happens in the main program message Here. You can see that I first instance she ate the timer and then the console clock. And then I attached the update method to the notify. Events like this. This simple line of codes are ready stores the update methods with the notify events. Now, every time the events fires, it will call the update message. Let me run the program to prove that everything is working. I'm compiling the code now and I'm running the program. No, There you go. The current time appears once every seconds on the console. Everything works. Here is a quick checklist you can use to implement the observer pattern. First identify the subjects ons observer objects then at a public event fields to the subjects hands a public updates message to the observer that matches the event signature. Have each observer adds it's updates methods to the events field. Have these subjects call the events when the internal state changes and finally decides If you want the subject to push states to the observer's or if the observers pull what they need from the subject. And here are some final comments. The mediator on observer patterns are very similar, both decouple senders and receivers. The difference between them is that the observer patter introduces more structure in the observer pattern. All participating objects are clearly separated into two groups, observers on subjects, and therefore the pattern is less flexible but more reusable. You can also combine the mediator and observer patterns in this combines pattern. The mediator object is responsible for object interactions on you. Use the observer pattern to register on register hands, communicates with participants. Okay, here is a summary off. What's we have learned in this lecture? The observer pattern defines a dependency between objects, so that's when one object changes. States all its independence are notified and updated automatically. The observer pattern is flexible and scalable on his can easily deal with new types off observers. The pattern is slightly less efficient than the push model on it may lead to memory leaks. The DOT net framework implements the observer pattern. With events, you can combine the observer patter with the mediator pattern 10. The state pattern: Here is the eighth behavioral design pattern from the famous gang Off Four Design Patterns book. This one is called ST Pattern, and it is a pattern you use when you need an object to alter its behavior. When its internal state changes, we'll start with a quick summary off what we're trying to accomplish with this pattern. The state's pattern is a good choice when you are trying to accomplish the following, you have an object that cycles through two or more discreet internal states. The behavior off the objects radically changes with each state transition. Let's go through the points one by one. In this scenario, we have on objects in our application architecture that's cycles through a number off internal states. These states can be very abstract. For example, something like Idol connecting connected, disconnecting arms, error. Each state's is only accessible from a limited number off proceeding states, For example, you can only transition to the disconnecting state from the connected state. So far, so good. The second requirement is that the objects radically changes its behavior based on the internal state, so the same methods behave very differently For different states values. You can code this my hands by putting switch statements in each object methods burns. The disadvantage is that the code that corresponds to a single state is now spread out over all methods in your object. If you have lots of states with complex states transitions, then things can get complicated really fast. The state pattern solves this problem. The pattern concentrates all coats corresponding to a single state into a single state class. It also makes each state's responsible for selecting the next states in the cycle for large state diagrams with lots off complex transitions. This simplifies things enormously, so we've talked about the benefits off the state pattern. The pattern concentrates all codes corresponding to a single state into one state object. This eliminates all complex switch statements That's you it needs if you do not use this pattern. The pattern also makes each state's responsible for selecting the next states in the sequence again. If you do not use the pattern, you would have to place this cold inside. Switch statements in each object methods. The pattern allows you to place the cold in the most logical place. The state class. The state's pattern scales really well, and it can handle very large state diagrams with lots of complex transitions. But the pattern also has disadvantages. First of all, this pattern is a trade off. The pattern concentrates all coat corresponding to a single state into one ST class. But sometimes this isn't what you want, because the pattern also spreads out the cold off a single operation over many state classes, which can make the codes hard to maintain. Another disadvantage is that you need to be very careful that each state has a reachable successor states. It is very common for state machines. Toe hand in a specific states with no way out. You need to carefully design your state transition diagram to prevent this from happening. Okay, here is the U. N. L. Diagram off the state's pattern. I will start with the state's class. This is an abstract based class that declares the methods that need to change their behavior due to changes in the internal states. In the diagram, only a single method has been joined. Calls handle the miss. It takes a single argument, which is the reference to the currents context. There are two classes derived from states called Concrete State a and concrete state be both classes, implements the handle method. Each concrete states does whatever it needs to do to handle that states and then changes the current state's off the context to the next states. For example, Concrete state. A good change, the context states to concrete state Be. Then, when the context class calls the handle message on Concrete State be, it could change the state's back to concrete state. A. This would create a state machine that is constantly cycling between these two states. The Context class is in the top left corner off the diagram. This class has a public interface that is exposed to clients. The class also has a private state field that tracks the current state of the context. In the diagram, The public interface consists off a single Mrs called request. When clients call the request methods. The context class calls the handle methods off the current state. The state's does whatever it needs to do to handle the current state, and then it modifies the context to change the current state to a new value. This pattern constantly changes the behaviour off the request methods as the current state's off the context cycles through all possible values. I am going to use the state's pattern to implement the software for a chocolate vending machine. My machine will be coin operators. After inserting one euro coin on pressing a button, the machine dispenses a single chocolate bar. I will create a class to represent the vending machine with four methods for inserting a coin, ejecting a coin, pushing the bosom and dispensing a chocolate bar. The state classes will change the behavior off these methods based on a constantly changing internal states. My states will transition according to the following pattern. From no coin to coin inserted two souls and then to either no coin again or to sold out. I will implement the pattern with the following classes. Okay, let's take a look at the code. So here is the abstract state based class. You can see the four methods here implemented as abstracts methods that must be implemented in the derived state classes. Let's start with the no coin state. Inserting a coin advances the vending machine to the coin inserted states. All other methods won't work because no money has been inserted yet. Here is the coin inserted States from these states. You can press the button to buy a chocolate bar, and this will advance the vending machine to the sold state. But you can also choose to reject the coin and get your money back. This will advance the vending machine back to the no coin state. And here is the sold states in this state's only the dispense method will work. It dispenses the chocolate bar on advances. The vending machine states back to the no coin states. That is, unless the machine runs out of chocolate bars. If that happens, the next state will be sold out. And this is the sold out state in this state's known off. The methods will work. A technician needs to restock the machine on manually, reset it to the no coin states to make it work again. Okay, now let me show you the vending machine class that last declares the four methods here and simply defers to the current state to implement the methods. In each call. The vending machine passes along this point or so that the state classes are able to modify the current state of the vending machine. That's finally here is the main program methods. It is a simple command line user interface that waits for the user to enter a number between one and three. One corresponds to entering a coin to means ejector coin on three is pressing the button. Let me run the program to prove that everything is working. I'm compiling the cold. No. And I'm running the codes. No. Okay. Let me insert a coin. Yep, that works now. I'll rejected the coin, and now I'll press the button. No, that doesn't work because there is no money in the machine. So I will insert a coin again. I'll try to insert another coin. Doesn't work. Okay, so I guess I press the button now and there's my chocolate bar. Now let me try to press the button again. No, doesn't work ons. Now, I'll try to Egypt's of the coin, and that doesn't work either. So there you go. The vending machine works fine. Okay, Here is a quick checklist you can use to implement the state butter. First, identify a class that needs to change its behavior. Based on a number off discreet states, we factor the class into a context class on define the context interface, create a state based class that replicates all methods in the context interface. Each message takes one additional parameter, which is a reference to the context class create derived state classes for each discrete states. Each derived class only overrides the methods it needs to override all context. Method calls are passed on to the current state objects with the this value in an extra arguments, and finally, each state changes. The current states in the context object as appropriate. And here are some final comments. State objects are often Singleton's, and this makes sense when you consider that the pattern continuously transitions from one state to the next, which clutters the heap with lots off the reference to state objects. When your application architecture has thousands of states on millions of possible state transitions, then you can actually run out of memory by using Singleton's, you prevent this memory pressure. Another solution for very large application architectures is to use the flyways pattern to share state objects. This combination of patterns will ensure that only the states with unique intrinsic states no stored on the and nothing else. You can also combine the state pattern with the interpreter pattern interpreters often have a parson context that determines how they will respond to sequences of expressions. You can use the state pattern to modify the behavior off the interpret method based on the parson context. Okay, let me recap what we have learnt in this lecture. The state pattern lets you alter the behavior, often object when its internal state changes. The pattern eliminates complex switch statements in the object methods. The pattern can sometimes hang. If they couldn't States has no six cents or states. States can be made Singleton's or fly weights to save memory. The state's pattern can be combined with the interpreter pattern. 11. The strategy pattern: here is the ninth behavioral design pattern from the famous gang or four design patterns book. This one is called strategy pattern. Andi. It is a pattern you use when you want to define a family off algorithms, encapsulate um, and make them interchangeable. I'll start with a quick summary off what we are trying to accomplish with this pattern. The strategy pattern is a good choice when you are trying to accomplish the following. You have a family off algorithms that you want to make interchangeable. You want to vary the algorithms independently from the clients that uses. Okay, let's go through the points one by one. The key to this pattern is that you have a family off algorithms that you wish to use in your application architecture. Each algorithm has a common interface butts, a unique implementation you want on elegant solution for making the algorithms interchangeable. The Strategy password does exactly that it defines on abstract strategy based class that's implements a common interface for the algorithm. Each derived concrete strategy class inherits the interface and implements its in a unique way. The clients can declare a variable off type strategy, and initialize is with a specific concrete stategy class to use that specific algorithm. Changing algorithms is as simple as assigning a difference concrete strategy to the variable. Because all strategy classes share the same interface, everything keeps working the benefits off the strategy pattern is that it completely shields clients from the implementation often algorithm. When you change on existing algorithm or add a new one the client codes will keep working on does not need to be re factored. This loosens the coupling between the context on the strategy classes, and that is a good thing. Okay, here is the UML diagram off the strategy pattern. The heart off the pattern is the strategy class. This abstract based class declares the public interface off the interchangeable algorithm. The diagram shows one single interface method called algorithm interface. There are three derived strategy classes called concrete strategy, a concrete stategy B and concrete stategy. See each concrete class implements the algorithm interface methods in a different way, and finally there is a context class. This class performs some kind off operation for which it needs the interchangeable algorithm. The class has its own public interface, shown in the diagram as a single context interface methods the implementation off this method uses a concrete strategy to perform the operation. Here's how that works. The methods contains a field off type strategy. Andi initialize is it with whatever concrete strategy it needs to perform the operation? Every time The context class needs to use the algorithm, it uses the variable to call the algorithm interface methods. The Context class has no knowledge about the implementation off the algorithm, as it only ever uses the status she based class. To demonstrate the pattern, I will show you a common I t problem. Let's say I have a database off people with everybody's name split into a first name on a last name field. I also have on external data file with names that I need to match against my database. Now here's the problem. The names are spelled differently in the data file. First names are abbreviated. The names contain extra spaces. The capitalization is all wrong or part off the name is missing. I need to rights a compare algorithm that matches the names in the data file with the names in my database. I am going to write three algorithms on use the strategy pattern to around the match three times for each algorithm, so I will implement the pattern with the following classes. Let's take a look at the code. I will start with the name compared her class. You can see that it's an abstract based class that declares a single compare methods. The Miss. It receives one imported name as a string on one name of records from the database. As a structure, the method should compare the two names return true if they match or return false if they do not. And here is the exact Compare er class. It's simply joins the first name on the last name together with the space and then matches this full name against the imported name using on exact string. Compare. The method returns true for an exact match and false if the names do not match, so you can imagine that this compared her is going to miss a lot of names. Any imported names with extra spaces or abbreviations or strange capitalizations aren't going to be missed. So here is on improved algorithm. The fuzzy compare ER uses regular expressions to strip all known words characters from the imported name. He then splits the name into a first name on the last name. Andi compares everything in lower case. This is a much better algorithm, but it's still cannot process abbreviations. So here is the thirds algorithm. The abbreviation compare er inherits from the fuzzy. Compare a Andi also matches abbreviated first names. So N. Smith. Well, no match Mary Smith. And here is the name importer class. You can see that it has a constructor for setting up a name compared her strategy. There is also a match method here that compares a given name database against a list of names to import. The message uses the current name compare er strategy to compare each name on displays each match on the console. Okay, on finally, here is the main program method. You can see that it initialize is a database off 10 names and another list off 10 names to import it, then uses all three name compare strategies to match the imported names against the database. Let me run the program to prove that everything is working. I'm compiling the coast now, and no, I am running the program. There you go. The exact compared. Her strategy only finds a single name, Iris West. The fuzzy match does a lot better and is able to match a total off seven names. But the abbreviation name compared her outperforms everything and is able to match all 10 names in the import list. Sends to the strategy pattern. You can easily swap these name. Compare algorithms in and out to find the best solution for any import list. Okay, here is a quick checklist that you can use to implements the strategy pattern. First, identify a family off related algorithms, then create on abstract strategy class that defines the algorithm interface, implements the algorithm interface in one or more derived concrete strategy classes and finally creates a context class that dynamically creates and loads no correct algorithm on . Here are some final comments. The strategy pattern is very similar to the templates method pattern, but the difference is granularity. The template message pattern differs. Sub steps often algorithm to sub classes, while the strategy pattern differs the implementation off the entire algorithm to sub classes. There's also a lot off similarity between the state and the strategy patterns, but the difference here is intense. The state's pattern uses subclass is to change the behavior off methods for different internal object states, whereas the strategy pattern uses subclass is to replace the implementation often entire algorithm, and finally, you often see the strategy pattern combined with the flyweight pattern. This combo pattern lets you support several types off flyweight objects that differ in their implementation. Okay, so here is a summary off everything we have learned in this lecture. The strategy pattern defines a family off algorithms, encapsulate system hands, makes them interchangeable. The pattern completely shields clients from the implementation details often algorithm. The strategy pattern is very similar to the templates message pattern, but differs in granularity. The pattern is also similar to the state pattern but differs in intense. The strategy pattern is often combines with the flyweight pattern to support several types off fly weights. 12. The template method pattern: This is the 10th behavioral design pattern from the gang off four Design patterns Book. This one is called Template Message Password. Andi. It is a pattern you use when you want to capture the structure. Often algorithm in a template. Methods on differ the implementation off particular sub steps off the algorithm to sub classes. I will starts with a quick summary off what we are trying to accomplish with this pattern. The templates method pattern is a good choice when you are trying to accomplish the following. You have a group off algorithms that all consists off the same discrete steps. The algorithms differ only in the implementation off specific sub steps. You want to transparently exchange algorithms without having to change the clients cold. Let's go through the points one by one. So the key intent here is that you have a group off algorithms that you needs to use in your application architecture. The algorithms all share the same sequence off discrete steps, and they differ on Lee in how they implement specific steps you want to use. The algorithms inclines cold, but you need the freedom to swap one algorithm out for another without the client's colds. Breaking the template method pattern provides the solution to this scenario. It allows you to define the overall structure off the algorithm in a top level templates class and overrides specific sub steps in derives classes. This architecture gives you a lot sof freedom. The top level class defines the number and order off individual steps and may even provide a default implementation for each step. The derives classes can override any step they want and can even replace a step with an empty message. To effectively switch off an algorithm, Step the benefits off. The template method pattern is that it provides a very compact way to implement a group offer latest algorithms all the shares cold off the algorithm goes into the top level templates class and only the corrections related to a specific algorithm go into the derived classes. The templates class provides a generic interface to the algorithm that completely masks the implementation. Therefore, you gained the freedom to swap one algorithm house for another without breaking the clients . Coz here is the UML diagram off the template method pattern. The algorithm is defined in the abstract class in a public message called templates methods . The methods implements the algorithm by performing a number off discrete steps in order. Each step is encapsulated in a separate methods called primitive Operation X. All primitive operation methods are protected and virtual the templates class can either provides on over rideable default implementation four implements the operation as an abstract methods that must be implemented in a derived class. The diagram shows a very simple algorithm that only uses to primitive operations. These operations are implemented or overridden in the derived concrete class. You you can see in the diagram that the derived class provides on implementation for the primitive operations on dozens needs to change anything in the template method itself. Okay, I am going to use the templates message. Pattern two creates a class that appends data to a file on disk. However, there's a catch. The file on disk is encrypted, so this process involves three primitive steps decrypting the file depending the data and re encrypting the file. I will set up a template methods that's implements these three steps by calling three primitive methods called decrypt file appends file on de encrypt file. The A pen file methods has a default implementation but the encrypted file on decrypt file methods are abstract and needs to be implemented in sub classes. I will provides to sub classes for handling desk includeds and non increased his files, so I will implement the pattern with the following classes. Let's take a look at the code. Here is the abstract based class called file writer. It's declares the three primitive methods called decrypt file appends file on de encrypt file. The pent file methods is implemented on appends data to the file, but the encrypted file and decrypt file methods are both abstract on a need to be implemented in sub classes. And here is the template methods simply called append. You can see that it performs all three operations in sequence decrypted file append data to its and finally re encrypting the file. And here are my concrete's classes. The this writer class implements the decrypt methods and uses deaths decryption to decrypt the file. The Miss. It writes the decrypted data to another file called temp adults text, and this is why I must also overrides the upend file message. It's cannot depends to the original encrypted file but must appendage data to the new temporary file called temp dot text, and here is the encrypt methods. The method takes the temp dot text file as input, and Chris is using a desk and crypt, or Andi writes the encrypted data back to the original file. Now compare this to the other concrete class called unencrypted to writer. Here. The decrypt file ons encrypt file methods do nothing, and so the class A bill only process unencrypted files. There is also no need to override the A pen file methods because the default implementation is fine here. And finally, let me show you the main program message. You can see that I have to files encrypted does text on unencrypted dot text. I first used a desk writer instance to add some text to the file, and then I use on unencrypted writer to do the same for the non encrypted file. Okay, before I run, let's take a look at these two files. Here is a file manager window with the debug folder off the application. Here is the unencrypted file on. You can see that there's a single line of text in here. The encrypted file contains the exact same text, but it is desk encrypted. When I opened the file, you can see that the contents are completely unreadable, just as we would expect. Now let me run the program to prove that everything is working. I'm compiling the cold. No, and I'm running the program. No. Okay, no errors. So let's look at the files again. When I opened the unencrypted file, you can see that another line of text has bean appended to it on. When I opened the encrypted file, we still cannot read the contents, but you can still tell that's a line of text has been added because now there is a lot more encrypted text now before. Okay, here is a quick checklist you can use to implement the template methods pattern. First, identify the algorithm on decide which steps should be deferred to sub classes, then creates on abstract class with a template method that implements the structure off. The algorithm adds abstract methods for each sub step that must be deferred to sub classes . Implement the sub step methods in one or more concrete classes that's finally have clients in Stan. She ate the correct concrete's class and call its template message and Here are some final comments. The strategy passer is very similar to the templates method pattern, but the difference is granularity. The templates method pattern differs. Sub steps often algorithm to sub classes, while the strategy pattern differs the implementation off the entire algorithm to sub classes, you might also notice a similarity between the factory method pattern on the template method pattern. The two patterns differ in intent. The factory method pattern modifies how new objects are constructed, whereas the template method pattern modifies her went algorithm operates. Okay, let's recap what we have learns in this lecture. The templates method pattern lets you capture the structure, often algorithm in a template method and defer the implementation off particular sub steps off the algorithm to sub classes. The pattern provides a very compact way to implements a group of related algorithms. The templates method pattern is very similar to the strategy pattern but differs in granularity. The pattern is also similar to the factory method pattern, but differs in intense 13. The visitor pattern: and here is the final 11th design pattern from the Gang of Four book. This pattern is called visitor Pattern, and it is a pattern you use when you want to perform operations on the elements. Often object structure. I will start with a quick summary off what we're trying to accomplish with this pattern. The visitor pattern is a good choice when you are trying to accomplish the following. Many distinct on unrelated operations need to be performed on nodes in a complex data structure. You do not want to query the type off each note before performing the desired operation. Okay, let's go through the points one by one. So the idea here is that you have some kind of data structure that consists off a large number off notes off different types. You want to perform many distinct on and unrelated operations on these notes. You could do this with the iterated pattern. Use a for each statements. To access the notes sequentially, check the type off each note on, then perform the correct operation corresponding to the notes type. But the key issue here is that you are unable or may be unwilling to perform the type check , perhaps because you want to avoid the extra performance overheads off a type check. So how would you do this? The specific operation that needs to be performed on a nodes depends on two factors. The type of operation to be performed and the type off the note object. This is called a double dispatch in C sharp. The visitor pattern provides a solution for this scenario and implements double dispatch. Here's how the pattern works. The pattern uses a special class called a visitor that can perform an operation on a single knows the class has a visit. Methods that receives the note as an argument ons performs the required operation on the nose. There is one visitor subclass for each desires operation. There is also a complex data structure consisting off 11 more notes. Each notes is called on element, and it has a single miss. It's called, except that provides for the visitor. The Except Methods receives the visitor as an argument and cools its visit message with this point of as an arguments. Now this pattern uses to bomb sex oriented tricks to implements double dispatch when calling the except message on elements the DOT net framework calls the correct virtual accepts methods corresponding to the elements type. This happens at runtime on This is the first dispatch. The accepts message then calls the visitors visit methods. Aunt provides the this. Point it as an argument. The dough net framework. Select the correct polymorphic visit message based on the type off the This Pointer. This happens at compile time, and it is the second this much. These two tricks implements double dispatch and ensure that the correct code runs for every unique combination Off visitor on elements type. The visitor pattern offers a number of benefits. First of all, all the codes for the operations that we want to apply to the elements is in separate visitor classes. This keeps the public AP I off the elements clean. The elements only needs to provide access to their value, and they do not have to implement each possible operation. This pattern offers a very elegant solution. If during the lifetime off the project, the number and type off operations can change every time. When you add a new operation, you only need to create a new visitor class. You do not need to make any changes to the elements classes. The pattern also implements double dispatch in an elegant way. By combining polymorphism on virtual messes, overloading the pattern can run specific calls for every unique combination off elements on visitor type. Without the pattern, you would have to use a type check for the second. Dispatch on this is less efficient. The pattern is not very well suited for the inverse off the above scenario. The number and type off elements can change during the lifetime off the projects. Consider for each new elements type you need to modify every single visitor class because you need to add a polymorphic overloads off the visit methods. The pattern also presents a rather convoluted A p I, which is harder to maintain than simply using the iterated pattern. Performing the type. Check on accepting the minor performance overhead. Here is the UML diagram off the visitor pattern. I will start with the abstract visitor based class of the top off the diagram. This class declares on abstract visit methods that must be implemented in a derived class. But look at the message declaration. The class declares one visits messes for each type off elements ons relies on C Sharps polymorphic methods, overloading to select the correct message. This is the second dispatch. There are two classes derived from visitor called concrete visitor. One aunt concrete visitor to the classes implements all polymorphic visit methods on. They differ in the type off operation they apply to the elements you can add as many visitor subclass is as you like. One. For each unique operation you want to apply to the elements. There's also an object structure containing one or more elements. The structure is represented in the diagram by the class object structure, and it refers to one or more elements classes. There's an abstract elements base class that's and declares a single abstracts Messes called except these methods except a single visitor. As its arguments, the method is implemented in one off the derived sub classes. Off elements calls concrete elements A ons, concrete elements be both classes implements the except methods by simply calling the visitors visit Mrs Ons providing the this pointer as an argument. So here's how that works. To apply an operation toe on elements you call the elements except Method Hands provides the corresponding visitor as an argument, except is a virtual message, so the Net runtime will automatically select the correct implementation. This is the first dispatch, and it happens at run time. The accepts method will then call the visitors visits methods as provide the this pointer as an argument based on the type. After this point, the runtime will automatically select the correct polymorphic visit message. This is the second dispatch, and it happens at compile time. The visitor pattern is a very nice way to petition a collection based on the type off their elements. So I am going to use the pattern to do exactly that. I am going to petition a product catalog. Let's say I have a large equal Merced sites up and running something along the lines off Amazon. I have a huge products catalogue with hundreds of thousands of products. My products are organized in a class hierarchy with an abstract products based class at the top ons products sub classes at the bottom. I want to quickly count the number of products in different groups, but without having to do a type check on each elements. The visitor pattern is ideal for this task. I will implement the passer with these classes. Let's take a look at the code. I will start with the visitor. You can see here that it is nothing more than an abstract base class that declares a number off abstract visits methods for each concrete products. I have a single visit message that expects that product as an argument. I will rely on C sharps supports for poli more fake message to select the correct line of code. And here is the concrete visitor called product petitioner. You can see that the class derives from visitor, and it sets up four integers to count the four types of products. Each visit message simply increments its corresponding counter. Okay, let's move on to the products classes I will start with the abstracts of based class called products Only Does is declare on abstract methods called except that except a visitor as its arguments. And here are the sub classes of products. The book class implements the except methods on simply calls the visitors visit message. With this point, as the first arguments on all other derived products, classes do exactly the same. I'll concludes with the main program message. I starts by setting up a small product catalog with a number of different products in it. Then, I instance, creates a products petitioner and use this loop here to call the accepts method on each listings products. Once the loop is finished, the petitioner will contain accurate counts for each product type. So these lines here right? The product counts to the console. Let me run the program to prove that everything is working. I am compiling the cold. No, I'm now. I'm running the program, and there you go accurate totals for each type of product. Everything works. Okay, so here is a quick check list that you can use to implement the visitor pattern. First, verify that the number off concrete element types remains relatively stable, then creates a visitor based class with a visit. Methods for each concrete elements type hands on except methods to each concrete elements class. The implementation calls the visitors Visit methods, creates a concrete visitor class for each operation to be performed on elements, objects and finally, half the clients create a visitor objects and pass it to each elements except method. And here are some final comments. The visitor pattern is often combines with the composite pattern to apply on Operation Toe every node in a Trie structure. The visitor pattern is more powerful than the commands pattern. Because a visitor can perform what's ever, action is appropriate for the type off elements it encounters. In contrast, a command always performs the same operation. Okay, here is a recap off everything that we've learned in this lecture. The visitor pattern allows you to perform operations on the elements, often object structure. The pattern concentrates operations in visitor classes on does not need to perform dynamic type checks. The disadvantage off the pattern is that it is a lot of work. Toe adds a new element type. The pattern can be used to quickly petition a collection by type. The visitor pattern is more powerful than the commands batter, because it's can perform different operations on each type off elements. 14. Course recap: congratulations. You have completed the entire course. You are now a certified C sharp design pattern guru. I have shown you all 11 behavioral design patterns what their intense are and when you should implement them. Knowledge off these patterns will greatly benefit you When you are developing your own projects. You have mastered the following design patterns. The chain off responsibility pattern, which gives a list off receivers a chance to handle requests. The command pattern, which encapsulates operations as objects. The Interpreter Pattern, which provides an interpreter for a domain specific language. The iterated pattern, which provides sequential access to the elements of a collection without exposing its underlying representation. The Mediator pattern, which sets up loose coupling between a group off objects by keeping them from referring to each other directly. The main mental pattern, which captures and objects internal states so that it can later be restored to the states. The observer pattern, which defines a dependency between objects so that when one object changes, states all his dependence are notified and updated automatically. The state pattern, which alters the behaviour, often object when its internal state changes. The strategy pattern, which defines on encapsulates a family off algorithms to make them interchangeable. The template method pattern, which captures the structure, often algorithm in a template. Methods hands differs the implementation off particular sub steps off the algorithm to sub classes. And finally, the visitor pattern, which performs operations on the elements, often object structure. These patterns have given you a rich toolbox off ready made templates that you can use when writing your own codes or when collaborating in a development team, especially when you're working on complex application architectures. If you discover some interesting insights of your own, please share them in the course discussion forum for us all to enjoy Good Bye, and I hope we meet again in another course.