Design Patterns Library Introduction Hello. This is David Starr, and in this module we're going to discuss the idea of design patterns, and specifically, how Pluralsight means to present design patterns to you in our Pluralsight Design Pattern Library. And in this module's discussion we'll be covering what in the world these design patterns are in the first place. Why should I care about this? Where the idea of design patterns originated, a little bit of the history of where design patterns come from. And also, why we should care. Why do design patterns matter, and are they worth my time? Should I pay attention to these things? And finally, we'll look at some specifics on the Pluralsight OnDemand! Pattern Library. What They Are And we'll start here with what design patterns are, and what they're meant to address. First and foremost, design patterns are very general, very nonspecific, yet reusable solutions, or templates for how to solve specific design problems in software design. What may come to mind is the idea of a software component. But it turns out that's not exactly an appropriate metaphor for design patterns. Components, assemblies, things like this, are elements of reuse, which is not necessarily a concern of design patterns. Design patterns are meant to address how specific classes, how specific code within a given code base, relates to each other. Also, these recipes for solving problems are not around algorithms, so you're not going to see, for example, a quicksort pattern. Quicksort is not a pattern. It's a defined algorithm. A pattern would be more focused on how different class elements relate to each other when being designed to address a very common recurring problem type. And we give names to these patterns. Each pattern that we'll present in the Library has a name, and we have these names so that we can talk about the patterns, and we can all understand what it is each other means. And design patterns are focused squarely on the domain of application and system design. There is some higher level, and some lower level patterns. So we do have patterns that address issues we find in enterprise architectures and service buses, and very high level concepts like that. We also have patterns that function at a very, very low level, and deal with things like how to create data structures that make themselves easily available for data binding. All sorts of patterns from low to high level, and everything in between. And it's important to release that these are abstractions on top of code. So we'll use terms when we talk about patterns, like a view, or a model, and when that class actually gets created inside of a software solution, there's nothing that says this class must be named model. So, this is really an abstraction, a human idea that we lay in on top of our code. We can name our code files anything. They can have method names named as we wish, but the structure of the interfaces of our classes is what we're focused on when we talk about how those classes come together to form a design pattern. We'll see the word collaborators when we talk about the relationships between the classes involved in a particular pattern. Collaborators are classes that will typically interact with the pattern, or might be in the pattern itself. And it's important for us to remember that patterns deal with problems that someone else has already encountered. And we all like to think we're special, but the real truth of the matter is that somewhere along the way, someone has probably seen this problem, or a very similar problem to the one that you're focused on right now. Particularly, if we happen to be doing what most software developers in this world do, which is forms over data, line of business of type applications. If that's the kind of work that you happen to be involved in, design patterns will promise to really improve your life by giving you some templates to follow for things that occur on a daily basis in your development. Now patterns, as we said, are not concerned with algorithms like quicksort, and they're not concerned with specific implementations. And that's very important to note because the intent of design patterns is to give us a starting point for solving a solution. A design pattern does not prescribe every single line of code that one must write in order to solve a particular problem, because, yes, even though we see these recurring logical patterns in our code, situations really do differ. Design Pattern History Now where did this whole idea of design patterns originate in the first place? It turns out that design patterns did not originate with software development. In fact, they originated with a man named Christopher Alexander who was a very successful building architect in the classic sense. Nothing to do with software architecture. This gentleman is responsible for more than 200 buildings worldwide in Europe, and Southeast Asia, and Japan. Now, in 1977, Christopher Alexander introduced a book, A Pattern Language: Towns, Buildings, Construction. And in this book, Mr. Alexander proposed that there are different patterns in architectural design that one can recognize, and one can make reuse of where appropriate. As an example, we have a building over here on the right. We can recognize right away that certainly the overall architecture of this building is Classical Roman in origin. Now why can we see that? Because our eyes are picking up on certain patterns within the picture, on the building here, and for example we can look at this low roof that's apexed right in the middle. There is a pattern for that roof, and it turns out there are various roof patterns in architecture, and that's a classification for specific pattern types. Also, we can see that we have columns here, and each of these columns has a top, and a bottom that has specific design characteristics, and we can borrow, and reuse those design characteristics as we might go about building a new building. That was the entire concept behind the pattern language book that Christopher Alexander wrote, and it rang a bell with Kent Beck and Ward Cunningham, who took his idea around classification of patterns, and applied it to software development. They introduced their work at the OOPSLA Conference in 1987. So patterns clearly have a very long history, and a rich one now. Probably one of the more seminal works on the subject of design patterns in software development was by the notorious Gang of Four, and this design patterns book has a reputation for being quite exhaustive, but also being somewhat hard to consume. It was the first design patterns book to come to press, and did so in 1994. You'll hear this book referenced, given that it was the first to bring many of the formal design patterns that we know and use today into a documented existence. Now, of course, there are many books, blog articles, and other such works around design patterns that we can find today, and while this design patterns book was the first, and is considered a seminal work, there are a lot of other resources that help us understand design patterns in a bit plainer language, and hopefully the Pluralsight Library will do just that for you. Pattern Organization and Language Now when we talk about patterns, we're going to use something called a pattern language, and a pattern language begins at a very high level by recognizing that there are certain categories, or classifications of patterns themselves, and then we give a name to each pattern. So, for example, here we have a list of named design patterns, all of which sort of fall into this classification, or category of creational patterns. Now, creational patterns happen to be focused primarily on how to instantiate objects at run time. And the circumstances for how we do that are definitely different depending on what problem we're trying to solve. Each one of these patterns focuses on a different scenario, and introduces a template for how you might want to solve for that particular scenario in your code. A list of classifications is here on the right, and you can see that this is a fairly long list, and certainly this list that we have here is not exhaustive. It's not complete, because the general body of knowledge around software design patterns is growing all the time, and there are various aspects of software design patterns, such as object-oriented design patterns. There are patterns for functional programming. There are patterns for parallel programming. And what that means is that the Design Pattern Library itself may be in constant growth, hopefully for a long time to come, as the software development craft matures, and we find more and more classifications for software patterns, and software patterns themselves. Why Patterns Matter Well alright, now that we know what design patterns are, and where they came from, why in the world do I care? One of the biggest reasons that design patterns matter for us is that it gives our profession of software development a language. This is a professional language that we can use with each other. Take, for example, the circumstance of builders, or carpenters, coming together on a single job. These carpenters may well have been trained in different places. They've attended different trade schools, and they all have different experiences. However, rest assured that each and every one of those carpenters knows when they look at a drawing like this one, they're looking at a tenon joint. There is a term for the type of joint we're looking at, the tenon joint, and carpenters know it. Now, if you look even closer at this particular tenon joint, it does not follow the classic definition of a tenon joint. We can recognize the pattern of a tenon joint in what we see. Also, even though there's been a variation on the theme after the carpenter got to work here, any other professional carpenter will be able to look at this and immediately recognize it as a tenon joint. This makes work within a team absolutely speed up when developers can look at each other, and simply say, you know, we should use a factory here. You know, we should use a visitor pattern here, and if we all understand what that means, that helps us be far more effective. This is establishing the professionalism of our craft in the form of a shared language. And not least of the benefits, is the idea that design patterns can help us avoid constantly reinventing solutions that have already been solved. And it's important to recognize that these design patterns are intended to provide a starting point for us, a template, if you will, like in Microsoft Word when I create a new resume. I still have to fill in my implementation details. However, I do have a general layout, and a general idea of what it is I'm going to produce, and that helps me be far more effective by not having to focus on low-level details. Design patterns give us that same sort of advantage that we get from templates. Now, it just so happens that what design patterns do is provide a human understandable abstraction on top of much of our code. And when doing so, it has the side effect of generally improving the design of our code, of our systems, and of our application architecture. When using design patterns, we'll often derive code that has much better separation of concerns, clear responsibilities for each classes, is much easier to read, and maintain. So, overall, it improves the craftsmanship of the code that we're working on when we use patterns to express our solutions. Criticisms Now even with all that goodness, there are, of course, some criticisms of design patterns, including the idea that what we're doing here is we're duplicating code over and over, and we're not getting reuse out of it. Critics that advocate for this position will often assert that design patterns become popular because of weaknesses in specific programming languages. A common quote we'll hear is that patterns are workarounds for missing language features, and that in a touring complete language, we would be able to express a design pattern as a succinct instruction. Whether or not that's the case, the state of our languages, and our software development tools today, is such that design patterns greatly aid in the construction of software. And it's reasonable to think of design patterns in similar ways that we think about other abstractions that we might put in our software design. The PSOD Patterns Library Now with regard to the Pluralsight OnDemand! Design Patterns Library itself, we fundamentally recognize that this is a mature topic. It has a rich body of knowledge already in existence. We can go out on the internet today finding books, blogs, and papers, lots of a variety, about various design patterns, nuances, and subtleties in the way that they get implemented by various people and various circumstances. This is a very mature subject area. Even though this is the case, we feel that Pluralsight can provide value to you by making these patterns practical for you as a .NET developer. Not only will we visit the rather classic explanations of the design pattern in each module, but we will also provide very real world context with genuine examples as often as we can from real production code. One way to think of the Pluralsight OnDemand! Design Patterns Library is to use it as a reference, although you're certainly welcome to go through each pattern in succession. It's also reasonable to come back to specific patterns over time just to freshen up on how this pattern might work, or when I have a specific problem that I'm trying to solve, look for patterns that seem related to the problem I'm trying to solve; go through them and see if they might help. For Pluralsight customers who have licenses that support it, each pattern will be accompanied by code examples, wherein the pattern's actually implemented. And because the state of computer science is always evolving, so are patterns, and as a result, we expect the OnDemand! Design Patterns Library to grow over time. Certainly, there's a core group of patterns that we'll find in the library, but beyond that, and over time, as new patterns evolve, are discovered, and recognized, Pluralsight will endeavor to bring those to you. And that means that the Patterns Library is going to be changing over time, unlike a typical course that you might think of. So, revisit the Patterns Library often. They'll probably be something new in there for you. Summary In this module we discussed what design patterns are, and what we learned is that design patterns are essentially reusable templates for how we can structure our application code, so that our application, or system design becomes far more repeatable, much better organized, and we don't have to solve the same problem again that someone's already seen. Design patterns give us that language that we can use to talk together when we come on site, or come together to build software. We know that even if two software developers come from very different backgrounds, if we share this language, and this understanding of design patterns, we have a starting point for communication. We have a good way to start talking to each other if we all know, for example, what a Factory Pattern is. We saw that design patterns actually started from the building architecture industry, and was applied to software development in the mid to late 80s. And regarding the Pluralsight OnDemand! Design Patterns Library itself, we recognize that there's a rich history of design pattern documentation already, and what we propose to do in our Library is make it very tangible for you, the .NET developer, and help you apply design patterns in your day-to-day life. And once again, please consider the Design Pattern Library an ongoing reference, one that will be updated over time as new knowledge is gained, and as the craft of software development matures. Well good luck on your path of software craftsmanship, and I know that design patterns will play a great part in that for you. This has been David Starr, and I'm looking forward to seeing you in class sometime soon. Adapter Pattern Introduction This is Steve Smith. Welcome to another Pluralsight On Demand module. This is part of the Design Patterns Library, and today we're going to have a look at the Adapter Pattern. Motivating Example The Adapter design pattern is one of the most common, and most useful patterns available to us as software developers. As with all of these design patterns, it's useful to consider a motivating example that demonstrates when you would want to use such a pattern. For the Adapter, this example would be when you have a class that needs to utilize a particular interface, and you have a library that includes the functionality you need, but it doesn't use the interface that you require. You can achieve the reuse of that library's code by creating an Adapter class that sits between your client code, and the code that's in this library, and adapts one interface to the other. If you yourself are writing a library, or a framework, and you want to ensure that it's useable by future classes that may not even have been written yet, and so you cannot be certain what their interface will be, you can add support for an Adapter as part of your interface for your code, and this will make it easier for other future applications to use your code. Adapters are also commonly known as wrappers, and in this module it's important to note that we will be referring only to object adapters, which do not require multiple inheritance as class adapters do. This is because in .NET the C# and VB.NET languages do not support multiple inheritance, and so there's not as much interest in looking at class adapters. Graphic Example Let's look at a graphical representation of the Adapter Pattern. In this diagram, you can see a Client class on the left, which requires a particular interface shown by this half-circle. A component that has functionality that the Client needs is shown on the right, and it expects an interface of this inverted triangle shape. Obviously, as it stands here now, we cannot simply connect these two pieces together. Our code will not compile with a Client that expects one interface, and a component that exposes another. This is where the Adapter Pattern comes in handy. By writing our Adapter class, and injecting it between the Client and the component, such that the Adapter provides the interface the Client expects, as well as implementing the interface that the component requires, we are now able to connect these three together in a way that we could not do when all we had was the Client and the component. Real World Example Like many design patterns, the Adapter Pattern has an analog in the real world that we can use to help our understanding of the pattern. In this case, if we consider a standard US power plug, such as one might have for a laptop power supply, it would look something like this, with two vertical metal prongs that are going to go into the power outlet. Recently I was in Bulgaria, which follows the European standard of its power outlets, and it exposes two round plug holes for the plug to be inserted into, and incidentally it also provides 220 voltage, whereas most US appliances, by default, expect 110. Fortunately, my laptop power supply will automatically convert from either 110 or 220 voltage, but that doesn't help me if I need to be able to plug my US plug into this European outlet. And so that is where the adapter pattern comes into play. By purchasing a travel adapter for my power plug, I'm able to plug my two vertical metal prongs into the one end of the adapter, and then I can plug the other end of the adapter's interface, which consists of two round prongs, into the outlet in my hotel room, thus allowing me to work while traveling. Intent The intent of the Adapter Pattern is to convert the interface of one class into another interface that its clients expect. This allows classes to work together that couldn't otherwise do so because they had incompatible interfaces. One thing this allows us to do if we were trying to write reusable software is to future-proof client implementations by having them depend on Adapter interfaces, rather than the concrete classes directly. Applicability You should consider using the Adapter Pattern whenever you want to use an existing class's functionality, but its interface is not the one that you require. Likewise, if you're trying to create reusable code, and you don't want to tie it too tightly to a particular implementation, you should use some kind of an Adapter interface as what you're code depends on, so that future clients could implement their own version of that Adapter and still make use of your code. You'll also find the Adapter Pattern useful if there are several existing implementations of code that you want to be able to use, and it's impractical to adapt each of their interfaces by sub-classing everyone. By implementing the Adapter Pattern, and just writing an Adapter for each of these subclasses, for instance, maybe you have a Data Access class, one for SQL Server, another for Oracle, another for DB2, you would be able to create a Data Adapter, and then create just the Adapter classes for each of those different implementations rather than trying to change those implementations directly to expose the interface that you require. Structure Let's look at the structure of the Adapter Pattern using this UML diagram. The two basic players within this example are the Client, shown up here, and the Adaptee, shown below. Now the Client needs some of the logic that exists within the Adaptee. Specifically, there is this AdaptedOperation that has the code that the Client wants to be able to utilize. Unfortunately, the Client has been written in such a way that it cannot directly call this AdaptedOperation because its interface is not the one that the Client expects. This is where the Adapter Pattern comes into play. First, the Adapter interface is created, exposing an Operation that has the interface the Client expects. Next, for each different implementation required, at a minimum, one, its different ConcreteAdapter is created that takes that Operation and implements it, such that that code calls the AdaptedOperation. In this way, the Client will now be able to call the Operation on the ConcreteAdapter, which in turn will call the AdaptedOperation on the Adaptee. The Client really wants to use the Adaptee directly, but unfortunately it can't due to the incompatible interface. The Adapter Pattern is simply allowing us to achieve this despite this incompatibility. How It Gets Used The way the Adapter Pattern is used is that Client classes are written such that they depend on an interface, rather than on a particular implementation. Then, at least one concrete Adapter class is created, which implements this interface, allowing the Client to work with a particular class that it requires. It may be that you already have both the Client and the implementation of the Adapter under your control, and you're simply writing the Adapter interface to decouple the Client from its implementation. In this case, you're doing a good thing, because you're future-proofing your Client, allowing for later changes to be implemented to its behavior by simply writing new Adapters that work with new implementations of this code. This is a very effective way to achieve what's called the Open/Closed Principle, which you can learn more about in the Principles of Object Oriented Design course available at Pluralsight On Demand. Collaboration In terms of collaborators within the Adapter Pattern, it's very simple. Clients simply call operations on the Adapter instance through the Adapter interface. Likewise, the Adapter instance calls Adaptee operations that carry out the request. Consequences Some of the consequences of using the Adapter Design Pattern are that a single Adapter interface may work with many Adaptees. For instance, it could work with one Adaptee, and all of its subclasses, which is nice because it gives you some reuse through the use of a polymorphism, or you have the ability to write a different concrete Adapter implementation for each different Adaptee class that you want it to be able to work with. This gives you some flexibility, and also allows you to follow the Open/Closed Principle, again, because you can just write a new class that implements the behavior for a new concrete Adaptee with the behavior that you need to be able to reference. Note that it can be difficult to override the behavior of the Adaptee class using an Object Adapter, because you cannot simply inherit from it. Since we're using composition, instead of inheritance, the only way to change the behavior on the Adaptee is to subclass it directly, add the overridden behavior, and then change our concrete Adapter implementation so that it refers to the Adaptee class. We consider this to be difficult when compared to a programming language that would allow for multiple inheritance, where we would only have to do this in one place, which would be in our Adapter itself. Implementation Example There are a number of examples of the Adapter Pattern within the .NET Framework Library itself. The one that I'm most familiar with, and it's probably the most commonly used, is built-in to ADO.NET, and thus has been a part of the .NET Framework since the early days of .NET 1.0. You will find if you look at ADO.NET in the System.Data namespace using a tool such as Reflector, shown here, that there is a class called the IDataAdapter, and that IDataAdapter has a number of derived types, including a concrete class called DataAdapter, and then beneath that you'll find the DbDataAdapter, and then finally the Odbc, OleDb, and SqlDataAdapters. Each of these implements at its core the IDataAdapter interface, and we'll look real quick at some code that shows how these can be used to achieve reuse, as well as to allow for the addition later of new adapters for data sources that perhaps don't even exist today. Let's look at an example showing how we can utilize the IDataAdapter interface in order to make some code more reusable. Now, let's look at some code that takes advantage of this interface, and the Adapter Pattern. Demo In this demo we're going to show how the Adapter Pattern can be used to create reusable code that is not tightly coupled to its implementation. The first thing we're going to look at is a class called DataRenderer. DataRenderer expects an IDbDataAdapter as part of its construction. It exposes a single method called Render, and using that Render method, it's going to write out to a TextWriter the contents of the data that it gets from that source. Now the way it's going to get that data is through the use of the dataAdapter's Fill method, which is going to populate a DataSet that we're going to pass into that Fill method empty. Once we have our data, we're simply going to loop through the columns, and write out the column headers, and then for each row, we're going to write out the data in each row. Now to verify that this code works, we're going to write some unit tests. And the first thing we're going to do is we're going to write a unit test that says that if we provide a StubDbAdapter, we get the output that we expect. Now for that Stub Adapter, I've simply implemented the Fill method, because that's the only one we care about, and I've created a new DataTable, and I've given it three columns, Id, Name, and Description, and then I've created a single NewRow, where I've given it the Id of 1, the Name of Adapter, and the Description of Adapter Description. I've then added the Row, and the Table to my dataSet, Accepted the Changes, and I'm returning 1 because that's how many rows were affected. If we Run this unit test, we will see that it passes. And if we view the results, we can see that our output consists of a line saying Rendering Data, the column headers, and then the actual data that we expected. Now for my test, I'm simply asserting that I got back the correct number of lines. In this case, there're two lines of header data, and then one row of detail, so I'm expecting three lines, and so my test passes. Now in order to make use of the Adapter, we need to be able to provide multiple different Adapters to the same DataRenderer class. So, this is also an example of the Strategy Pattern, in this case, because we're able to change how this class behaves based on what type of interface we pass into it. So if we look again back at our tests, we can say that we could pass in a different DataAdapter, in this case a DbDataAdapter, using OleDb to talk to a SQL Server Compact Edition database. So you can notice here in our Solution Explorer, I have a sample database called Sample.sdf, and within that I've defined a Table called Pattern, and if we view the Table Data, we can see that we have two patterns listed; one is the Singleton with a Description that says there can be only one, and the other being the Adapter that simply says Make it fit. And we're going to write a test now that expects to be able to pass in an OleDbDataAdapter. Does the exact same code as before to get out the result. Writes it out to the Console, and we're going to Assert that we have this time four lines, because we have two rows of data, plus our two headers. So if we Run this Test, we see that it also passes. And if we view the results, we see that we got the correct results rendered to us. So this is an example of how to use the Adapter Pattern that's built into ADO.NET, and you could imagine that we could also change this to use a SQL Client Adapter, an Oracle Adapter, an ODBC Adapter, connecting to different data sources of those types. But let's look at another example of how we would implement an Adapter ourselves. Imagine that we have a Model now that includes the notion of a Pattern, with its Id, Name, and Description, and we need to be able to Render that pattern. And so, somewhere in our application, we already have code that is requiring this interface that expects to be able to call a PatternRenderer, and get back a string when it says ListPatterns. Now, at the moment you can see that we're just generating a patterns.ToString, which is not going to be the correct implementation. What we really want is for this to give us back some kind of a tabular representation of our patterns, very similar to what the DataRenderer does given a DataAdapter. Now unfortunately, the DataRenderer's Render method is a void that expects a TextWriter, and our PatternRenderer is a string that expects a collection of patterns. So, even though we know that the code that we need that will render stuff in a tabular fashion exists in our DataRenderer, we don't have easy access to it because it doesn't have the correct interface that we expect. So the way that we can achieve that is to create that interface. And then pass that interface into our PatternRenderer. So let's write a little bit of code. The first thing we need to do is create a new constructor for PatternRenderer, and we need to say that it expects some kind of an Adapter. Now one of our tougher problems is going to be coming up with a name for this thing, so we're going to call it an I, let's call it DataPatternRenderer, which isn't necessarily the best name, but we'll go with it, and we'll just call it DataPatternRenderer as our parameter, and we're going to use the ReSharper tool here to introduce and initialize a field for us. You can do all that code yourself if you like, but it simply does this assignment for me, and it adds this variable declaration here. Now I still don't have an IDataPatternRenderer interface. We need to create that next. So, I'll create that interface here, and I think that interface needs to give us back something that looks very much like our ListPatterns interface. So, we will call it a string, and we will just go ahead and say its ListPatterns, and it's going to expect an IEnumerable of Pattern called patterns. And so that works for us I think. Now we need to implement this, so let's create a derive type here, and we'll call this the DataPatternRenderer, that's fine. And let's go ahead and implement our interface. So now we've got that. Now at this point we can come back up to our code, and make it so that it is going to call the correct thing, so instead of just returning patterns.ToString, we want it to return the dataPatternRenderer.ListPatterns method and pass in the patterns. At this point, our Client code is pretty much a pass through that's just letting the Adapter do most of the work. And our DataPatternRenderer. Ah, you know what, let's not call that Renderer. Let's call this DataPatternRendererAdapter. Let's make sure we're using our name of our pattern here. And then we'll just call this the Adapter as well, there we go. So now we've got an IDataPatternRendererAdapter, it's a little bit long, but it's very clear what it's doing, and we'll make this guy public. And the next thing it needs to do is actually render our pattern data using the DataRenderer. So to do that, it's going to need an instance of a DataRenderer, so we'll say private DataRenderer_dataRenderer, and the next thing it's going to need to do is actually implement ListPatterns, so it's going to need a new DataRenderer. (Typing) And at this point we know that we're going to need to provide some kind of a DbDataAdapter. We don't have a DbDataAdapter that is going to work for our IEnumerable of patterns, so we're going to have to create one of those as well, but that's okay, because we can do that simply internally here. We could implement something that would be useable for any IEnumerable, but that's beyond the scope of what we need right now, so we're just going to write an internal class called PatternCollectionDbAdapter, which implements IDbDataAdapter. (Typing) And we'll pull in that namespace that we need, and then we'll implement it as well. And so now we've got a whole lot of stuff that we don't need, so we're just going to worry about the Fill for now. We'll move that up to the top, and then we'll hide everything else away in a region, which we'll call Not Implemented. This is a bad practice, and I'm only doing this because I have, this is an internal class, so I know nobody else but me is going to be able to try and use this, and get bitten by the fact that it doesn't actually implement the interface it says it does. Generally, you're not going to want to have the implementation of an interface where you don't implement all of its features. Now, at this point, we just need to Fill a DataSet and pass it back, so I already have a StubDbAdapter that has the code I mostly need. So I'm going to pull out this code here, bring it over here and Paste it in, and in this case I know my DataColumns are still going to be Id, Name, and Description, because that's what a pattern has, but the actual data is going to have to be different. We're going to have to go through our collection of patterns. But, you know, we don't have a collection of patterns yet, so we're going to need that. So let's create another constructor here, and this constructor is going to say I need this IEnumerable of Pattern patterns, and do the same deal as we did before to give us this local instance of it. And now, within my code here, I can simply foreach through patterns, and do the same work that I'm doing here, so we're going to do all that within our loop, and I just need to change this Id to be pattern.Id, and this to be pattern.Name, and pattern.Description, right, and then I can do something like return our data tables row count. (Typing) There we go. And that'll give us back the count of rows that we filled into our dataSet. Now, at this point we need to write a test that says that we're able to actually do this. We also need to be able to pass in to get our code to compile, we need to pass in an instance of this PatternCollectionDbAdapter, so let's say var adapter = new PatternCollectionDbAdapter, and this is where we'll plugin our patterns collection, and now that we have our Adapter, we can pass that into the Renderer, and that will let us have our DataRenderer instance. Now we still need a string that we can pass back, so we're going to say string result = dataRenderer.Render. Oh, but we need a TextWriter, so we'll say var writer = new StringWriter. (Typing) Pass that into this. (Typing) Can't actually take that result there yet because it's a void. But now we can return writer.ToString, and we should be able to get the data that we expect. Let's fix our compile error. (Typing) That interface needs to be public, and we're good. And now we need to write some tests. So let's come in here, and we're going to Create a New Class called PatternRendererShould. And PatternRendererShould, I'm going to just pull some tests in that I've previously written. And so you see that we now have a class called PatternRendererShould. It's going to take a new PatternRenderer. In this case, it's expecting a parameter that I don't really want to have to provide here, so what I'm going to do is I'm going to create a default constructor inside PatternRenderer that'll do that for me. So, the way that works is I'm just going to come in here and create another constructor, and I'm going to say that by default it's going to default to this, and it's going to create a new instance of the DataPatternRendererAdapter that I want. And that's all this constructor does. But it'll make it so that any code that was previously depending on PatternRenderer, and was not aware of this interface that we're using, this Adapter, will still continue to work the way it did before. So now our test is fixed. No more compile problem. And for this test, I'm going to create a collection of patterns using a List of Pattern, and we're going to have two patterns in the list, one's going to be called Pattern One, one's going to be called Pattern Two, and we're going to pull out the result using my ListPatterns method. Notice that there's no knowledge here of DataAdapters, DataSets, anything to do with the DataRenderer. It's just behind the scenes that we're using the DataRenderer inside of that overloaded constructor that I just showed you. If I wanted to swap it out with a different Adapter for how I'm doing my data rendering, I could do that by injecting a different instance of that Adapter interface into the constructor here. When all is said and done, I want to be able to view the results, and I expect that my results will always be the size of my list, plus the two header rows. And so if we Run these Tests, we can see that it does in fact pass, and we should probably rename this guy to say RenderTwoPatterns, and Run that Test again just for good measure, and let's see, it output out Pattern One, Pattern Two, Pattern One Description, Pattern Two Description. So, it looks good. So if we Run all of our Tests for our project, which we can do from here, we can see that they all pass, and in this way we've seen how we can utilize the Adapter that's built-in to ADO.NET so that we can take this DataRenderer and have it depend on an Adapter, and then we can utilize our own Stub Adapter, or an OleDb command, or we can further take our own PatternRenderer and make it depend upon an Adapter of our own writing. In this case the IDataPatternRendererAdapter, which itself is going to implement an IDbDataAdapter in this case, in order to utilize DataRenderer, which already has this core logic of writing out a tabular set of data, so that we didn't have to rewrite the same data at another location. Related Patterns There are several other design patterns that are related to the Adapter Pattern. The Repository Pattern is a higher level design pattern that's a very common use of the Adapter Pattern. The Strategy Pattern, which is one of my favorites, is also very commonly associated with the Adapter Pattern. Whenever the Adapter Pattern is passed in to a constructor, or property, or parameter of another class, or method, this can be seen as an implementation of the Strategy Pattern, in addition to the Adapter Pattern. Another related pattern that we haven't talked about thus far is the Facade Pattern. The Adapter and the Facade Patterns are both wrappers. The Facade Pattern has as one of its primary goals the simplification of a complex interface, and oftentimes a Facade will wrap a complex hierarchy, or graph of many different objects that have to collaborate together into a much simpler interface. The Adapter on the other hand, is generally only concerned with a single Adaptee class, and it does not worry about making that interface any simpler, so long as that interface is usable by the Client. In fact, generally in the case of the Adapter, the interface that it needs to use is already fixed by the Client, and the interface it needs to adapt to is already fixed by the Adaptee, so there's no simplification, or changing involved, it's simply a matter of making the one fit into the other. You can learn about these patterns in the Pattern Library available at Pluralsight On Demand. References You can learn more about the Adapter Pattern, as well as other design patterns from the following books. The first one shown here is Design Patterns book, which kind of started the whole idea, and it's written by the so-called Gang of Four, and is highly recommended as a reference. Design Patterns Explained, and Design Patterns in C# I also highly recommend. And Head First Design Patterns offers a very different, and enjoyable approach to design patterns, and also includes some great coverage of the Adapter Pattern. You can learn more online at Wikipedia, which has this URL devoted to the Adapter Pattern. Summary And so to wrap up, the Adapter Pattern is used to wrap a needed class with one that implements a required interface. If you write your Client classes so that they depend on Adapters, it allows you to future-proof these classes so they can be made to work with future versions of code that does not use interfaces that you foresaw when you wrote your Client Library. You should remember the Open/Closed Principle, which states that modules should be open to extension, but closed to modification, and by utilizing the Adapter Pattern in your implementations of your code, you allow for your code to better follow the Open/Closed Principle. This has been the Adapter Design Pattern. My name is Steve Smith. Thank you very much for attending, and I hope to see you again soon at more Pluralsight On Demand courses. Thank you. Bridge Pattern Introduction Hi. This is John Sonmez from Pluralsight, and in this module we're going to be talking about the Bridge Pattern. The Bridge Pattern is one of those design patterns that I think a lot of people find pretty difficult to understand, and understandably so. The Bridge Pattern has quite a few different components to it, and it's sometimes difficult to find good examples of when to use the Bridge Pattern, and it can be a little bit confusing to grasp this concept. But in this module, we're going to try and simplify this as best as possible so that it'll be real easy for you to understand exactly what the Bridge Pattern is, and when you should use it. So, we're first going to talk a little bit about a general case of using the Bridge Pattern, and we're going to see how in a real life situation the Bridge Pattern might apply. And then we're going to go through some code, and we're going to refactor that code to use a Bridge Pattern, and we'll see how doing so is going to reduce our code, and make our code much more maintainable. Then finally, we're going to wrap it up by looking at the actual UML diagrams of the Bridge Pattern, and see how we had implemented that pattern in our code, so let's go ahead and dive right in and learn about the Bridge Pattern. What Is It? So, what is the Bridge Pattern? Well, according to the Gang of Four definition in their Design Patterns book, it is to decouple an abstraction from its implementation so that the two can vary independently, and it's a little bit difficult to understand the statement as it's stated, but we can break this down a little bit and try to understand really what is being said here. So, if we look at the first part of the statement, to decouple an abstraction from its implementation. Well we know what an abstraction is. An abstraction in our code is usually some way of classifying a group of things, or something that exists in our problem domain, or code. So, an abstraction might just be a base class, or it might be an interface that we're using to abstract away the concept of something that could have different implementations. Now, traditionally, in our code when we create an abstraction, we might create an interface, and that interface would be an abstraction. And, of course, an interface is no good without an implementation, so we'll typically create an implementation that implements a specific interface. In this case, the abstraction and the implementation are coupled together. If we have a class, and that class implements an interface, any changes in that interface are going to need to be made in that class, and changes in that class, in regards to the methods that it implements in its interface, are going to affect the interface. So, an abstraction and an implementation are, by default, coupled. So what we're going to try to do in the Bridge Pattern is to decouple those two. And the reason why we're going to do it is so that the two can vary independently. So, we're actually going to create one level of a higher abstraction. We're going to abstract away the implementation from the abstraction. So another way to think about this is to say that we have our abstraction, we have an implementation for that abstraction, but we're going to abstract away, put one more level of indirection between that implementation. So, where we had our abstraction tied to our implementation before, now we're saying this abstraction is going to use another abstraction as its implementation, and what this allows us to do is to vary the two. We've put this extra piece in between our abstraction in our implementation, and it's made it so that the implementation, all the way on one end can change, and that abstraction can change, and we have this kind of glue that binds them together, but they can change independently. And really the Bridge Pattern is just that bridge which is connecting those two things that can vary independently to each other. Nom Nom Burger So I always find it helpful to look at a real world example when thinking about design patterns. So, I've got an example here of a menu for Nom Nom's Burger House. The idea behind this menu is that the person creating this menu wanted to display all of the possible items that they sell. I don't have the prices listed here, but you can see that there are quite a few items here. There're five different kinds of burgers, and each one of those can have a fry and drink combo, and then each one of those can have a veggie, milk combo. So, this is a pretty full menu. Now you can see immediately here that there's some duplication. But the person designing this menu went ahead and created this duplication because they didn't want to not show all the options that were available. And this is something frequently that we'll do in our code. You can think about the abstraction as the burger, and you can think about the implementation as the combo meal, and so there's two different implementations here. You can either have the fry and drink, or you can have the veggie and milk. If you create some kind of hierarchy here, you have to enumerate all the possibilities. You have to say, well you can have a Nom Burger with the fry and drink, and you can have a Nom Burger with the veggie and milk, and a lot of the times our class hierarchies and code will look like that. But for now, let's just focus on this example. And the concept here is that you're not selling a burger by itself, you're selling a meal. We have these different meals that exist based on these options. Now let's look at another example. Here's a simplified menu. You can see that in this menu, we have all of the burgers. There're four different kinds of burgers, and then we state that you can have it with fries and a drink, or vegetables and milk. And so, we've created this combo, or we've created this meal concept by combining two things together. If you think about it, the abstraction really is this burger, and there're different types of burgers that you can have, and then the implementation is the meal that goes with it, or the combo, the fries and the drink, or the vegetables and milk. And so you can really think about this as two separate concepts. Now, this burger is not tied to the combo anymore. The combo is the implementation. So, we could change this out. Let's say that we wanted to have a different combo. We'll add a new one. Or let's say that we wanted to make it fries and milk. We can make those changes, and this menu doesn't have to change, or the left side of the menu doesn't have to change, when the right side does. We could introduce a new burger to our menu, and if we introduce the new burger, we could still keep those two combos. Now, I'm going to go back one step in the slide, and we're going to see why that concept doesn't work with the original menu. So looking back at this slide again, now what happens here if we introduce, for example, a new combo meal? Well, we're going to have to create four new menu items. This menu's going to grow. It's going to affect the entire menu. And if we changed one of these combos, we'd have to change it in all these different places. And if we added a new burger, we would also be adding two new items. So, when you contrast this with this simplified Bridge-style Pattern, you can see that the benefit that using a Bridge-like Pattern is giving you here is that you're separating these two things, these two concepts, you're not making them tied together. The customer, the person buying the food, can decide how they want to couple the things together, and they can decide when they purchase it, not you coupling them together ahead of time when you create the menu. Inital Problem So let's go ahead and take a look at the Bridge Pattern in action. I've created a small project here, called Bridge Example, and in this project, you can see I've created a few types of classes. I've created a FAQ, a Book, and a TermPaper, and these are all kinds of documents, or manuscripts, and they have some different properties on them. For example, the FAQ has a Title, and it has a dictionary of Questions, but it can be printed. We've got a Book that has a Title, Author, and Text. And we've got this TermPaper that has some other attributes, and it can also be printed. So this is something that you might typically see, a set of classes that do somewhat similar things. We don't really have much of a problem here. The only thing that we can really see, if we look at each one of these classes, is that we've got this Print method. But, each one of these is implementing Print slightly different, so we're not too worried here. If we were using this, we might want to create some kind of a higher level interface, so that we could refer to a manuscript, and just call Print on it if we wanted to print a collection of manuscripts, for example. So let's go ahead and make that improvement to our code as we get closer to the Bridge Pattern. So, for example, we shouldn't have to call Print on each one of these. We should be able to basically take each one of these things and add them to some dictionary, so, or a list. Let's just create a List of, we'll call this IManuscript, and we'll call this documents. It'll be a new List here. And then what we'll go ahead and do is we'll just go ahead and add each one of these documents to this List, so we'll Add our FAQ. We'll do documents.Add on our book, and we'll do documents.Add on our paper. So now we should be able to do foreach. We'll say var doc in documents, and we should be able to call the Print method. Now this method doesn't exist because this interface, or class doesn't exist either, but this is what we want to be able to do. Because all these should have this in common, we don't really need to know what the document type is, we just need to know that it's a manuscript, so it has Print. So we can go ahead and implement this, and this is a pretty good refactor for our code, so I'm creating this interface called IManuscript. We'll make it in its own file. And this IManuscript has a Print method on it, so we should have void Print, and everyone implementing that should have Print. So, we can go ahead and make our Book implement IManuscript. We can make our TermPaper implement it, and our FAQ implement it. So now if we go ahead and Run this program, we should be able to Print each one of the documents. In fact, we need to do doc.Print, because each doc will have a Print method on it. So I'm going to go ahead and Run this, and you can see we got the exact same output we had gotten before, but now we're doing something a little bit smarter here, we're able to handle the commonality between these things. So, at this point, we don't really need a Bridge Pattern. We are able to solve our problem. We're able to handle documents through this IManuscript interface. We have one level of abstraction here. Wrong Solution Now, let's imagine that we got some new requirements. Our customer is happy with our Book, our FAQ, our TermPaper, but our customer says, what I really want to be able to do is to print the books backwards because I need to have the ability for my customers to be able to read the books, or the manuscripts in a mirror. They've requested this feature. Now, as weird as this feature is, we still need to implement it, so we got to think about how we're going to do this. Now the first approach to doing this might be to take our Book and to create a new Book class from it. We could even inherit from Book, and we could make two kinds of Books. We could have our standard Book, and we could have a backwards Book. And we could do the same thing with TermPaper and FAQ. So, let's look at Book here, and actually, look at this error we had. We need to switch this up, but the basic idea here would be that we can inherit from Book, and we can implement this Print method. So, we can make this method virtual here, and then we can go in, we can create a new Class here, and we can call this BackwardsBook. And what we'll do in BackwardsBook is we'll just inherit from Book, and we'll just override this Print method, so we'll just do override public void Print. So in here, we'll basically do what's in Book's Print, except we'll Print the text backwards. And a neat little trick to do this is to print a new String here, and in this String we're going to have our Title Reverse.ToArray. So it'll create a character array for us. So we can go ahead and do this for each one of these, and we'll go ahead and modify our main program to try and use this, so we'll use a BackwardsBook instead of our Book, and let's go ahead and Run this and see what we get here. So you can see now its printing out our Book, all the information in our Book backwards. But we've got a big problem here. And we're starting to grow a bigger problem in general. The problem is that we need to be able to apply this backwards capability to any one of these types of manuscripts. So we've implemented Book, but what about TermPaper, and what about FAQ? We'll need to create a BackwardsTermPaper, and BackwardsFAQ. There's really no good way for us to create an inheritance hierarchy that's going to allow TermPaper and FAQ to get these same attributes. The closest thing that we could do at this point might be to create a flag, a toggle, where we could either Print the String forwards or backwards. We need some kind of abstraction for a way of formatting the actual text, or doing the printing. So, in this case, we're going to have an implementation because, remember here, when we look at Book Printing this is an implementation of the manuscript interface, but what we really want here is we want another level of abstraction. We want it so that when Book calls Print, it uses some kind of printer, or some kind of formatter to do the formatting, and do the printing, in some way, and we want the Book to be able to print the way it needs to, because it does Title, Author, Text, whereas FAQ is doing something different. It's doing the Title, and it's looping through this Dictionary. So, we're going to create an abstraction for the implementation of formatting, and that's going to take us into the Bridge Pattern. The other thing to consider before we get down this road is what happens when the customer asks for a different type of formatting? Right now, we might just have standard and backwards, but perhaps they ask for this fancy type of formatting. If we go down the road of creating inheritance hierarchies for Book, TermPaper, and FAQ, we're going to have to expand that out, and create a new class every time they want a new formatter, and if they added a new manuscript type, we might have to multiply that exponentially, so we'd have a large number of classes, a large headache for maintenance. Refactoring to Bridge So, let's go ahead and extend this into the Bridge Pattern by creating our formatter, which will be our implementation for formatting. So, let's go ahead and get rid of this BackwardsBook, since we're not going to need this anymore, and we'll go ahead and change this reference here to reference the Book. And what we'll go ahead and do here is we're going to pretend like we already have this formatter so we can see what kind of interface we want for it. And here we're defining an abstraction for our abstraction of printing. So in this case, we'll go ahead and duplicate this. We'll say Console.WriteLine, and we want to have basically a formatter that's going to have a method on here called Format, and we want to pass it in the String, just like we have above here, and then the Value, just like we have here, and we're expecting that it's going to do the formatting for us. In fact, let's make it a little bit smarter. Let's make it know how to add the colon and then add the value at the end. We're just going to tell it what the key is, and then what this value will be to be formatted. So we'll need this formatter member. And before we can do this, there's two ways that we can go about this. Right now we're implementing this IManuscript interface. What we'd really like to do is to force everything that implements this interface to have a formatter, and to have a constructor that takes a formatter. Because we want to say that if you're a manuscript, you've got to have a formatter. The only problem is we can't really do this with an interface. But we can change this around, and this is a place where we would use an abstract base class over an interface. So I'm going to change this to be a public abstract class, and we're going to call this Manuscript, and it's going to have an abstract method called Print. And we'll need to go ahead and make this public at this point. And then we're going to define a constructor here. So, we'll go ahead and do public Manuscript, and in this constructor, we want to take an IFormatter, and we're going to define this formatter. There's already a formatter that exists, and we'll go ahead and initialize this field formatter. So, now we're going to make sure that we have this formatter field. Let's go ahead and make this protected, so we can access this in our drive classes. And now we need to define this formatter interface. So now in Book here, you can see that it's going to use this formatter that we should define. We'll have to change this so that it's inheriting from Manuscript. So we don't have this format, and we don't have our formatter. So I'm going to go back into this Manuscript, and I'm going to go ahead and implement this interface formatter. I've created this IFormatter interface, moved it to another class here, and then in our Book here, we're going to want to create Format. So now we'll go ahead and create this Format method on the base class, and this Format method should be returning us a string, and it should take in a string that we'll call the key, and another string that we'll call the value. And we're also going to make this part of the interface so that anyone who implements this formatter needs to implement this method here. So now if we go ahead and look at what we have here, we can see that in our Book we now have this formatter that we can use to format. We also have to modify our Print here now, because it's going to override in this case, because we already have a Print method in our Manuscript. Remember, we changed this Manuscript to a class, an abstract base class, and so we already have Print declared, and so we're providing an override for it. So now if we go into Book, we're going to see here immediately that we can't have a parameter list constructor. So we'll go ahead and generate this constructor, that's going to take in our formatter, and it's going to call the base constructor, and pass that formatter. So this will ensure that we always have a formatter to work with. So now we'll just go ahead and modify our code here to use this formatter. And we'll do the same thing for our Text here. And remember, we don't have any concrete implementations of the formatter yet, so we don't know what it's going to do. We need to provide an implementation. But first we need to modify all the classes to use this formatter. Standard Formatter So I've gone ahead here and I've changed the rest of our classes, TermPaper inherited from Manuscript, and I've changed everything to use formatter, and to have the constructor for formatter. So now we've got everything using formatter, and this is going to be the implementation for printing, the Print method. You can see that we still have Print methods that are doing different things for each type, but they're all using this formatter, because this is the implementation for formatting the Text that we're going to output. So now we actually need an implementation for formatter. So we're going to go ahead and create a standard formatter. We'll create a new Class here, and we'll call this StandardFormatter. And we'll make sure that this class implements this IFormatter interface. And then the member for this will be Format, so we'll take the key and the value. So, in this case, we're just going to return string.Format, and we'll take our key, and we'll put this in followed by a colon, a space, and then our value. And so we'll go ahead and put key, and then value in here. So this is going to give us a basic standard format, just like we had seen before. And now, if we go into our Main Program, you'll see that we've got a few things that are broken here. We had changed our Manuscript from an interface to a base class, so I'll fix that, and now you can see that all the constructors here need a formatter. So we can go ahead and create a formatter. We'll go ahead and create a standard formatter, so we'll say formatter = new StandardFormatter, and we can pass this formatter into each one of these constructors, and now they'll use this formatter for their implementation. So now we'll go ahead and Run this code. And you can see here we're getting what we had initially gotten. We're printing everything out using the StandardFormatter. So, each one of these is using this formatter that's being passed in. Nothing really fantastic here yet, until we do this. Let's go ahead and create our reverse formatter. Reverse Formatter So I'll go in here, I'm going to Add a New Class here, and we'll call this BackwardsFormatter. So now we'll go ahead and implement this IFormatter, and we'll make this class public, and we'll go ahead and implement the members here, so now we have this Format method. And the way that we're going to handle this one is we're going to do return string.Format, and in this case we want to reverse the value, so we'll pretty much do the same thing here. We'll go ahead and provide the key with a colon, and then all that we're going to do here is substitute for the value. Instead of just doing value, we're going to go value.Reverse, and we're going to make this into a new string, and we'll do ToArray. So this should give us a reversed value for the string, and there's a couple ways you could do this. This is just a way that I'm going to do it for this demonstration. But this should basically reverse whatever we end up passing in here. So, we'll go ahead and go to our Main Program here, and we'll switch this out. Instead of using the StandardFormatter, let's use this BackwardsFormatter. Now, we'll go ahead and Run this, and you can see that everything is coming out backwards. If you go ahead and right now go and grab a mirror, and look at this through the mirror, you'll see that it'll look correct to you. Not exactly the most useful thing, but we've done something pretty neat here. We've extended the ability of the set of classes. Not just one class, but all of these classes. By creating a new formatter, we've changed their implementation. So, we've effectively decoupled this abstraction from the implementation. Fancy Formatter Let's go ahead and create one more formatter. We'll call this the FancyFormatter, just to see this in action here. So we'll Add a New Class. We'll call this FancyFormatter, and we'll go ahead and implement this IFormatter. And in this case we'll go ahead and return string.Format, and we'll make this maybe a little more fancy here. (Typing) We could do, you could do whatever you wanted with this. But we'll go ahead and put the key and the value, and so now we can use this FancyFormatter. We'll just switch our program here. Instead of using BackwardsFormatter, we'll use FancyFormatter, and we'll go ahead and Run this, and you can see we're getting some fancy results here. What We Did Let's take a moment now to go over what we did in our examples. So what we're looking at here is a UML diagram. This is typically what you're going to see when you see the Bridge Pattern, and this can be kind of confusing. But, based on the examples that we've done so far, I think now we can understand this, and explain this, and see how what we did in the code mirrored this UML design pattern. So, looking over at the left here, you can see that we have an abstraction. Now, the abstraction that we had created was a manuscript, and that was a way of having some data, some text, something that someone could read, or print. That was the concept behind this abstraction. We had some refined abstractions that implemented this manuscript interface, and we had a Book. We had a Paper. We had a FAQ. We could've had a lot of different reading materials, or manuscripts that refined that abstraction. Then, over on the right, we had an implementor. And that implementor was a formatter, because in order to implement a manuscript, or this idea of a manuscript, we needed some way for it to be formatted. A book has formatting, a paper has formatting, any written material has some kind of formatting applied to it. Now we didn't want the formatter to be tied to the type of manuscript. For example, we didn't want to have a book being forced to be one particular type of formatter, and every type of book that we created, we would have to create a new formatter, just like we had talked about earlier with the Burger example, we didn't want to have all these combinations of every abstraction, and every implementation choice. So if we look down further at this implementor, we created an IFormatter, a formatter implementor that the abstraction uses to implement the formatting of the Book through its Print method. Then, this implementor had multiple concrete implementors, and we had a StandardFormatter. We had a BackwardsFormatter, and we had a FancyFormatter. By doing this, we had made it so that we could add any new formatters that we wanted. We could add more abstractions that we wanted. We could add more manuscript types, and we could combine those in any way that we wanted. And this really allowed us to reduce that hierarchy that had started off with a really big hierarchy of classes in order to handle every single type of implementation. And one thing that's really important to realize about this Bridge Pattern is you can apply it multiple times. And it can get a little bit tricky here, but if you think about it, there's other aspects to a manuscript besides formatting. We could have different types of printers. We could have different types of language, or text in there. And we could vary each one of those specific types of implementations that belongs to a manuscript using the Bridge Pattern. We could Bridge them all together, and we could mix and match, and have our own customized implementation of that abstraction. Common Usages So the Bridge Pattern can sometimes be difficult to identify, or to figure out when should you use it. So I'm going to give you a few tips on some of the common usages that you'll see the Bridge Pattern so you can recognize this a little bit better, and identify it in code. The first instance where you might see the Bridge Pattern commonly used is in the user interface. A lot of times you'll see multi-platform user interfaces designed using the Bridge Pattern, and they'll have some kind of drawing APIs. You might have some shapes, or some kind of components, or widgets that can be drawn, and then you'll have different implementations that do the drawing based on the different operating systems. So that's a good instance for using the Bridge Pattern. Another common one is persistence. You might create some kind of persistence abstraction so objects can be persisted, and then the type of persistence, the implementation of that persistence might vary. You might have a database persistence. You might have a file system persistence. You might have a streaming over the network persistence. Whatever your persistence layer is, you're bridging those two concepts, abstraction of the ability to persist, and then the actual implementation of persistence. And then another common usage if you're familiar with the .NET provider model, in many cases the provider model for .NET is implemented in terms of a Bridge Pattern. So a lot of times you'll see that you might provide, for example, an authorization provider, or membership provider. In those cases, what you're really doing is you're providing an implementation for some kind of abstraction. Your abstraction is going to use that implementation. Really, the key thing to keep in mind here is anytime that you're creating a large class hierarchy, and you're having to split those classes based on different implementations, as well as different abstractions, and doing some kind of combinations with those, that's probably a good time to use the Bridge Pattern to simplify that class hierarchy. Summary So now you should be pretty familiar with using the Bridge Pattern. It's really not that complex of a pattern once you understand how it should be used, and how to implement that pattern. We took a look at what the Bridge Pattern is, saw a real life type of example when we talked about how you would create a menu that would separate the combos from the actual sandwiches. Then we went through some code here, and we created our class hierarchy of basically different types of manuscripts, and we saw how we could use a formatter as an implementation that we could decouple from this abstract idea of a manuscript, and how that allowed us to swap in different formatters, and not have to create a huge hierarchy of different classes to handle each type of formatting. Finally, we took an architectural view of the Bridge Pattern, and saw what the real UML diagram for this type of pattern looks like, and the official names for the things that we had created in this pattern. Well, hopefully this module has helped you to get a better understanding of the Bridge Pattern, and you should be able to use a Bridge Pattern successfully in your software development. The Builder Pattern Introduction Hi. This is John Sonmez from Pluralsight, and in this module we're going to be looking at the Builder Pattern. So let's go over what we're going to cover in this module. First thing that we're going to do is we're going to kind of overview the entire Builder Pattern, and we're going to kind of look at this from a high level. We're not going to go into the details, and look at the UML diagrams, but we're just going to kind of try to grasp the concept of why we use the Builder Pattern, and what it's for. Then we're actually going to dive into some code here, and we're going to use some problems to get us to the point where we're going to refactor our code into the Builder Pattern. So the first problem that we're going to look at is the problem of having too many parameters. And this is probably a common problem that you've seen in your code, and we're going to see how we're going to make that code, instead of having too many parameters in a constructor, have some properties that we're going to be able to set, and we're going to eliminate that problem. But, as soon as we eliminate that problem, that's going to bring us into problem two, where we're going to be order-dependent. So now it's going to be dependent on the order that we set, the properties, or do things on our object to create our object, and so that's going to be an issue for us. So we're going to refactor that code a little bit more, and we're going to get to a point where we're going to be not order dependent, we're not going to have too many parameters, but we're going to find that we need to be able to construct different objects, or different constructions of that object, and so we need to be able to abstract out the process from the data. A lot of times in patterns you're going to find this common idea of abstracting away data, and process, so we can take logic and data, separate them out, and we can put the logic in one place, and the data in another place, and that's what we're going to do, and that's going to give us actually a Builder Pattern. So then we're going to take a look at what we built. We're basically going to overview what the real Builder Pattern is. We're going to look at the UML diagrams there, and we're going to go over the roles, and we're going to see that we'd actually refactored our code into this final product of the Builder Pattern. Then finally, we're going to go back into the code and we're going to look at some variations of the Builder Pattern. We're going to see some things that a lot of people think are Builders that are not really the true Builder Pattern, even though they're a kind of Builder, like a String Builder for example. And kind of the goal of this module on the Builder Pattern is to get you to the point where you understand the Builder Pattern from a practical sense. We're going to refactor our code to get there, and that should really help you to understand exactly how the Builder Pattern works, and why you would use it instead of just blindly applying it. Understanding Builder So now let's talk a little bit about the general concept of the Builder Pattern. What is exactly the Builder Pattern? Well, this definition is kind of the Gang of Four definition, which you can find in the Classic Design Patterns book by the Gang of Four that really explains what design patterns are. It's kind of the basis of understanding all of design patterns, and where they kind of came from. And this definition, it might be a little bit hard to grasp, but let's try and break this down. So, it says that it separates the construction of a complex object from its representation so that the same construction process can create different representations. So, if we kind of walk through that, what are we really doing here? We're separating the construction of a complex object. So, we have a complex object to start with, so this pattern's going to be applied to some object that's complex, not a very simple object. And we're going to separate that construction from its representation. So, the construction is a process. Its representation is the data. So you can think of this as process and data, or logic and data. So we're going to separate logic from data. So once we have these things separated, the reason why we're going to do the separation is so that the same construction process can create different representations. So basically, if we had to summarize this, what we're really saying here, is we want to be able to reuse this logic to work with a different set of data to build the same thing. The only difference is going to be the data. So, that's really the gist of what a Builder is. It's really not that difficult even though some of the pieces, and when you look at this, it might seem a little complex, just remember this goal is very simple; separate data from logic, reuse that logic. So let's go through kind of an example, kind of a real world example of a Builder Pattern in practice, and why it might be useful. So I'm going to go through this dialog here, and we're going to kind of see how making a sandwich is kind of like the Builder Pattern, or how we could benefit from it. So, hey! Yeah? I want a sandwich! Okay, well what kind of bread do you want? Wheat. Okay, what size? One foot long. Okay, what kind of meat and cheese? Turkey and Swiss. Do you want it toasted? Yes. What kind of vegetables? So on and so forth. I'm sure if you've gone to Subway, or one of these places where you can go through and have your sandwich made, that you've gone through this process before, and it can be a little bit annoying, because do you really want to answer all these questions every time. Sometimes it's easier to just pick number five off of the menu, and so this is kind of an example of maybe you have some code that's like this. Maybe you have some code that has all this extra dialog, and maybe you've thought, well I can put it all in a constructor, and so you have a large constructor where you pass in all these parameters, all these options. Or maybe you construct the object, and then after you construct the object, you start setting fields on it, or properties, in order to build this thing. And there might even be some steps that are involved, some process to finally get this final object built. So, you kind of go through this dialog in your code. Let's look at another example of a dialog. Now, let's apply this Builder Pattern to the sandwich scenario, and this is maybe what the dialog would be like in that case. Hey! Yeah? I want a sandwich that I have designed called the super turkey pickler. Do you have instructions? Yes. Here's a list of the ingredients. Okay, I can follow my steps and use those ingredients. So, this dialog is much shorter. This is kind of a scenario that might not really happen in a real sandwich shop, but it'd be pretty efficient if it did. If you came in with a list of ingredients, in fact, maybe some people do this. Maybe if you're ordering for a friend, or a group of people, or for your whole work, and you have a list of ingredients of what sandwiches they want, or maybe you did pick one off of the list, maybe a combo meal, or something like that. But the basic idea here is that you're only providing data. You're not going to the sandwich shop in this case, and you're not saying, or you're not going to say to them, here's my sandwich that I want you to make, and here's what I want you to do. First, go get some bread from the oven. Then cut the bread. And then put some mayonnaise on it, and then put some mustard on it, and then toast the bread, or whatever the step is. Then apply meat. You're not going through that entire process and giving them detailed steps. Instead you're giving them a list of ingredients, and then they're going to follow the steps that they already know on how to make a sandwich, and every place that there's a question, or in that step they need some data, they're going to get that from your ingredients list, and that's going to make the sandwich. So that's kind of what we're going to do with the Builder Pattern, that's kind of how we're going to apply this. If you think about code scenarios, where this same thing is going on, where you have this process, and there's some data differing, and it's in your code, it's not abstracted, they're not separated, we're going to use the Builder Pattern to do that. Problem 1 So now let's take a look at some code that is an example of a situation where you might want to start working towards a Builder Pattern. We've got our Sandwich class here that I've created in this BuilderDemo project. And I've basically just created a Sandwich kind of like we had talked about, and it has this kind of really big constructor. So you can see there're a lot of parameters for this constructor. We've got some private member variables, and it's got a method to Display the Sandwich, so it'll write out to the Console the attributes of the Sandwich, and we've got some enumerations to define, the MeatType, CheeseType, and BreadType. And so I've created an example program here creating our Sandwich, and you can see that we had to pass in all these parameters, and it can be kind of confusing to know which parameters do we need, what order should they be. This is something that you'll commonly see in some class that's kind of grown over the years. And let me go ahead and Run this so we can see what the output is. You can see here we get Sandwich on Wheat bread. Meat: Turkey. Cheese: American. Veggies: Tomato. So it's correctly performing, but the problem is really this constructor, and in a lot of classes like this, you might even see multiple constructors that are chained together, one that takes one less parameter, different variations of these parameters, and some defaults, and this can be a real mess, and really hard to figure out which constructor to use, and when. So, the first step that we can do here is we can think about changing it so that instead of passing all these parameters in the constructor, we could use properties here. So we could say, the caller of this class, if you use this class, you don't have to specify everything in the constructor, but you can just set the properties that you want. And this seems like a decent approach, so let's go ahead and see what happens when we do that here. So, I'm going to go ahead and refactor all of these. I'm going to use ReSharper to do this to make it a little quicker. But we're basically just going to take each one of these and just make it into a property. I'm just going to choose Auto Property here. And we'll just do this for each one. And you can actually use a shortcut here, Ctrl+R+E. (Typing) And so now that we've got all these fields, all these properties now, we can basically get rid of this constructor, because we don't really need it. So now we can change our code a little bit here. If we go into our Main Program, we don't have a constructor anymore, so we can basically just set the values that we want. So, I'll go ahead and change this so we create our new Sandwich. We'll have a variable here to hold the Sandwich, and then we'll call on this Sandwich, and we'll choose BreadType = White. And you've probably written code like this yourself. One thing that we'll need to do is make it so these aren't private, so we can set them. So, again, one reason why I'm doing this here is look what we're having to do. We're having to expose all of these, because we no longer have the constructor, so we're having to make it so that you can set these. So these values, where we kind of had an immutable object before that couldn't be changed, now we have a changeable object. So that's one thing to keep in mind here. And, like I said, this is pretty common I think to see code like this where you have to basically set the properties on it. You have to remember what they all are. So we'll do a false here, and we'll say IsToasted = true, HasMustard = true, and then we'll set the Vegetables equal to a new List, and we're doing this of string, so we'll put Tomato, and we'll put Onion. So now we've created our Sandwich, and we can call sandwich.Display. Let's go ahead and Run this and see what we get here. So you can see, this has worked. We've got basically everything here. But there's a problem with this code now. In fact, there're a couple of problems with it. We'll get to those problems next. I just want to point out here the problems that we've solved, because I think it's important we have solved some problems here. The big problem that we've solved is this huge constructor that we used to have. Now we have these properties. This is a little bit cleaner. It's a little bit easier to just set the properties, instead of having to have this big constructor. It makes it a lot easier to construct this object, and if we had a lot of different constructors that had different optional parameters, this kind of would work to simplify that. So, this is kind of step one. We've eliminated that big constructor. Problem 2 So now that we've solved one problem, we've kind of created another problem for ourselves. In fact, we've created perhaps a worse problem because now we have the problem of having to remember all of these properties to set. And we have to kind of keep track which ones have we already set. It's a lot of work. It's a little bit more clear to read, but we have a problem that we might not set all of these, and we might need to set some of these. In this simple example, there's not really much of an issue here, but in a lot of classes that you might be creating, there might be a lot more logic. In the Sandwich class we only have really this Display logic, but you could really think of a lot of situations where you'd have more logic going on, especially when you're constructing the object itself. In fact, we're going to build a little bit of that logic as we try to solve this problem. Another problem that we have here is that you can see that we have no way to control the order of the creation of the Sandwich now. Before when we had everything in the constructor, we could kind of take all the parameters in at once, and then work with that. We could basically have some steps, or some process that we're following in order to construct the Sandwich. In this case, we're not really following any steps, but we don't have the ability to do that either. For example, at some point we might add some validation logic to the Sandwich class, so we might say that, well, before you can choose the MeatType, and the CheeseType, we need to know if the Sandwich IsToasted, and we need to know what the BreadType is. And so we might put some validation in there to check for that. And, in fact, we can't really do much here. We can just throw an exception, or we'd have to fail if this object isn't constructed all the way. We could actually have a partially constructed object if we left off some of these properties, and some of these were critical. So, we can run into a lot of problems with the situation that we have now. But we can easily fix this by creating a class to ensure that these steps are done in the correct order, that the correct things are set. So, we could basically create a class that does this. So I'm going to go ahead and create that class now. I'll create new Class here, and we'll call this MySandwichBuilder, and this is going to build this exact sandwich. So what we'll do here, is we'll go ahead and make a method on this Sandwich Builder to return our Sandwich, and we'll call this method GetSandwich, and here we'll just return a sandwich that we're going to store locally, so we need to actually create a member variable to hold this. And we'll actually make this a member variable. So what we'll go ahead and do here is in our constructor, or actually in our class, we can just make a method to create a new sandwich, and we can call this method when we want to create the sandwich. So we'll make our method here. We'll say CreateSandwich, and in this method it's first going to create a new Sandwich, so it'll set our sandwich = new Sandwich, and then it'll basically do what we did here. So we'll cut this code out. We'll put it in here, and then this gets Sandwich and will return a sandwich. So we've created a Builder that's going to handle this for us. And the nice thing about this is that it's making it so that we don't have to remember these steps. It's all kind of in this class, and if someone wants to create this special kind of Sandwich, this MySandwich here on White bread with Cheddar, this exact formula, they can do this without much trouble. They don't have to remember all the steps. So, this would actually make sense to have a couple of variations of this potentially, but we'll get to that a little bit later. For now, we're just kind of refactoring this code as it is. So now, what we have here is we're going to basically create our sandwich builder, and it's a MySandwichBuilder. It's just building a very specific kind of sandwich. And so we'll call builder.CreateSandwich, and then we'll set our sandwich = builder.GetSandwich. So now we should have a completed Sandwich. There should be no way that this Sandwich is not constructed properly. So let's go ahead and Run this code. And you can see, it's worked out. We've gotten everything that we should've gotten for the Sandwich. We've made this code a little bit better here. We still have this Sandwich class with all these properties, which may be a problem, but at least we don't have all of this logic here in our Main Program. We've kind of encapsulated it into one place where it's all in this Builder. So, we're still building a very specific kind of Sandwich, because we're building each one of these things how we had set them initially. Now, another thing that we're going to want to do here in this Builder is kind of have some kind of technique to our building of the Sandwich. So, a Sandwich building actually has a process, and has some steps, and so we can actually build some logic into here. Where, when we didn't have the Builder before, we just had the Sandwich class, there really wasn't any notion of the logic of building a sandwich, but in most cases there's going to be some kind of logic involved in doing some kind of complex object construction. So let's go ahead and change this up a little bit. Instead, for our CreateSandwich, let's go ahead and figure what the steps are. So the first step might be PrepareBread. So we'll go ahead and create this method here, and then the next step might be ApplyMeatAndCheese. This is usually done together. Then we might have another step here for ApplyVegetables, and then maybe a final step here of AddCondiments. So let's go ahead and create these methods. PrepareBread, we're going to go ahead and set the BreadType, and we'll set the Toasted value. So at this point we could consider that the bread is prepared, and we need to create our new Sandwich, so we'll go ahead and put that at the top here. That's the first step really. Then we need to ApplyMeatAndCheese, so we'll create this method, and we can kind of take these parts out. And actually in doing this, we've kind of discovered a problem here. We were not actually putting meat on the Sandwich, so we probably made a mistake here. So let's go ahead and correct this. Let's set the MeatType = Turkey, and let's go ahead and add a ApplyVegetables, and here we'll set our Vegetables, and then we have this AddCondiments, and here we'll add these too. So I'm still showing red here, but this is working if we Run this. We can see that it's actually working here. So what we've done now is we've kind of refactored this a little bit more. This makes a little bit more sense now because we have some steps. We have our Sandwich being created initially. We've got PrepareBread, ApplyMeatAndCheese, ApplyVegetables, and AddCondiments, and this has kind of organized this so that this class will be a little bit easier to maintain, and you can kind of understand this process here. And you can imagine that in a real class, in a real program that we might be working on, we might need to really specify this order, because we might have some validation, or, in doing these steps, it might be doing some things that are going to be dependent on the previous step. For example, we don't have it in this case, but maybe before you apply the meat and cheese, it needs to check the bread type in order to determine some way to put the meat on. Maybe it needs to check if it's toasted, or check what the bread type is, and to make some kind of decision based on that, or do some validation. So, we've kind of refactored this so that we could allow for that. We've got some explicit steps here. So again, now looking at our entire code, we're looking a lot cleaner from the Client standpoint. We have a pretty simple class here, and we've got this Builder that's going to Build this the right way for us every time, instead of us trying to remember this. Especially if we have to create the same exact type of Sandwich in different places in the code. Problem 3 So we've solved some problems here, but now we have a new problem. And you don't really see this problem until we try to do something like this. So at this point, we want to create a new type of Sandwich. We want to create a Club Sandwich. We have this MySandwich, which is that special Sandwich that we had created. Now we've got this Club Sandwich. So if we were to go ahead and create this class, we can go ahead and try and create this class here, and I'll go ahead and move this to its own file. The first thing that we're going to realize here is that, well, we don't have any kind of standard definition of how to create a Sandwich. We might go here, and decide, okay, let's go ahead and Copy all this code, and Paste it into our new Sandwich type. So, this is really kind of a bad thing to do. And you can see that we'll have to Paste this code, and we'll need to modify this in order to make our ClubSandwich. So this is quite a bit of work here, and we're copying some code here. This really is not a good approach. So, what we really need here is we need some kind of description of each one of these steps so that we are forcing this ClubSandwich, or any other Sandwiches that we make, to kind of follow these same steps, or to have all of the same things that are required in order to be built, we need a common interface. So we can go ahead and do that. We'll go ahead and create a new Class here, and we'll just call this class SandwichBuilder. And in this, we'll define what a Sandwich should be like, or what a SandwichBuilder should be like. So, if we look at our MySandwichBuilder, we had all of these steps here. So let's go ahead and take some of these things and move them into this SandwichBuilder. Well the first thing we need is the Sandwich itself, so let's go ahead and create protected member variable we'll call of type Sandwich, we'll call this sandwich. Then we're going to need this GetSandwich method. We need to be able to return our sandwich. So, we'll go ahead and put that in to our Builder here. We'll make this an abstract class here, and this is going to return our sandwich. Now, we're always going to create a Sandwich the same way, this new, regardless of what type of Sandwich we're building, we're always going to do this. So we can take this step, and create a method for this, and we'll go ahead and create a method, we'll call it CreateNewSandwich, and we'll go ahead and initialize our Sandwich this way. These are common things that are going to be in any sandwich. If we look at MySandwich here. The other thing that we're going to have is we're going to have these methods. So, let's go ahead and move these methods in. And we're going to define abstract methods here so that anyone implementing this is going to be forced to implement all these methods, so we'll do public abstract void, and these are each one of the steps. So now we've got a pretty good skeleton class here that we can make all of our Sandwiches inherit from. So if we go to our MySandwichBuilder, we'll go ahead and make it inherit from SandwichBuilder. And you can see now that we're actually overriding these methods, so we're just going to add the override, but we've still got a bit of a problem here. We've still got this logic of creating a Sandwich here. In our SandwichBuilder, let's fix this real quick, we have the logic to actually new the Sandwich, and we say that we have to have all these methods, but we don't have a class that's really having the logic. Instead, if we make our ClubSandwich, again, we're having the same problem here, so even if I make this one inherit from SandwichBuilder, we'll fix these overrides, and we can make this ClubSandwich a little bit different. We'll put true here. We'll make it have Tomato, Onion, and Lettuce, and we'll make it have Swiss cheese. So, the problem here, you can see is, we still have this CreateSandwich method, and it's defining the steps. Well these steps are common between the two. We've kind of eliminated a lot of the duplication here between the two, and we've made it easy to create a new Sandwich, but we still have this problem here. So, we're going to create a new class that is going to basically control doing the actual creation of the Sandwich. So I'll go ahead and Add a New Class here, and we'll call this class SandwichMaker, because this class is actually going to make the Sandwiches. And so the idea of this class is that it should be able to make a sandwich. It should be able to have that process of making the Sandwich, regardless of what type of Sandwich it is. So, let's go ahead and create the constructor for this, and our SandwichMaker is going to use one of the Builders, either a ClubSandwich Builder, or this MySandwich Builder, so we can make it take a parameter here that will be of SandwichBuilder. We'll call this the builder. We'll go ahead and create a field for this. So, then it should be able to use this builder to create the Sandwich. So, let's go ahead and create a method to do that. We'll make a method called CreateSandwich, or even BuildSandwich maybe is a little bit better of a name in this case. So, this method is really going to be the one that is going to handle all of these steps here, and because we know that we've overridden all of these methods, we know that we're going to have these steps in any class. So, we'll go ahead and take these steps, and let's put them in the SandwichMaker. So, the SandwichMaker should be able to basically call builder.PrepareBread, builder.ApplyMeatAndCheese, builder.ApplyVegetables, and builder.AddCondiments, and remember that we still need to make it so it creates that new Sandwich. So, now in order to build a sandwich, we're going to create a new Sandwich, PrepareBread, ApplyMeatAndCheese, ApplyVegetables, AddCondiments, and this logic is encapsulated in the SandwichMaker. We need some way to get the Sandwich back out, so we'll go ahead and put a method on here that returns a Sandwich, called GetSandwich, and this will return us builder.GetSandwich. So we're going to actually get the Sandwich after we've built it. So now we can go back into our classes here, and go into MySandwich, and we can take out this CreateSandwich. We don't need this anymore. So now you can see that all that's in our SandwichBuilder is basically just the implementation of each one of these steps. In fact, we don't even need this variable anymore, and we don't need to GetSandwich. We have a Sandwich declared in our SandwichBuilder. If I go here, we've got this declared, and it's inheriting that, so when you look at this now, all it is the steps. This is really looking like ingredients now. It's not looking like any kind of process. This has really become a Data class, and so now it's real easy to define a formula for building a Sandwich. We can fix this ClubSandwichBuilder the same way. Take out all of this, and again, no more logic, really just data in here. So now our Maker is controlling the process. This Builder is enforcing the structure, the steps, and so now we can utilize this in our program very easily. So we're just going to clear this out, and figure out our new way of creating our Sandwich. So now, we'll create sandwich1, and we'll basically need to create our Builder first, or our SandwichMaker, so let's go ahead and create a new SandwichMaker, and remember we need to pass a Builder to it, so we'll decide what type we want. Let's do a MySandwichBuilder. So we've got our Maker here, and on our sandwichMaker we can call BuildSandwich, so it's built, and then we can call GetSandwich, and that's going to get us our Sandwich, and then we can Display it. So let's go ahead and Run this, and you can see here it's built this Sandwich, and it's Displaying it. And we can change this. We can create a new Sandwich, and we can build the other type. So, instead of building the MySandwich type, we'll go ahead and build this ClubSandwich. So we'll just do a new ClubSandwichBuilder, and we need to set this to sandwichMaker2, so I'm going to go ahead and Run this, and you should see both of them are being made here, and you can see that they're slightly different. This one has the Lettuce. So, we actually went ahead and implemented this full pattern. Now this is kind of the full Builder Pattern, and you can see here what we've really been able to do, is we've made it very easy. If we wanted to create a new type of Sandwich, we could basically just go in here, go to Add, New Class, and we could create our SuperSandwich, and all we have to do is implement this SandwichBuilder interface. In fact, that should probably be SuperSandwichBuilder, and as long as we implement all the members of this interface, then we'll have another Builder, and we don't have to put any logic in here. We just have to implement each one of these steps, and then our SandwichMaker knows how to make a Sandwich. What We Built So now that we've refactored our code, and we've actually built an application using the Builder Pattern, or we've built the Builder Pattern in our code, let's take a look at the formal definition. Let's look at what we actually built, what is this design? So when we first talked about the Builder Pattern, we didn't really go into the details. We kind of had a high level summary. We kind of basically said, when you're using the Builder Pattern your separating your logic from your data, so that you can basically reuse that logic. But now we're going to kind of give the formal definition. So, if you look at this UML diagram, you can kind of see all the components that we had built in our code. And, each one of these components works together, and this is just the basic UML diagram. This is kind of how you would see the Builder Pattern explained in a lot of text books, or places where you would read about the Builder Pattern. And I think it's a little bit hard to digest it here, but it should be easier for us to understand now that we've actually seen it applied. So, looking at this diagram, you can see that the core is the Builder. We have a Builder, and that Builder is used by a Director. And that Builder is implemented by a Concrete Builder, so we have a Concrete version of our Builder, it's the thing that actually is an object that we can instantiate. And then we've got a Product that the Concrete Builder is able to produce, and it operates on that. So, we basically create our Builder, our Concrete Builder. We give it to the Director class, and that Director class follows a step, or has the process, that's where the process logic is, and it uses that to Build our Product. And so the Builder in this example is going to define for us what the steps are, and the Director is going to put those steps in the right order. So that's kind of the basics. It's really not that complex of a pattern. You just have to remember here that we're building a single product, we're differing the data on that product, and really, where's the logic here? It's really in the Director. The Director controls the logic, the Builder defines what the steps are, the Concrete Builder provides the implementation, and they all work together to produce a Product. So let's take a look at each one of these roles a little bit more explicitly so that we can have a good definition and understanding of these for when we need to apply this pattern, or to recognize this pattern. I think it's real important to really understand a pattern, not just what it does, but kind of how you would see it in other people's code, and how you need to talk about it when you're explaining how to implement this to someone, because we have to have the same language if we're really going to be effective with patterns. So, the first role is the Director. And we talked about this earlier. And it's basically going to use the Concrete Builder. So the Director is going to be given an instance of the Concrete Builder. You, as the Client code, or the Client, is going to need to provide a Concrete Builder to tell the Director what to build. Now the Director, he knows how to build. He doesn't need the steps. You don't give the Director the steps, you just give them the ingredients, or this Concrete Builder that the Director is going to use. Every time that the Director hits a step that he knows what order they're supposed to be, it's going to look to the Concrete Builder for that implementation of that step in order to know what to do in order to build this object, and then from this Director you're going to be able to ask for the completed object. So the Builder is basically just the abstract interface, or it could be an Abstract class, that really defines the steps that the Director's going to use. And the only reason why we have this class is basically to make it so that the Director can count on certain steps being named a certain way, and existing for each of the actual Concrete Builders. So this Builder is really just an interface. It's just a set of rules, a set of steps, that both the Director can depend on, and that the Concrete Builders have to implement so that we can basically abstract this concept of building. So the Director doesn't need to know about each individual type of Builder, it can just use this interface that's defined here in this Builder interface, and it can count on all those methods existing there. And the Builder also is going to hold an instance of the Product that we're going to create. Next we have the Concrete Builder, and the Concrete Builder, this is a class that we should be implementing multiple of. So, if you only have one Concrete Builder, maybe you shouldn't have applied the Builder Pattern because really the purpose of the Builder Pattern is to make it so that you can kind of reuse that Building logic for different data. If you only have one set of data, you're creating a lot of overhead, not getting a lot of value. So, we should multiples of these, and these are actually going to implement that Abstract Builder, so it provides that implementation for that interface that we created in the Builder, and this is a recipe, or even more specifically, it's a set of ingredients. It's going to basically have the instructions, or rather the data that is going to be used by the Director. So the Director is going to use the Abstract Builder's interface, but since this Concrete Builder's going to implement that interface, it's going to actually provide the real data, or the steps, the implementation of those steps that's going to be used by the Director. Then finally, we have the Product, and the Product is basically just what you're building, and that's just going to be the data. And remember, this is going to be some kind of a complex object. If it's just a simple object that doesn't have much data, it's not going to make much sense again to use the Builder Pattern, because the whole point is that this is not an easy object to build. If this is just an object that has one data member, using the Builder would be overkill here, because you're not really gaining any benefit here. There're definitely some tradeoffs because you're increasing the complexity of something. You need to be really reducing it in another way when you're using this pattern. So, one important thing to remember about the Product is it's not a different type. You don't have an inheritance hierarchy of Products. You could possibly have this, but in general, in this pattern, it doesn't say that you must. What's really happening here is that you're getting different data. And this is a point that a lot of people confuse with the Builder Pattern. They want to make a hierarchy of Products, and really you're having one type of thing, but you're having different data for it, and that's really what the Builder is designed to do, is to fill in that data. Variations So let's take a minute to look at some of the variations of kind of the Builder Pattern that aren't really the Builder Pattern, but a lot of people think they are. I just wanted to clear this up so that we aren't confused about what really is the Builder Pattern when we're talking about the true Builder Design Pattern. So the first one that I see a lot is this StringBuilder. And StringBuilder is a great class, but it is not really the Builder Pattern, so you typically would use this this way. Create a StringBuilder, and then you might do stringBuilder.Append, and then you might add Hello, and then you might keep on appending onto this, (Typing) and so forth until you finally call on StringBuilder ToString. And, while this does build up a string for you, you can see that it is not the Builder Pattern, because it doesn't have all of these elements of the Builder Pattern that we had talked about. In our example here, we had a Director, which was our SandwichMaker. We had our SandwichBuilder, our Abstract class, and then we had each one of the Concrete Builders, and we had our Product. In this case, we really have just a Builder and a Product. We don't actually have the full pattern implemented here. The other way that you'll see things that are kind of similar, but aren't quite the Builder Pattern, is you might see something like this. You might see an API that works in such a way as to do new Sandwich, and then you might see a fluent API here where on this it'll basically let you set the BreadType, and you might say BreadType.Wheat, and then maybe you could chain this together, and you could say CheeseType, and then you would do CheeseType.Cheddar, and so on and so forth. So you could add as many parameters as you want by chaining all these method calls together. And while this is great for an API for making something fluent, a little bit easier to use, it's really not accomplishing the goal of the pattern of the Builder, which remember, what we're really trying to do here is separate out our logic from our data so that we could enforce some rules. We could enforce a process, and so, for example, in our SandwichMaker, we have this process of how to create this Sandwich. When you look at either the StringBuilder, or this kind of syntax, you're not really enforcing a process. There is no requirement for you to call certain things in a certain way, and even if there was, you would be responsible for that as the Client, whereas in the case of the true Builder Pattern, like this SandwichMaker, the SandwichMaker is responsible for this, and you're just providing the data. So that's just one difference. If you see the word Builder being thrown around a lot, don't get confused by StringBuilder, or this kind of syntax. Now that you've seen this module, you really know what the Builder Pattern is. Summary So let's go over what we covered in this module. The first thing that we did is we talked about the Builder in general. We didn't go into the technical details. We didn't go into the UML diagrams, but we simply defined that a Builder, its purpose is basically to just separate the logic and the data from the building of an object, or a product, and to be able to reuse that logic. So, we want to be able to build different variations of some complex object. We're going to pull that logic into one place, that's called the Director, and we're going to use that to build different kinds of a Product. Then we went ahead and we looked at some problems. So the first problem we looked at was the case where we had too many parameters. We had created our class, and we had made a constructor that had a lot of different parameters. We refactored that code, and we basically made it so that we had some properties that we could set and get, and some steps, and so we eliminated all the parameters from the constructor, but then we got into a new problem, which was that our steps were order dependent, and we could have partially constructed objects. We had this kind of dependency of the order that things were done. So, we refactored our code one more time, and we changed it so that we explicitly controlled the order. We could basically create a class that would ensure that things were done properly, and done in the right order. The problem we started to face there though was that we wanted to create different variations, or different constructions of that class. So once we got to that point, we actually did one more refactor, and we refactored into the Builder Pattern, and that made it so that we were able to actually separate that logic from the data, and provide different Builders to build different variations of that data. So then we went ahead and we took a look at what we built. So, this is where we actually looked at the real UML diagram. We went through all the roles. We talked about the Director, the Builder, the Concrete Builder, and the Product. And then finally, we talked about some of the variations that exist, some of the things that look like the Builder Pattern, or sound like the Builder Pattern, but aren't really the official Builder Pattern. We looked at StringBuilder, and some other things that kind of seem like Builders, and kind of serve somewhat of the same purpose, but could be a little bit confusing to someone when we're talking about the Builder Pattern. Chain of Responsibility Introduction Hello. This is Robert Horvick with Pluralsight, and in this module we'll be looking at the Chain of Responsibility Design Pattern. The Chain of Responsibility provides a simple mechanism to decouple the sender of a message from the receiver. In a nutshell, the Chain of Responsibility is an ordered list of message handlers that know how to do two things; process a specific type of message, or pass the message along to the next message handler in the chain. Let's take a look at a simple example to see what I mean. In this example, we have a single message sender. The message sender is aware of the first receiver in the chain. The first receiver in the chain is aware of the second receiver, and so on. When a message comes in to the sender, he can only do one thing, pass the message on to the first receiver. The first receiver now decides if it is capable of handling the message or not. If it is not, it will pass the message along to the second receiver. The second message receiver now has the same decision to make. If it can handle the message, it will send a response back to the sender. In this example, the sender sent a message, and it was handled by the second receiver. But the sender has no awareness of the second receiver, only the first receiver. It's important to note the third receiver was in no way involved. It did not receive the message, and it is not aware the message processing occurred. The Chain of Responsibility has several traits. The sender is only aware of one receiver. Each receiver is only aware of the next receiver. Receivers process the message, or send it down the chain. The sender does not know who received the message. The first receiver to handle the message terminates the chain. In this respect, the order of the receiver list matters. If the first receiver, and the second receiver can both handle the same type of message, some sort of message handling priority would have to be built-in to the list. Traditional Usage The traditional Chain of Responsibility Design Pattern has three participants, the Client, the Message Handler interface, and a series of concrete implementations of the interface. The Client and Handlers link together to form the Chain of Responsibility. Motivating Example Let's begin by taking a look at a more concrete example. In this example, William has generated an expense report. He would like to have the expenses approved so he can be reimbursed. He sends the expenses to his manager. The expenses are too large for his manager to directly approve, so she sends it on to the vice president. The vice president is also unable to approve such a large expense, and sends it directly to the president. Now the president has the ultimate authority, and will review the approval, and give William a response. Let's take a look at a solution that does not use the Chain of Responsibility Design Pattern. Demo: Expense Report Let's start by taking a look at our expense report sample. There're a few basic interfaces we'll cover before we begin to get everybody up to speed. First, we have an ExpenseReport. An ExpenseReport simply has a total value, the dollars and cents of the expense. Next, we have an ExpenseApprover. An ExpenseApprover is an employee who can approve an expense. And then we have an ApprovalResponse; Denied, Approved, or Beyond the Approval Limit for that ExpenseApprover. The ExpenseReport concrete implementation is very straightforward. It simply exposes the Total as a property. The Employee class is the concrete implementation of the ExpenseApprover interface. Its constructor takes a string, which is the name and the decimal value for the approvalLimit. The ApproveExpense method simply looks at the ExpenseReport, and determines if the value is above, or below the approvalLimit. If it's above the approvalLimit, BeyondApprovalLimit is returned. Otherwise, the Expense is Approved. Here we have our Expense Approval application. Our sample data is four workers. These workers represent a very simple management reporting structure. It begins with William, who reports to Mary, who reports to Victor, who reports to Paula. Each member along that chain has an expense limit. William's limit is 0. He's not able to approve any expenses. Mary's limit is $1000, Victor's is 5000, and Paula's is 20,000. The algorithm begins by reading in the expenseReportAmount from the command line. That amount is fed into the constructor of an ExpenseReport, which will then be passed to every manager to see if they're able to approve it. If the first manager is able to approve the ExpenseReport, we're done. The request was approved or denied. But if they weren't, we'll iterate on to the next manager in the list. Let's take a look at this in action to see what I mean. So here we're prompted to enter an Expense report amount. Now you may recall that the values between 0 and $20,000 are all handled. So, for example, if I entered $5000, the request was Approved. Now if I entered a much larger number, nobody's able to approve the expense. So we can see here that we are properly handling whether or not the expense report has been approved. So why is that not good enough? We have an algorithm that iterates over each manager. It sends the ExpenseReport through. We get a response back. Ultimately, we know whether or not it's been Approved or Denied. Why does the Chain of Responsibility help us? Well, one of the issues we have is that the caller is responsible for iterating over the list. This means the business logic of how expense reports are promoted through the management chain is captured at the wrong level. If I bring an expense report to my manager, and I ask for approval, if he says that's beyond my expense limit, he doesn't tell me to go on and ask his manager, he'll do that for me. I simply send an expense report, and at some point in the future, I get a response. I don't need to worry about the promotion process that happened behind the scenes. Our code should reflect that. And with the Chain of Responsibility, we'll be able to. Demo: Expense Report w/CoR Now let's take a look at the Budget Approval application, using the Chain of Responsibility. It should be clear just at first glance that this is a significantly smaller amount of code than what we had in the non-Chain of Responsibility solution. The most obvious difference to begin with is the addition of the ExpenseHandler class. This ExpenseHandler represents a single link in the Chain of Responsibility. Let's go ahead and take a look at that class to understand how it works. The ExpenseHandler implements the IExpenseHandler interface. This interface exposes two methods, the Approve method, which should look familiar, and the RegisterNext method. The RegisterNext method registers the next link in the chain. Basically, what its saying is if I can't approve this expense, I should ask the next link in the chain if it's able to approve the expense. Let's take a look at how that works. In the ExpenseHandler class, the concrete implementation of the IExpenseHandler interface, we take an ExpenseApprover in the constructor. This Approver is an employee, just like in the previous example. The Approve method receives an ExpenseReport. We ask the Approver, are you able to approve this expense, just like in the previous example. In this case, if they are not able to Approve the expense, because it's beyond their approval limit, we go to the next link in the chain, and we ask it to Approve it. Now that we understand how the Approve method works, let's go take a look at the application logic again. So we start by instantiating our four ExpenseHandlers, William, Mary, Victor, and Paula. As before, they have respective 0, 1000, 5000, and 20,000 dollar expense limits. Now, instead of creating an explicit list, what we'll do is we'll register the links of the chain. William will Register Mary as his successor. Mary will Register Victor as her successor, and Victor will Register Paula. As before, we'll read the expenseReportAmount off the Console input. We'll create an ExpenseReport, and then we'll go to the head of the chain, William, and we'll ask, can you approve this expense? The response we get back from William will abstract away the promotion of the request through the management chain. We now have a very simple request, am I approved, or am I not? We print out the response and we're done. This is a much cleaner interface. Let's go ahead and take a look at how it works. As before, we're prompted to enter an expense report amount. We have a 0 to $20,000 limit to work in, so let's enter something small. This request has been Approved. Now, before we go on, there's a bug in the code, and I'm not sure if you've seen it, so let's go back and take a look. It's right in here, and the issue is what happens if we request a value greater than 20,000? In the Approve method, if the ExpenseReport is for a value that's beyond the approvalLimit of the last member of the chain, the next field will be null, which will cause the dereferencing of next to throw a null reference exception. Let's take a look at that in practice. Let's enter a much larger amount. And here we can see the null reference has happened. So let's go ahead and Cancel this out, Stop Debugging, and see how we can fix the problem. Well there's a couple ways we can approach this. We could add a null reference test, and simply return Denied within the Approve method. But what I would rather do is use a null object pattern to solve this in a way that's slightly more elegant because it gives us a little more freedom in how we want to handle the end of the chain. Every time we create an ExpenseHandler, until we've called RegisterNext, next will be null. So instead of letting it be null, let's give it a default value of a null object. What I've done is I've created an EndOfChainExpenseHandler class, and this class exposes a singleton Instance. This Instance is the EndOfChainHandler. Let's go ahead and take a look at the EndOfChainExpenseHandler implementation and see what it does. The class implements the IExpenseHandler interface. It has the static instance that we refer to in the previous method, and its Approve method returns Denied, always and only. And this is important. We're at the end of the chain. If we've made it to this point, nobody has approved the expense, and we shouldn't approve it here. So now that we've made this change, we have the next defaulting to the EndOfChainHandler. Let's see if our bug has been fixed. So now we enter a much larger amount, and we can see the request has been Denied. So now you can see how the Chain of Responsibility Pattern has simplified the Budget Approval process. It's allowed us to create a more extensible Approval process, and it's one that we can not only introduce new members in the management chain to, but we could introduce new custom behaviors far more easily than using a straight iterative list. Demo: Non-Traditional Usage I'd like to take a look at how the Chain of Responsibility can be used in a slightly less conventional context. What we'll do here is we'll use the Chain of Responsibility Design Pattern to help rank Poker Hands. So, let's take a look at how this might work. We have a Poker Hand. We want to categorize it based on a series of rules. For example, we don't want Four of a Kind to appear as Two Pair, and we don't want a Royal Flush to appear to be a Straight Flush, or just a Flush. The ranking of the Hand is order specific, with the highest value ranks being evaluated first. So the way this might work is that we would pass the Hand in to the handler for the Royal Flush. The Royal Flush would look at the Hand, and determine whether or not that Hand represents a Royal Flush. If it doesn't, it would hand it off to the next highest ranking Hand, the Straight Flush. The Straight Flush handler would now determine whether or not the Hand of Cards is a Straight Flush. If it's not, it would hand it off to the Four of a Kind handler. If it's not a Four of a Kind, it would be continued to hand off until it gets all the way to the end. And the end is simply High Card. Let's take a look at how this might be done in code. So here we have the Chain of Responsibility Design Pattern being used to categorize Hand rankings. So let's start by looking at some of the classes that make up a Poker Hand. We have a Card. Cards have Suits and Values. For example, the Four of Spades. Now, we provide some utility methods to print out the Values and the Suits in a little friendly manner. That way we can use the Console output to see what the Card looked like. Cards group together to form Hands. In addition to the Cards, a Hand has a Rank. For this sample, dealing is just adding a Card to the Hand. Now we've limited the Hand to five cards, and once the Hand has five cards, we determine the Rank. We do that using the HandCategorizerChain class, which implements the Chain of Responsibility Design Pattern to categorize the Hand. The Hand also has some additional utility methods. For example, it returns the High Card, and IEnumerable of the Cards in the Hand, the Rank, and a simple ToString method. Now everything that follows is actually what the non-Chain of Responsibility Solution looks like. As you can see, it's quite a bit of code. Certainly there would be other ways to implement this, but this was a very straightforward approach that was fairly minimal for what we were doing. And now let's go to the Program. So what the Program will do is it'll deal out 10 Hands from a Deck of Cards. Remember a Deck of Cards has 52 cards, so we'll able to get 10 Hands of 5 from it. So what we do is we take the Deck, and we Shuffle it. So we new up the Hands, and we iterate over the Deck. We'll Deal five cards into each hand. Once all the Hands are dealt, we'll print out what the Hands Rank, and the Card Values actually are. Let's take a look at the output just to make it look clearer what I mean. As you can see, we dealt out five Decks. It looks like we have four HighCards, and a group of Pairs. Not terrible, not great, but you can see that we've correctly identified that a Pair of 5's, a Pair of Ace's, that they all come together to form the relative groups. Now I have Run this just to see, and it takes several 100,000 rounds before you finally get a Royal Straight Flush, which I believe to be more frequently than they occur in the wild. So now let's move on to the Chain of Responsibility, and see how that works. Now you may recall, when we looked at the Hand, that there is the HandCategorizerChain.GetRank. So let's take a look at that. Alright, now this is fairly simple, and this should look familiar from what we've seen before. We start by creating the first item in the chain, the RoyalFlushCategorizer, and that's the Handler for this link of the chain. The RoyalFlush Registers the StraightFlush, which Registers the FourOfAKind, the FullHouse, all the way down to HighCard. So you can see what we're doing in the constructor here is creating a Chain of Responsibility for all of the Rank Categorizers. So the GetRank method, simply looks at the Hand, gets its static instance, looks at the Head of the list, and the Head you can see is the RoyalFlushCategorizer, but it's important to note that our GetRank method is not aware of that. It just knows there's a Head. And then it calls Categorize. So let's take a look at how Categorize works. Categorize is an abstract method. Now from that you can infer we're going to have an override for every single type. We're going to have one for RoyalFlush, StraightFlush, all the way down to HighCard. Now, you can see there's some utility methods here as well, HasNofKind, HasStraight, HasFlush. These are in the abstract HandCategorizer class because they're reusable, and they're useful in multiple categorizing contexts. So let's go take a look at the Categorizers themselves. So here we have the individual HandCategorizer classes. Each class searches for a single type of Hand Ranking, from HighCard, all the way to RoyalFlush. So let's start by looking at HighCardCategorizer. So every Hand ultimately has a High Card. So in that respect, this is the EndOfChainHandler. There is nothing beyond this. So if we've made it to HighCardCategorizer, it's HighCard. Pair is very simple as well. It's simply going to ask, do we have Two of a Kind? Now you might wonder, well wouldn't Three of a Kind satisfy Two of a Kind, or Four of a Kind, or Full House? Well they would, but all of those came before PairCategorizer. By the time we've made it to PairCategorizer in the chain, we've determined none of those cases exist. So, if we have a Pair, we're done. This type of logic continues all the way down to RoyalFlushCategorizer. The RoyalFlushCategorizer is equally simple. Do we have a Flush? Do we have a Straight? And is our High Card an Ace? If we have a Flush, and we have a Straight, and the High Card is an Ace, we have a RoyalFlush. So as you can see, we've taken some logic that would seem very complex, and we've decomposed it into very small parts. The RoyalFlushCategorizer only has to worry itself with a RoyalFlush, and a StraightFlush will look very similar to a RoyalFlush, only without the check for an Ace. We don't need the check for the Ace because we've already made it through the RoyalFlushCategorizer and determined we don't have a RoyalFlush. So if we come back to the Hand class, some of the complexity here might make a little more sense. So you see here, we have all the available Ranks, from HighCard to RoyalFlush, and what we do is we start removing them from the list of possible Ranks. If we don't have a Flush, it couldn't be one of these. If we don't have a Straight, it couldn't be a Straight. If we don't have a Triplet, it couldn't be a ThreeOfAKind or a FullHouse. If we don't have a Pair, it couldn't be a Pair, or a TwoPair. What we're left with is a list of availableRanks the Hand could satisfy. And from there we simply go and ask. Is it a HighCard? Is it a Pair? But we ask in the appropriate order so that we always ask for RoyalFlush before HighCard. So this isn't a lot of code, but its convoluted code. We've mixed the logic for searching for a RoyalFlush with the logic for searching for a HighCard. This would be hard to extend to add additional Hands. For example, if we switched from Five Card Poker to a Seven Card Stud, the Chain of Responsibility would allow us to add additional logic at each step, and isolate those changes depending on the type of Hand Rank we were looking for. So HighCard wouldn't have to change at all. RoyalFlush would simply have to look for a Royal Flush within the seven cards. It would isolate the logic, and allow us to have a much cleaner interface. Now if we come back to the Program, we can again see we deal out the Hand. We get the Deck. We Shuffle. We deal all the Cards, and we print all the Ranks. Nowhere in here did we need to worry about how the Ranks were generated. It creates a very simple calling structure. I hope what I've shown here is that we're able to use the Chain of Responsibility in a somewhat nonconventional manner to solve what is an otherwise somewhat complex problem. We're categorizing the set of data into one of many buckets, and we're able to do it by implementing minimal logic for each bucket, and allowing it to be handed down the chain. This is a very straightforward way to do this, and I think that you'll find it's kind of a fun solution for a lot of these types of problems. Summary So in summary, you should use the Chain of Responsibility when you have more than one message handler for a message, if the appropriate message handler is not known explicitly by the sender, or if the set of handlers can be dynamically defined. In the previous examples, statically defined handler lists were used, but dynamically defined lists are quite common. The benefits you'll see when using the Chain of Responsibility include a reduced coupling between the message sender and receiver. You'll be able to dynamically manage the message handlers, and the end of chain behavior can be defined appropriately depending on your business context. Some related patterns to look at include the Composite Pattern, where the parent object might be used as the next successor in the chain, or the Tree of Responsibility. The Tree of Responsibility is similar to a Chain of Responsibility; however, each node may have multiple successors. When using a Tree of Responsibility, you can use the multiple successors asynchronously, or synchronously, creating a very dynamic structure. So thanks for joining us as we learned about the Chain of Responsibility. I encourage you to look at more of the Design Pattern videos available at Pluralsight. The Command Pattern Introduction Hi. My name is Keith Brown. I'm a cofounder of and I'm here to tell you a little bit about one of my friends, the Command Pattern. This very simple little pattern can be used in everything from websites implementing complicated features like Undo, to implementing very simple features, like command-line Parsing in a Console application. Motivating Example In order to explain the Command Pattern, I'm going to take the simplest possible example that I can so we can focus on the abstraction of the pattern itself. We're going to take a command-line order management system, where orders can be created, and edited, and shipped, and a log of everything that happens to an order has to be kept. And I'm going to focus on one of these commands that need to be handled, the Editing command. Now just to give you a little bit of context, I have a Program here. This is my Main app. There's static void Main here, and it's just going to go off and Run my first Program. I have a second Program that looks a little bit different that uses the Command Pattern strategy that we'll look at later. But let's go ahead for now and take a look at the Run method. In the Run method, we basically take a look at the arguments that are coming in. This is a command-line application after all. And if we're not passed in any arguments on a command-line, we go ahead and print out usage information so people can figure out how to use our app. Assuming arguments are passed, we create a little helper called CommandExecutor, and we call ExecuteCommand. Now, this is not the Command Pattern. This is just a little helper class that's going to go off and do this work, and get us out of our Main Program. Now the first smell that I see here when I walk into this command is a big switch statement, and any time we see a switch statement, we should be thinking to ourselves, hmm, maybe there's a better way to do this. But we'll come back to that and deal with that later. Basically what we do is we look at the first argument, which tells us which command is to be executed. We can Update the Quantity of an order. We can Create an Order, and Ship an Order. The only one that I've really implemented is UpdateQuantity, and if we scroll down a little bit you'll see that after we Parse the new Quantity of items in the order, we're going to update that. Now I don't actually have any code here that updates a database and logs, but I do simulate it, so I write out to the Console, this is where I would Update the DATABASE, and this is where I would LOG, so that you can see that those things are happening. I don't care about the details of how you do that stuff. But these represent two different dependencies, a dependency possibly on a repository of orders, a dependency on a log system as well. And one other thing you'll notice that I'm also keeping very simple is that I only have one order in the system. That keeps me from having to pass around identifiers, and things like that. I really want to keep this simple, to just focus on the abstraction of the command. Now if we were to Run this, if we just Run it without any command arguments, it'll print its usage, and if we Run it, UpdateQuantity, and we give it a number, like 42, we'll see that we're updating the order quantity from 5 to 42; 5 is the simulated old quantity that would be coming from our database, if we actually had a database, we'd look up the existing value, and then we log that, and we log, you can imagine logging to a persistent LOG that would keep track of the change, and it says, hey, you went from 5 to 42, and that's a very useful piece of information to have. So, one of the requirements of this system is that whenever a change is made to an order, we want to see details of what change was made, and you know, if I was really building this for real, I'd also want to know who made the change. Now what I'm interested in doing in this example is simplifying this CommandExecutor. It's just, it's basically doing all the work here inside of the one class, and you can imagine creating orders, and shipping orders, and doing all of the other sorts of commands that might be required by this app, there might be an awful lot of dependencies here, and this is going to become a class that's going to be doing an awful lot. It's going to have way too many responsibilities. So, we're going to figure out a way to use the Command Pattern to break this thing up into separate commands that do their own thing, and then we can just, really, we can actually get rid of this class, period. Intent and Applicability The intent of this pattern is really simple. We want to represent a piece of business logic, or just a piece of logic in general, some action as an object that implements an interface. And let me show you an example of what that interface could look like. This is the simplest form. In its purest form, we have an interface that has a method on it, that doesn't take any arguments, and returns nothing. It's basically just a way for a client to be given something to execute at a later time when it makes sense. So this completely decouples the client that's going to call Execute from any of the details of how that command will get executed. The client doesn't have to care about any dependencies. All of that stuff will be set up beforehand, and then we can just kind of wire our system together with commands. One of the things that this also enables is delayed execution. I can queue commands up, and execute them later on in a certain order if I like. I could also persist commands. If I decide to go further, and make my command object support persistence in some way, then I might be able to actually put that thing on disk, and bring it back up, and execute it later on without caring exactly what it's going to do. I just know that I need to have those instructions run. And this could be incredibly valuable implementing complicated features like Undo in a WebForm scenario. Now you may have heard this Command Pattern referred to as an Action Pattern, or Transactions. Those are also very common names for these things. Now we'll talk about this a little bit more as we go through some code, but a number of things you can do with a Command Pattern is enforce logging. If your command encapsulates the details of executing some action, and then logging the fact that it was executed. If clients are always using commands to execute actions, then you'll know that your logging's always going to happen. That's one thing we actually use on our website at, when critical things are happening that need to be logged. Validation is another thing that's useful with a Command Pattern, as we'll talk about a little bit later. An Undo functionality in a website, this is another great example of where, in a website, or in any application really, where a command object can be used. If you think about it, if a command has all of the information that it needs to perform some action, it can record everything that it needs to know while it's performing that action in order to be able to reverse that action. So, you can imagine having not only an Execute method on your command interface, but you could also have an Undo if you like. Structure and Consequences So here's a pictorial view of the Command Pattern. There's a client out there somewhere who has a reference to a command object that implements a method called Execute, or Do, or Run Transaction, it doesn't matter what it's called. It's a method that doesn't take any arguments. The client doesn't need to provide any context. It just executes that command. The command object itself may hold reference to several dependencies in order to get its work done, and that's fine, as long as the client is shielded from those dependencies. We could also take this one step further. If, for instance, you wanted to implement validation, one very interesting thing you could do is add a Validate method to your command. So, now you have Validate and Execute, let's say. And what could happen is that the client might accept commands from a command-line Console, or the GUI, or something like that, and Batch them up for later execution. Perhaps it's a Batch job that's going to run at night. But we might want to do validation on those commands early to make sure that all of the context for those commands is correct, the input we provided for each of those commands is good. And so we can run the Validate method on each of those commands to make sure that they're good, before we actually Execute them. And then, of course, we can also perhaps Undo a command. If you put Undo on your command interface, then that means that all of your commands need to be able to be undone, or if you call Undo, they should do nothing, but very likely, if you put an Undo method on your command interface, you're saying to the world, all of my commands can be undone. There are other ways of implementing Undo with command objects that don't require you to put Undo on your command. For example, you might have a command Execute and return a compensating command that can act as the Undo. And if a command's not undoable, you can return null. There's lots of different ways of playing with this. The key thing to think about with a Command Pattern is that you have a method that somebody can call without having to have any extra data to call it with. Now because the client doesn't pass any arguments into this command, this makes it a little different than something like strategy. With strategy, you have a very specific thing that you're doing, and you're passing in some arguments that give the strategy some context, and it's just done in a different way depending on the strategy that's chosen. The Command Pattern is more general than that. It's not doing any one particular thing. A command could represent anything. It could represent screwing in a light bulb, or painting a car, or who knows, whatever it could represent, but the client doesn't care about those details, doesn't have to pass any arguments in. But a consequence of that is that the command has to be constructed with everything it needs in order to get its job done before the client can Execute it. When the client Executes it that object needs to have all the context that, it's not going to get any context from the client. It needs to be able to have its own context when it's built. This often argues for having factories to build these things, and you'll see an example of that when I show you some code in a minute. It's easy to add new commands to the system. This is an example of the open/closed principle. If we have a system that's based on commands, then instead of going and modifying say, say this CommandExecutor class. In our CommandExecutor, for example, when we want to add a new command, we have to come in and modify this class. So this class is not closed to modification, which is what the open/closed principle tells us is a good idea. It's a better idea to make sure that this class is not, we don't have to update this thing every time we have a new command that we want to run. We'd like to just extend the system by creating a new command object, and that's when you use the Command Pattern, that's the place that you get to. So with the Command Pattern, it's pretty easy to satisfy the open/closed principle by simply adding new commands when you need new functionality. Implementation Example Okay, so now that we talked a little bit about what the pattern is, we're going to go and take a look at some code that implements the same order management system, the command-line application, but using the Command Pattern instead of using the big old CommandExecutor class. So, looking back at our Program now, I'm using Program2, instead of Program1, and that Program runs a little bit differently. It uses the Command Pattern. If we go ahead and jump in there, you'll see that there is a command that comes back from ParseCommand, and I'll take a look at how this is parsed in a minute, but this command object implements ICommand. So if we go and take a look at that, you'll see the interface ICommand, which is what that thing returns, it just has one method on it, Execute. And so if we back to our little Program here, when we get one of these back from our CommandParser, which is a new class that we've added, kind of helps us implement the whole factory notion, and I'll come back and talk about how that's built in a second, all we have to do is just Execute the command. We don't have to know the details of it. And every one of those commands is going to be a separate class, and so if we want to add a new command to the system, it really just involves adding a new class to the system, instead of having to go and modify our big old CommandExecutor class that we used to have. So let's go and take a look at the command that we implemented here, our UpdateQuantity command. Now I've kind of hidden some of the extra goo around this thing, just to show you the command interface. This command, it has a little bit of context that needs to be set up, like what's the quantity of the new quantity that you want to update. So one of the commands here is to Update the Quantity of the Order, and so we create one of these commands when that happens, specify the NewQuantity that we want, and ask it to Execute. And this code should look real familiar. This is the code that we had before. The only difference is that instead of being in the executor object, along with all of the other things that could happen, it's in this little class that just knows how to do this one thing, it has a single responsibility. Now the question comes up as to how do we actually create those commands? When a user passes us an argument that says, UpdateQuantity, how do we get the right command, and give it all of its context so that we can just Execute it here, because really, this is the easy part. The more interesting part is how that thing gets created, and that's where factories come in. Now, if you recall, I'll go back to my old Program here, Program number one, where I basically just created this big object and asked it to handle every single command. And then when I needed to Print the Usage of these commands, I had to basically come here and just know what they all were, and write them all out. You'll notice that that's very different now in my new world. I have something called an ICommandFactory, and that factory, if we take a look at it, its job is to know something about the command that it creates. It knows the Name of the Command, a user readable Description of the Command, and it has a way to actually create an instance of a command by parsing command-line arguments. So you'll notice here that I just have one place where I centralize all of these factories. I have one for CreateOrder, one for UpdateQuantity, one for ShipOrder. I basically just have a collection of these things that I can hand back, and I can use that to implement PrintUsage. Now I don't have to have that knowledge spread all over the place, I can just have it in one place. So here inside of PrintUsage, I just walk through all of the available commands, and print out their Descriptions, instead of having to hardcode what they are here, because it's very easy to forget. If you add a new command to the system, you have to remember to go and update PrintUsage in our old world. Here you don't have to do that. You just have to add it here. And if you don't add it here, you'll notice upstairs that our CommandParser takes those availableCommands, and uses those to discover which command we want. Notice here when we call ParseCommand. This little parser is going to go through and look at the command name that was requested, and he's going to go look through the availableCommands to find a matching CommandName in there, so, if you forget to add your command to that list, not only will it not show up in the usage printout, but it also won't be able to be executed, and that's a really good thing. Now I had a choice when I came to this design. I could've either created, I could have created separate factory objects for my commands. I could have implemented it that way, where I have factory objects, and I have the commands themselves, and, you know, for simplicity in this little command-line app, I really just wanted to keep it all in one object. When you add a new command, I wanted you to be able to describe that command, and know how to parse it, knows how to parse the command-line, arguments that it takes, and have it Execute command, I just wanted that all to be in one place, simply so that when I go to add a new command to the system, I only have to add one class. And so if we go back to our UpdateOrderCommand, you'll see I've brought in some, I cleaned up some white space that I hid some stuff from you before. We have the command Execute that we had before, and the NewQuantity. But we also implement ICommandFactory right on the command, and this is just a convenience for me. You might find this convenient to do yourself. You could have this on a separate object if you like. But what I do is I just go ahead and allow the program to just create all the commands that it needs, and they can act as factories to create new commands as well. And to also be listed and described. So when you want to create a new command in this system, you just have to add one class that does all of these things. So, here's the factory method down here, MakeCommand, and it's passed the argument list that was passed to the program, and its job is to return an ICommand instance, and so all this guy does is he goes and Parses the arguments that this command accepts, and returns a new instance of itself really. So, we have this functionality kind of, both of these bits of functionality are here in this one class, which is convenient. Now in a more complicated system, you might want to factor that out, and have a separate factory object, and that would be okay too. So, let's try actually running this on the command-line. If we go back and just say .\LoggingDemo, you'll see that we're looping through all of our commands that were created, our command factories technically, and printing out their Descriptions. So to go back to my Program here, and I take a look at GetAvailableCommands, really all I need to do, if I add a new class, a new command class to this system, because I've kept it so simple, and the factory is right on the command, I would just need to add like just a new instance of whatever command, the DeleteOrderCommand, or whatever. I would just add it there, and it would become part of my system just immediately. So I wouldn't need to modify any of my other code in order to get a new command into the system. Now let's jump up and take a look at this run. It should run exactly like it did before, if we go ahead and run our LoggingDemo. The order of the commands that are listed are a little different here because I have them ordered differently, but basically the functionality is the same. And if I go ahead and Run UpdateQuantity with a number, 42, let's say, then it finds the command. It actually creates an instance of the command given the arguments that were passed, and it Executes the command. So I have an application that's functionally equivalent, but it's much, much easier to extend. Now, it turns out there's a bug lurking in this application. If I Run this application, I give it a command that doesn't exist, I'm going to get an Exception. Now to find out the source of this Exception, we'll go back into the code, and we'll notice that, look, when we call ParseCommand, if it doesn't find what it wants from us, it's supposed to return null. So clearly, that can't be the problem. But if we go and look at the Parser itself, you'll see that the way this is working is it's looking for a matching command, command factory actually, and if it doesn't find it, it's going to end up returning null, FirstOrDefault will return null if it doesn't find a matching command here. And now we're going to go ahead and call MakeCommand on a factory that doesn't exist in that case. So this is right where our null Exception is happening. Now there's a couple of ways that we can approach this problem. The obvious approach would be to say if, if we have a null command, we return null. We just go ahead and pass null all through our system, but nulls can be really scary. The client that gets a null might not be expecting it, and we might end up with the same sort of bug that we have here. So to solve this null problem once and for all, what I'd like to do is, I'd like to make it so my client, my Program here, doesn't have to worry about ever getting null back from this command. I just want to be able to say, command.Execute, and always have something to Execute. And, in this case, I could do that pretty cleanly by creating what's called a null object. This is a little mini-pattern, if you will, where instead of returning null, if I don't find the command, I will return a new instance of NotFoundCommand, which is something that I've created. It's a very, very simple command, that when it's executed simply prints out, hey, I couldn't find the command you were asking for. A lot of times, you can find cases where instead of returning null, you can return a special object that allows the client to work properly, but gives the expected results. So, with that in place, let's go ahead and Build this and go and try it out. So if we go and Run this again, you'll see that we couldn't find the command, and, oop, I needed to pass in the name of the command. Let's go ahead and do that, Name = requestedCommandName. Let's Build that. Try it again. There we go. Okay, so the idea here is that instead of returning null, oftentimes we can return a special object that implements the interface, but it implements it in a safe way, and your clients do have to expect that. They have to expect that they're going to get something other than null back, and be able to discover that if they need to. Related Patterns Patterns are oftentimes related. In fact, the Command Pattern lends itself very well to being used with factories, and you saw an example of that in my code where I had the command object, the implementation actually implement a factory interface because it was convenient. We also use the null object mini-pattern, if you will, where instead of returning null, we returned an object that implemented the interface that was required, but just did it in a safe way. We also can use what's called a composite command, and this is an example of the Composite Pattern. If you were to imagine a command that could be given several child commands, such that when that command executed it ran Execute on all of its children, then you'd have a usage of the Composite Pattern, which is also oftentimes used with the Command Pattern. Summary Alright, so we've seen the Command Pattern. It's very useful for decoupling client code that needs to execute some command, or some action, or some business logic from the details of that logic, and it's a very strong separation, because you can't even pass any arguments. That command has to be setup and already to go so that all we have to do is have the client call one method that doesn't take any arguments, and it might be called Execute, it might be called Run Transaction, or Do, or whatever. It could be called a lot of different things. In fact, it could be called Undo depending on what you're trying to do. But this whole idea of calling a method on an object that has some context and some state, and it knows how to do some action, is a very powerful thing. So, we saw how to do that with a command-line application, making a very extensible command-line application, where if we want to add another command, we just have to add another class. We don't have to go and modify anything in our system. We can use this to implement Validation, and pre-Validate some command that we'll run later, and we can also use this to implement Undo. There's no reason you can't have an Undo on your command that allows you to Undo that command. Alright, well thanks for spending some time with me learning about the Command Pattern. I hope you find it useful in your own applications. Composite Pattern Introduction Hi. This is John Sonmez from Pluralsight, and in this module we're going to be talking about the Composite Pattern. The Composite Design Pattern is actually a pretty simple pattern to understand. It's not really that difficult like some of the other design patterns. But the trick with the Composite Pattern is knowing when to use it, and knowing how to properly use it to make it so that your code to iterate through collections, and to handle trees is reduced. In this module, we're going to go ahead, and we're going to look at the Composite Pattern, generally what it is, and breakdown the definition of the Composite Pattern. Then, we'll go ahead and see some examples of the Composite Pattern, first one in real life, and then we'll look at one in the code, and we'll see how we can refactor our code to use the Composite Pattern, and really simplify that code. Than finally, we'll take a look at the UML diagram of what we've created, and we'll discuss some ways that you can recognize the need for using the Composite Pattern in your day-to-day code. Breaking it Down So the definition of the Composite Pattern from the classic Design Patterns book is to compose objects into tree structures to represent part-whole hierarchies. Composite let's clients treat individual objects and compositions of objects uniformly. So this definition's not as hard as some of the other design patterns. But let's go ahead and break this down so we can get a good understanding of what this exactly means. And it's really not that complicated. So, if we want to compose objects into tree structures, we know how to do that. That makes sense. So, we would be taking some objects that we have, and building a tree out of it. Now to represent part-whole hierarchies, this might be a little bit confusing. Part-whole is basically just a mathematical term that refers to things that are composed of parts that make up that whole. So, really, when we're talking about breaking objects into a tree structure that represents a part-whole hierarchy, we're just saying we're creating a tree where some of those leaves in the tree might come together to make up a whole, a thing that exists on its own, but needs those parts. Then, composite lets clients treat individual objects and compositions of objects uniformly. So basically, all this means is that we should be trying to derive the solution that's going to let us take the leaf of a tree, or the very bottom of the tree that doesn't have any children, and a branch on the tree, or something on the tree that is going to have leaves, or have children, and we should be able to treat those the same way, so we don't care if it's a leaf, or if it's a composite in this case, something that has leaves, or has children. And that's really all the Composite Pattern is trying to do, is just to say, we need some way to represent something in a tree, and to treat leaves and branches as the same, so we don't have to make a distinction between the two. Email Example So let's look at a basic real world example of using the Composite Pattern. This is an example that we probably use every day, which is sending email. So first let's look at the example of sending email without the notion of groups. Now, groups is something that we probably use pretty often in order to send emails to multiple people, but to treat them as one. But if we don't have that capability, this would be without the Composite Pattern, then you can see here I've got a list of emails I'm sending to Dick, Jane, Tom, Bill, Mary, and you could have a lot more than this, but in this case we've got five examples here. And Dick, Jane, Tom, and Bill all happen to be developers, so I went ahead and I looked up what each one of their email addresses was, and I typed it into my To box and then I typed in Mary, who's our designer, and I sent off an email to all of them. But I had to do a lot of typing to get that in there, and if I had a really long list, and different groups of people, I might have to look up for each group, remember who all the members are, what if I forgot one, and so on and so forth, until I had composed my To block of my email to have all the email addresses I needed. Well this isn't very efficient. This is not typically how we do things. If you're doing things like this, you probably need to apply the Composite Pattern to your life. So let's take a look at this example using the Composite Pattern. So here's what that same exact email might look like if I were using the Composite Pattern. And this Composite Pattern is applied to email grouping functionality. We use this in pretty much any email client that you might be using if you're using Gmail, or Hotmail, or Exchange; you have the ability to send to a group. So, in this case, we'll send to the Developers group. So we'll get all the developers in there, and then we'll send the email to Mary. So, we can make our To in our emails go to a group, and we can make it go to an individual, but we're treating them as the same. It doesn't matter that we're sending to a group. In our mind, we're sending to this group, but for the purpose of using the email message, the To box in the email, it doesn't matter if it's a group, or if it's an individual person. We'll just hit Send, and then we'll rely on the email software doing the logic to actually send this out to each individual on that list. So this is a good example of a Composite Pattern that you're using every day in real life, and that's really how simple the Composite Pattern is. Split Gold Let's take a look at some example code that's not using the Composite Pattern, and then we'll refactor this code to use the Composite Pattern, and we'll see the value of using this pattern. So, I've created a small program here, and the purpose of this program is to basically divide up gold in a game, perhaps, for a kill. So we have a group of adventurers. This group kills some monster, and they gain some gold. We need to split that gold up. This is a common thing in games to be able to split something among people, or among characters. So you can see here that in this Main, I've got some manual process for doing the splitting. So, I've hardcoded a few things here, like the gold for the kill, and the message, just because I don't want to try to write a whole game engine here. We're just going to pick up from the part of splitting up the gold. So, you can see we're going to take 1023, that's the number of gold pieces to split, and we've got some people here. We've got Joe, Jake, Emily, Sophia, Brian, and then we created a group of Developers that has the members of Joe, Jake, and Emily. And then we have another list of persons that has the members of Sophia and Brian, those are the ones that aren't grouped together. So then I've created a variable to hold the groups, which we only have one group, which is Developers, and so we've got this individuals and groups. So this is where we need to split the gold. So, in order to calculate the total to split by, we've gone through, we've gotten all of the individuals. We've gotten all of the groups, and we're going to split it amongst them. So, if you're in a group, in this case, you're only going to get your group's share. So, for example, if we had three gold pieces, and there were two individuals and one group, then each individual that wasn't in a group would get one piece, and then that the group would have to split the remaining one piece of gold by however many members were in that group. So you could imagine that you could have a tree structure like that. In this case we only have one level. So, we're calculating the amount. We're calculating whatever the leftOver is, because there could be a leftOver. And then we're simply going through each individual, and we're going to give them their fair share, and give the first guy the leftOver, so that someone will get that leftOver. Then we're going to print out the Stats for each individual. Then we're going to do the same thing with the group. For each group, we're going to go through, we're going to look at each member, and we're going to divide up the group's share, and then print out that member Stats. So I'll go ahead and Run this. And you can see here that the gold is split up. We've got 1023 gold total, and you can see that Sophia and Brian both got 341 gold pieces, but then the group of developers had to split their 341, and we had to give the remainder to someone, so Joe got it, and he got 115, and Jake and Emily each got 113. So, our code works to split this up, but it's a little bit messy. If we look at this code, we had to go in here, and we had to do some calculations for each group, and for each member, and then, if we had some nesting, if we had multiple layers of groups, like a group within a group, we would've had to further complicate this logic. Now let's take a quick look at some of these other classes. We had this Group class, which didn't have very much logic in it at all, it just holds Members, and has a Name. And then we had this Person class, which just holds a Name, Gold, and it has a method to write out the Stats. Refactoring 1 Now that we've seen the hard way to split this gold, let's go ahead and refactor this code into the Composite Pattern, and we'll see how much easier this should make things. So the first thing that we need for a Composite Pattern is an interface that both the Person, and the Group are going to implement. And so we basically need to be able to treat a Group like a Person, and if you remember here, the Person has the Stats interfaced, it will write out Stats. It has a way to get some Gold, and it has a Name. We already have a Name on Group here. And sometimes it's a little bit easier to work a little bit backwards from what we want to be able to determine what our interface should look like. I like to design interfaces that way, because then you're actually using it before you design it. So let's go ahead and take a look at how we might rewrite some of this code here. Instead of having to have individuals and groups, what we would really like to do is to just have a collection of parties. In this case, we'll call them parties, which would be, an individual could be a party, or a group could be a party. It could be one, or more, or it could be a party that is composed of some nested level of groups and individuals. So, let's go ahead and change this code a little bit. We'll say, party is equal to a new ListOfParty. We'll call this one parties. And in this ListOfParty, we're going to want to have everyone. So, let's have our developers, and we need Sophia and Brian. Now, we don't have this class yet, but this is what we'd like it to look like. We'd like it to be able to take this type of Group, and Person, so they both will need to implement a common interface. So let's go ahead and comment out this code here. So now we know that what we'd really like to do here is to be able to just split it amongst a party instead of having to calculate for individuals, and calculate for group. So we're going to ignore this code for now. What we're going to do instead is we're going to still calculate the total to split by, but in this case, our total to split by isn't going to be individuals count plus the groups count, it's going to be the parties count. So let's go ahead and change that code. We'll do parties.Count. So the amount for each is still going to be the same. The leftover's still going to be the same. And now we're not going to loop through individuals. Instead, what we're going to do is we're going to loop through each party member. So, we'll say, partyMember in parties, and then what we want to do in this case, is we want to do partyMember.Gold, and we're going to add to that Gold the amountForEach, and the first one gets the leftOver, then we'll go ahead and blank out the leftOver, just like we did before, and we'll be sure to do partyMember.Stats to print the Stats for that member. So now we'll go ahead and comment out all of this code as well. (Typing) And this is what we would like to simplify our code to. Pretty simple here. In fact, let's go ahead and get rid of everything commented out, just so we can see how simple this should really look when we're done. (Typing) Refactoring 2 So now we'll go backwards, and we'll go ahead and define this Composite interface. So, let's go ahead and create a class called Party, and we'll actually change this to be an interface, and we'll move this to someone's file. So we've got our Party interface, and the first thing that we find is that we need all of these guys to be able to implement that interface. So, let's go ahead and make that so. We'll go ahead and go into Person, and we'll make Person implement Party, and we'll make the Group implement Party. (Typing) So now we can have all of those in the same list. Then the next thing that we run into here is that Party has to have Gold. So let's create a Gold property here. And we're going to need to create some getters, and setters for this, but let's go ahead and skeleton this out first, and it'll also need to have Stats, and Stats is going to go ahead and print out the Stats for that partyMember. So now we have this code okay, but we need to go ahead and implement this on Person, and on Group. So Group is the first one we actually really need to implement these members on. We need Gold and we need Stats. So, in order to get the Gold, we'll basically just need to loop through each Member we have, and ask for their Gold, and add it up. So let's go ahead and implement that real quick. So our Get method will say totalGold = 0, and then we're going to end up returning totalGold, and then we'll go ahead and do foreach member in Members, we'll do totalGold += member.Gold. Then we just return it. For the set, we'll go ahead and do something similar. In this case, we're going to set the Gold, and in this case if we use += we're going to be getting the Gold, and then we're going to be setting it, so we're going to be re-splitting that Gold up, but that's okay for this example. So in order to set the Gold, we're going through each member, and we're going to give them an amount of Gold that is equal to the split of Gold. So here's where we'll split up our Gold. So the first thing that we'll need to do is we'll take the value that needs to be set, and that's going to be our total, and then we're going to divide that among the Members. So, we'll go ahead and say, eachSplit will be equal to the value divided by Members.Count, and then we're going to have a leftOver amount, which we'll make that equal to the value mod the Members.Count. And we'll do that same logic that we had seen before. We'll go ahead and split this, so we'll say foreach member we're going to take the Gold += eachSplit + leftOver, then we'll go ahead and blank out the leftOver so that only the first member is getting the leftOver, and we'll go ahead and Save that. And again, using this method, just so you're aware, when we're doing += here in our Program, we're actually going to re-split the Gold because we're going to be getting the Gold for the entire group from all the individuals, and we'll be redistributing that out. But that's okay in this case. We could have just created a giveGold, and not a way to get the amount, and that would have let us just split up some Gold. So now we've implemented our Gold property, and we just need to implement Stats. So Stats is pretty easy to implement. All we're going to do is we're just going to loop through each member, and we're just going to call Stats on each member. So now we have a Group composite that is going to be able to handle having a List of Members and to operate on those, and in fact, in this case, if we want to make this so that we can actually have groups within groups, we can change this to be a ListOfParty, and we'll change this to be a ListOfParty, and we just have to make sure that the interface is public here. So now, we have a composite object. Let's go ahead and make sure our Person is correct. We don't actually even have to do anything to Person, because Person already has Name, it already has Gold, it already has Stats, so there's really no problem here. So we'll go ahead and Save that. We'll look at our Program here, and we should be able to Run this now, and it should work as a Composite. So you can see here, we got the same results as we had gotten before, a little bit of a different order, but you can see that our Group here, they had split up their share of 341, and our individuals in the Party got 341 apiece. Adding Depth So let's go ahead and try to extend this model a little bit further. Let's see how we can actually create a real tree here using the Composite. Now that we have this Composite Pattern, we can very easily make this tree of any depth, and we don't have to change our logic at all. So, let's add a few more developers here. I'll go ahead and add another developer named oldBob, and then I'll add another developer named newBob. And we'll go ahead and put them in their own group, so we have Old Bob here, and we have New Bob here. And let's go ahead and create a Group for them. We'll call it the bobs, and this will be a new Group, and in here we're going to have Members equal to oldBob and newBob. Now, we want to have our Group of developers include the Bobs, so let's have Joe, Jake, Emily, and the Bobs. So now you can see that we have a tree structure here. So, at the top of our tree, we're going to have our individuals, we're going to have Sophia and Brian, they're not in a group. Then we'll have a Group, and that Group will consist of Joe, Jake, Emily, and the Bobs. Then if you go one more level down that tree, there's another Group, the Bobs are actually two guys, it's Old Bob and New Bob, so they're going to split their share. So we'll just go ahead and Run this just like this, and you'll see that we don't have to make any more changes. Now, you can see that the split has changed quite a bit. Sophia and Brian still get their 341, but the other 341 is now split four ways, with one remainder. So you've got 85, 85 and an 86, and then Old Bob and New Bob have to split 85, so one of them gets 43, and the other one gets 42. Now the beauty of using the Composite Pattern in this case is that all we had to do was just add in our Group to this tree. We could basically create this tree as many levels of depth as we want, and this logic, this algorithm is still going to work just with this simple bit of code here because of our Composite Pattern, because we can treat a group like an individual. So thinking about how this code actually works, when this Group logic happens for setting the Gold, it's going to go through each member, and since a Member can be of Party type, so it could be an individual person, or a group, the interface is the same, it's not going to matter. So if there's another Group in here, it's going to call the Set on the Gold for that Group, which is just going to split that amount, and we didn't have to think about that complex logic. A lot of times when you're dealing with trees, it can get very confusing trying to figure out, is this a leaf, or is this a node, and handling things differently. But we've contained all the differences here in this Group class, and in this Person class, and so our Main Program doesn't have to know, and it can treat any level of hierarchy exactly the same. Using a Root So there's one last thing that we can do here to reduce this code even more. We still have this ListOfParty types, and we are having to loop through it because we're using a List here. But, if we reduce this down, and we make this parties actually just be a Group, so we create a new Group, so we have one high level Group, with all these Members in it. Then we'll find that we don't even have to do any of this logic. We can just assign Gold to the Group, and it's automatically going to be split to the Member of that Group, so we can just do parties.Gold and we can just do +=, and we'll do the gold for the kill, and then we'll just simply print out the Stats. So, we'll go ahead and Run this. And now you can see we're getting the exact same result, but our code is very simple at this point. All we're doing is setting up the structure, and then assigning the Gold and calling the Stats. We're not having to do any logic here. The Composite Pattern is allowing us to automatically do all of this without much work at all. Formal Definition So let's take a look at the actual UML diagram of the Composite Pattern. So, in our code, we had gone through and we had created this basic structure, but here we're going to look at what the official diagram is for the Composite Pattern that you might see in representation of this pattern in UML. So you can see here that we have an interface that's the Component, and the Component is that interface that we're going to interact with that is going to treat a Leaf and a Composite as the same. Then we have a Leaf, which implements that Component interface, and it just has to do whatever actions that we're going to have on the Composite. They both are implementing the same interface. So we have the Composite as well that's implementing that interface. It also is going to have some way of managing its children, which could be one or more Components. Remember a Component can be a Leaf or a Composite, so you can create a tree with multiple branches that way. You can see that if the Composite can have children that are of the type Component, and a Component can be either the Leaf, or the Composite, we could keep on going down that path if we keep using Composite. So that's the basic idea here, and when you write code that's going to operate against this, you just have to remember for the Composite case to be able to handle its children, and as long as your Composite can handle its children, then it's not going to matter how many levels of nesting that there are to your Composite, it's going to do that automatically for you, and that's really the simplicity of using the Composite Pattern. When to Use The only real confusing part, in my mind, for the Composite Pattern is when to use this. And I think this is a problem worth talking about. So there are a lot of instances where you can actually use a Composite Pattern that you might not think of. And here're a few tips that you can use to identify situations where you could use the Composite Pattern. The first one is if you have some set of groups, or collections. This is a big indicator that you might be able to use the Composite Pattern. You should think to yourself, can I add some kind of interface to that group, or that collection that's going to let me treat that whole group of things as one individual thing? Then you can have mixed groups, because then you can have individuals, and you can have that whole group being treated as an individual, and there you have the Composite Pattern. So this is a big one where you might look at a list of things, and then you might think, could I restructure that so that that list of things implements some kind of interface? Another easier to detect one is when you have a tree. Any time you have a tree structure, you should be thinking, can I simplify navigating this tree, and doing work on this tree by using Composite Pattern? It can be really difficult to handle trees in code, to be able to do the logic to traverse trees properly, and to deal with the nodes, and the leaves in a tree, but if you can use a Composite Pattern to do that, you can greatly simplify it by creating this abstraction above the tree that lets you operate on the tree directly, and not have to traverse that tree down, and work on each node, and each leaf. Then finally, the other place that I find this pattern useful is when you have some kind of distribution. We saw in our example that we were trying to distribute Gold to Members of a party, and that was a good time to use a Composite Pattern. Anytime you're trying to give out something, or you're trying to divide something up, you can probably utilize the Composite Pattern to do that. Summary So that's it for the Composite Pattern. The Composite Pattern really isn't that difficult of a pattern. Like I said, the hardest thing is just to know when to use it. In this module we covered the Composite Pattern. We saw how the real life example of using email is a great example of how we're using the Composite Pattern in our daily lives, and how we could think about our code in the same way. Then we went through this example of splitting up the gold, and you can see here in this last slide that I've drawn out the final tree that we ended up creating. We saw how we could take some complicated code that was a little bit difficult to maintain, and difficult to understand, and we made it really simple just by applying this Composite Pattern, because we were able to treat leaves, and nodes, or branches, as the same. And by doing that, it greatly simplified our logic, and you can see even this complex tree structure, very easy to split gold without having to get into all of the details of, is this an individual, or is this a group. We handled that by putting that logic into each one of the Group class, and the Person class, and making a Composite that let us treat them exactly the same, by having that party interface. Then finally we talked about some of the ways that you can use the Composite Pattern, and some of the things to look for to identify when you can use it. Well hopefully you've learned how to use the Composite Pattern, and that you'll be able to start using the Composite Pattern in some of your code. Decorator Design Pattern Introduction Hello. This is Brian Lagunas, and in this module, I'm going to discuss the Decorator Design Pattern. The Decorator Design Pattern is a structural pattern which is used to extend, or alter the functionality of objects at runtime. It does this by wrapping them in an object of a Decorator class, leaving the original object intact without modification. I recently worked on a legacy application in which there was no client side validation. I used the Decorator Design Pattern to add validation to all client-side objects without modifying the existing code structure. This allowed me to not break anything, yet at the same time add the required functionality. Motivating Example Let's look at an example in which the Decorator Design Pattern could really help us out a lot. There's a pizza company called Acme Pizza, and all they sell is pizza. When they first started their company, their class diagram for their application looked something like this. They have a base Pizza, which would contain Description of the Pizza. It would Calculate the Cost, and then a method to return the Description. And in the beginning they just had a LargePizza, a MediumPizza, and a SmallPizza, and each Calculated Cost differently, so they each implemented their own implementation of the CalculateCost method. Well they soon realized that people liked toppings on their pizza. For some strange reason, toppings just make pizza that much better. So, they decided to add three new toppings. They wanted Ham, they wanted Cheese, and they wanted Peppers. Well now that they know they needed three new toppings, they needed to modify their class diagram and their application to handle those toppings, and calculate the cost, because each topping cost a different amount, and when you've added them to a Pizza, a Small, Medium, Large, you need to calculate those differences. So this was their attempt. They took the approach of creating a new concrete class for every single possible combination of the Ham, Cheese, Peppers, LargePizza, MediumPizza, SmallPizza combinations. As you can see, this results in what I like to call class explosion. And this is what they get with just three toppings. What happens when they add three more? Well now you have exponential possibilities of combinations between Pizza sizes, and Pizza toppings. And each one of those combinations will calculate their Description, and their Costs differently. As you can see, by taking the inheritance-based approach, they will open themselves up for a very hard to maintain application, which will be time consuming to implement new toppings, or new functionality. Intent What does the Decorator Design Pattern do for us? Well, for one, it allows us to add functionality to existing objects dynamically at runtime. Meaning that as the application is running, and the user is interacting with your application, you can have logic that determines what type of functionality to add to an object. This is different than adding functionality to objects at design time, which normally involves inheritance. You have to create new classes, and subclass a base class to add that functionality. It also provides an alternative to sub classing. It is easy to add functionality to an entire class of objects by sub classing it, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object, and leave others like it unmodified. With inheritance, as you add more behaviors to a base class, you will soon find yourself dealing with a maintenance nightmare. A new class is created for each possible combination, resulting in class explosion. It also encourages a flexible design. We want our applications flexible enough to take on new functionality to meet changing requirements. We don't want a rigid design where we must continuously subclass. We also want to prevent modifying a base class that isn't appropriate for some subclasses. The Decorator Pattern also naturally supports the Open/Closed Principle. The Open/Closed Principle states that classes should be open for extension, but closed for modification. Basically, you spend a lot of time and effort getting the code in your base class functional and bug free. So you want to lock that code base down. But chances are someone's going to need to add functionality to that object. Of course, you don't want them in your base class breaking all the code you spent so much time getting to work. So you need to leave it open for extension. This is a good principle to keep in mind, as it keeps your class stable, but leaves it open for extension if someone wants to add behavior. Applicability When would you want to use the Decorator Design Pattern? Well, the book answer is anytime you want to add responsibilities to an object dynamically at runtime, without affecting the other objects in the class. But in my experience, there are three common scenarios in which you would utilize the Decorator Design Pattern. The probably most common scenario is when you're dealing with legacy systems. Most of the time, you're part of a project team that has to maintain a preexisting system. And sometimes these systems can be pretty nasty. But you often have to add new functionality to these systems. Using the Decorator Design Pattern, you can add new functionality to the current legacy system without having to worry about touching the current spaghetti code that's probably in there. Another common scenario is when you need to add functionality to UI controls. You see some examples of needing to add scroll bars to windows, or functionality to buttons. Sometimes it makes more sense to use the Decorator Design Pattern to add functionality to a control rather than subclass that control, and add your functionality that way. There actually exists one implementation in the .NET Framework via the IExtenderProvider interface. The IExtenderProvider interface permits developers to assign new elements to existing components and controls without inheritance. That is a great example of how the .NET Framework utilizes the Decorator Design Pattern internally. Another common scenario is when you're dealing with sealed classes, which may be in a third party DLL, or possibly the .NET Framework itself. The Decorator Design Pattern allows you to add functionality to these classes, even though they're sealed. Structure Let's take a look at the structure of the Decorator Design Pattern as it is represented by UML. There are four main parts to the Decorator Design Pattern. The first one is the Component. The Component is your base class, and it's the base class for all Concrete Components, as well as all the Decorator classes. For example, if I had a class diagram of all types of Animals, such as dogs, and cats, and goats, and horses, chances are my base class, or my base Component would be an Animal or Animal base. And this Animal base class would define all the Attributes, and Operations that are common across all Animal types. Now, of course, if you do not wish to create any actual functionality in this class, you may decide to create it as an interface instead. The next part is the ConcreteComponent. This is the object to which additional responsibilities, or functionality can be attached. The ConcreteComponent inherits from your Component base class. And there may be multiple ConcreteComponent classes, each defining a type of object that may be wrapped by Decorators. For example, this ConcreteComponent may be a dog. I can have another one that's a cat, and another one that's a horse, or a goat. Basically, it subclasses your base Component class, and in the case that your Component is an interface, then this would be your Concrete implementation of that interface. The next one is the Decorator. The Decorator is the base class for all ConcreteDecorators, and it inherits from the base Component, so that Decorators can be used in place of ConcreteComponents. What I mean by that is since the Decorator inherits from, let's say, we'll go back to our Animal example, say this is Animal, and we have an Animal Decorator. Well because our Decorator inherits from Animal, it is seen as a type of Animal, just as our dog, or our cat, or our goat are seen as types of animals. So, because --- our Decorator's also seen as a type of Animal, this allows multiple Decorators to be applied to a single object. One thing you need to pay attention to with the Decorator, is that it will store an instance of the Component being decorated. So if we go back to our Animal example, my Decorator will have a Member of type Animal, and you may call it MyAnimal, or whatever you want to call it, but it's going to be of type Animal. Your Decorator will also have a constructor that accepts that Component as its parameter. Now that passed object is the Component that would be wrapped. So in this case, it would be the Animal that is being wrapped. The last one on the list is the ConcreteDecorator. This basically just adds responsibilities to the Component. In this UML diagram, I have two Concrete Decorators, ConcreteDecoratorA and ConcreteDecoratorB. Now DecoratorA is just adding NewState to the Component. I have added a new Property, and it's going to hold some type of data associated with that Component. ConcreteDecoratorB simply adds NewBehavior. I've simply added a new method that extends the behavior of my Component. How it Works How does the Decorator Design Pattern actually work? You've seen the UML diagrams. You've heard all the technical talk. So, tell me, how does it really work? Well it's simple. The Decorator just wraps the objects. The Decorator Pattern is also known as the Wrapper Pattern, because its key aspect is that a Decorator wraps around the object being decorated. Let's take our Pizza example. We have a LargePizza, and we need to add toppings to this Pizza. Instead of doing an inheritance, we can add Decorators as toppings. For instance, I'm going to add a Ham topping. So I wrap the LargePizza object in a Ham Decorator. We want cheese you say? Well easy. We create a Cheese Decorator and wrap the Ham Decorator object. Peppers too? No problem. Let's go ahead and create a Peppers Decorator object, and wrap the Cheese Decorator object. We initially started out with just a plain old LargePizza object. But using Decorators, we were able to add our Ham, Cheese, and Pepper toppings. Now, we have to calculate the Cost of our Pizza, including the toppings. To do this, all we have to do is call the CalculateCost method on the outermost Decorator. Peppers is going to delegate computing the cost to the object it decorates. Once it gets the cost, it will add the cost of the Peppers as well. And all this decoration can occur at runtime, and use business logic determine what kind of Decorators are added, or even removed. Motivating Example Refactored Let's take a look at Acme Pizza's first attempt at adding toppings capability to their application. We want to reduce the complexity of this class design by implementing the Decorator Design Pattern. When we are done, we should have something that looks like this. Now, you will immediately notice that we have completely eliminated the class explosion. We still have our base Pizza class with the same Attributes and Operations, and the same three base Concrete implementations of a LargePizza, a MediumPizza, and a SmallPizza. We will create a PizzaDecorator, and each Decorator will represent a single topping. Even though we completely eliminated the majority of all the Concrete implementations of Pizza that the previous class diagram had, we will still be able to create any number of combinations between Pizza and toppings. Demo: Overview of the Project I've created a simple Console application. I've also created four folders in this application that would represent each Component of the Decorator Design Pattern. Our Pizza class is our Component. It's an abstract class which contains two abstract methods, one called GetDescription, and the other called CalculateCost. It also has a Description property. We have three Concrete implementations of this Component. We have our SmallPizza. We set our Description to the Small Pizza, and for CalculateCost, we're just going to return $3.00. Our MediumPizza, its Description is set as a Medium Pizza, and it costs $6.00. And then we have a LargePizza. Description is Large Pizza, and returns $9.00 as a cost. Currently, our Program is pretty simple. We create a new LargePizza, we output the Description, and then we output the Cost. So, let's go ahead and Run this and see what we get. As you can see, we have output the Description of a LargePizza, which is Large Pizza, and the Cost of the Large Pizza, which is $9.00. So everything works as expected. Demo: Create the Decorator Now, we want to add the ability to add toppings to our pizzas, and because we're using the Decorator Design Pattern to do this, we need to start off by creating a Decorator. So let's go ahead and create a new Class, and we'll just call it PizzaDecorator. We'll be sure to make our class public. And we need to inherit from our Pizza component. We also want to implement the abstract methods. The first thing I need to do is add a private member of type Pizza. (Typing) This is the object that will be decorated. The next thing I need to do is create a constructor. (Typing) This constructor will take a Pizza as a parameter. (Typing) We want to set our private member to the instance being passed in as the parameter. Now I'm going to implement these abstract methods by simply returning, if I can spell, (typing) the pizza's Description, and Cost, (Typing) just like that. Now, you may notice that I have some things popping up on my screen that you are probably not used to seeing. You also see some code highlighting, and things like that. This is a plugin called DevExpress CodeRush. So, if you see things popping around, and you don't know what they are, it probably belongs to the CodeRush plugin that I'm using. Okay, so now that we have our Decorator implemented, let's go ahead and start working on our ConcreteDecorators. Demo: Create the Concrete Decorator The first one I want to start with is the CheeseDecorator. So let's go ahead and Add a new Class, and we'll just call this Cheese. Make it public, and since this is our ConcreteDecorator, it needs to inherit from the PizzaDecorator. Let's add a constructor, which takes a Pizza, and pass it along to our Decorator. (Typing) Great. Now, let's go ahead and override the GetDescription, and the CalculateCost methods. Well I know that I want to concatenate the Pizza's Description, along with the Cheese. So, before I do this, I need to go back to my PizzaDecorator, and I'm going to make my member protected. This allows me to see this in any derived classes. So now, I can go pizza.GetDescription. We'll go + (Typing) Description. Great. Well I'm going to go ahead and use String.Format, and I can't forget to set my Description to Cheese. I also have to calculate the total cost. So I'm going to take the current cost of the Pizza, (Typing) and add $1.25 to it, because Cheese is expensive. Let me make a quick modification to my namespace. And now we have to go make a slight modification to the Program. First off, we can no longer say largePizza = new LargePizza. Instead, let's just say a Pizza equals a new LargePizza. And we want to add a topping. So let's say largePizza = new Cheese, and it takes a Pizza. This is the object we're going to add the functionality to, or the object we're wrapping, which, in this case, is the largePizza. And now, let's go ahead and change this to calculate, to GetDescription. (Typing) Now when I Run this, we should expect Large Pizza with Cheese and a total of 10.25, because a Large Pizza is $9.00, add the Cheese of $1.25, and now you have a total of 10.25, so this works as expected. I'll go ahead and Close that. So, what we did here is we had a Pizza, and we created an instance of a new LargePizza. Then we wrapped that largePizza with our Cheese Decorator. So now, this LargePizza is of type Cheese Decorator. Okay, it's of this type Cheese object. So when we call GetDescription, we're calling it on the Cheese. The Cheese will then get the pizza's Description, and that is done when we created the Cheese object, we passed in an instance of the pizza. So we get the Description from the pizza, and we add the Description of the Cheese on it as well. And the same thing goes for the cost. We grab the cost of the pizza, and then we add our $1.25, which is the cost of the Cheese, to the pizza. So to demonstrate this more, let's go ahead and create two more ConcreteDecorators. We'll create the Ham, and then we'll create the Peppers. Demo: Adding more Concrete Decorators I went ahead and skipped ahead a little bit and created the Ham and Peppers Decorators. As you can see, they're very similar, almost identical to the Cheese Decorator we created, set, of course, to Descriptions match and the Cost is a little different. The Peppers add $2.00, and the Ham adds $1.00. So, let's go ahead and add Ham and Peppers to our largePizza. Well that's easy to do now. All I have to do is largePizza equals a new Ham, pass in the same largePizza, Run it. Now, I have a Large Pizza with Cheese, and Ham, with a total of 11.25. Great! Well, you know what? I changed my mind. Let's go ahead and add Peppers on there; largePizza = new Peppers. Pass in the largePizza, Run it. Now I have a Large Pizza with Cheese, Ham, and Peppers, and now my total is 13.25. Now, any time I want to add a new topping to my system, all I have to do is create a new Decorator, and have logic that determines when that Decorator is applied to my Pizza. This leaves my system very maintainable. I don't get class explosion, and I get to show off to the boss on how quickly I can add functionality to the application. Consequences Let's look at some of the consequences we will see when we use the Decorator Design Pattern in our applications. Well for one, by wrapping objects in Decorators, it leaves the original object unmodified, and unaware of any added functionality that has been applied to it. There is also no single feature-laden class that has every single possible option in it. This helps avoid huge inheritance trees as well. And because the decorations are independent of each other, they can be composed together in a mix-and-match fashion, and they can be chained together to add multiple behaviors, which can be a runtime decision, unlike inheritance. This lends itself very well to a flexible reuse of code. But, it can also increase the complexity of code. Not only do you have to write code to instantiate the Component, but you also have to wrap it with any number of Decorators. Larger number of smaller classes can sometimes be overwhelming to a developer trying to use the Decorator based API, because it makes it harder to learn the system, and to debug the code. Related Patterns The Decorator Design Pattern is a structural design pattern, but it's not the only structural design pattern. There are a handful of related structural design patterns, such as the Adapter, which basically is used for converting an interface of a class into an interface that a client expects. You have the Bridge, and Composite. The Composite is used to compose objects so that they can be represented in part-whole hierarchies, and tree structures. The Facade Pattern provides a high level interface that makes the subsystem easier to use, and basically hides a lot of complexity through a single interface. And you also have the Flyweight, and the Proxy Pattern, which is used when it's required to use another object as a substitute to control access to the object. For more information on these patterns, you can check the Pluralsight On-Demand Library, or use your favorite Search engine. Summary In this module, we talked about the Decorator Design Pattern. We learned that the Decorator Design Pattern allows us to add functionality and behavior to objects dynamically at runtime. We learned that it did this by wrapping the objects that are being decorated, which provides an alternative to sub classing. We also saw that the pattern helps support the Open/Closed Principle, which states that our classes should be closed for modification, but open for extension. We also saw how to implement and use the Decorator Design Pattern in our own applications. This is Brian Lagunas, and thanks for watching this module on the Decorator Design Pattern. Event Aggregator Introduction Hello. My name is Glenn Block, and I'm going to talk to you today about the Event Aggregator Pattern. Motivating Example To understand the pattern, let's start with a simple example. You have an order entry system that has many, many screens. There's an Order screen, an OrderDetails screen, an OrderHistory screen, and a Shipping screen. And each of these screens have to be synchronized whenever a certain activity takes place within the application. For example, when a user selects an order, then you expect that all of those different screens would display the currently selected order. Whenever an order is created, each of those screens would then have to display the created order. And in the same way, whenever an order is updated, saved, or deleted, you would expect for all those different screens to display the current information. The challenge here is how do you synchronize all these different screens together? Demo: The Order Application Let's take a look at such an application. So here we have a mock Order Entry app, and we can see that on the left side I can select different Orders. As I'm selecting Orders, I can see that the screens on the other side are updating. So, for example, if I go to the Detail screen, and I've switched to Order 2000, you see instantly it updates to Order 2000. If I go and add a New Order, I can see that the screen is synchronizing, showing me that New Order. And if I go to any one of the Orders, and I click Save, you can see that immediately it shows me that that Order has been Saved. Pattern Intent The Event Aggregator Pattern is going to help us to address some of the scenarios that we just saw in the previous application. It does this first by providing a central place where events are registered, thus making it easier for subscribers to discover those events. It also reduces coupling between publishers and subscribers, because today when we use .NET events, actually the publisher holds a reference to all of the subscribers that are out there. That means that in order for a subscriber to be hooked up to an event, there has to be a direct connection back to the publisher, which decreases maintainability. But with the Event Aggregator, the publisher and the subscriber are completely decoupled from one another. By doing that, it reduces friction for introducing new events, because I can add new events into the system, and my subscribers simply have to be able to go to the Event Aggregator to get those events. They don't have to know how the source of that event is. That's the Event Aggregator's job to route from the source to the subscribers. So that makes it very easy for you to introduce new events in the system. Lastly, a big thing that Event Aggregator does is reduce memory management issues that we experience today when we work with .NET events. Because of the fact that the publisher holds a collection of the subscribers, it's the subscribers' responsibility to unsubscribe themselves, and if they don't do that, there will be memory leaks, and often today many application developers that work with .NET events don't go through the process of manually unregistering the subscribers to those events, and as a result, memory leaks in the application prevail. Applicability Let's take a look at where this pattern is applicable. If you're building a composite application, and what I mean by that is an application that's broken up into several modules which are coordinating between one another, and with which each perform different aspects of the system, like an Order module, or Reporting module, then you're going to find this pattern very useful. Even if you're not building a composite application, or if you have really complicated screens, for example, in the Order Entry app that I showed, that could be a composite, but it doesn't necessarily have to be a composite, but there is quite a bit of synchronization, so that the pattern really helps us there. If you have many publishers and subscribers, meaning there are events where you have these many-to-many type relationships where there are different publishers, or if there are just many, many different subscribers that need to be connected, you'll find this pattern useful. If you find that you're adding new events to the system quite frequently, and that's painful, then this pattern's going to be for you. And if you find that you have to do Static events, then that really is a red flag, where you may want to look at using an Event Aggregator to solve that problem for you. Demo: Solving With Standard .NET Events Let's take a look at how one might solve these problems today not using Event Aggregator. So, here I'm going into my version of the solution that doesn't use the Event Aggregator. And the first place I'm stopping at is our MainPage. And if you can see, our MainPage has a StackPanel that has two Buttons, New and Save, and then we have a StackPanel that has within it a List of Orders, and a TabControl that is going to contain the OrderViews. Let's take a look at what's going on in the code behind for our MainPage. First, we have these two events, OrderCreated, and OrderSaved, and we also have this collection of Orders. We'll come back to both in a bit. The first thing we're going to do is we need to populate our UI with the different views that are available for the order. If you remember, when we ran the application, as I select an order, I can see various different views for that order which were represented in tabs. So here in AddOrderViews, I'm just going to populate those tabs. Nothing special there. But, I need each of the views within those tabs to be synchronized such that whenever I select a new order, they display that order. So there's some notification that's going on there. So to handle that, what I've done is each of these views actually implements a very simple interface called IOrderView, that has on it two methods, OnOrderSelected, and OnOrderSaved. So then what I can do is I can take each view, cast it to its interface, and wire it up. And what am I wiring it to? Well, I'm wiring the events that the MainPage itself raises, OrderCreated, and OrderSaved, as well as the OrderListViews OrderSelected event, and I'm wiring those to corresponding, those corresponding methods that I showed on the view. So if we take a look at one of the implementations, for example, the OrderView, I can see that in OnOrderSelected, I'm simply updating a label that says that current order number is the OrderNumber. And if I jump over to OrderDetail, it's almost identical. The only difference here is you can see it's highlighted, is I have the word Order Detail, instead of Order, and that's just so that when you look in the UI, you can actually tell that the synchronization is happening. Jumping back to our MainPage, we see that after AddOrderViews, this LoadOrders method is called. Now, LoadOrders is really just loading up some dummy data. It's not doing anything that interesting, other than the fact that it's actually going to the OrderListView, and it's setting the Orders that have been created, which under the hood, is actually going to the OrdersListControl within the OrdersListView, which, in this case, happens to be a grid, and it is setting the selected index for the first order in the list. It's also subscribing to the CollectionChanged event on that OrdersCollection, because it's an observable collection, and in the future, any time orders get added, or removed from that collection, it's then going to update the SelectedItem to be the newly added order. After the Load is completed, the next thing we're going to do is wire up our two Buttons, the New and the Save Button. We're going to wire those up each to a New and Save Click handler. The New Click handler is basically going to create a new Order, Add it to the collection, which you remember being that it's an observable collection that will cause the grid automatically to update that as the selected item, and then what it's going to do is check to see if anybody's listening to the OrderCreated event that it raises, and if so, it's going to raise that OrderCreated event, which we saw before would result, as you can see up here, in the view's OnOrderSelected method getting called, because we said that creation and selection are really both being handled the same way from the view's perspective. On Save, we do the same thing, making sure that there's somebody who's listening to the OrderSaved event. If not, we just Exit out, because the only thing we want to do in Save Click currently is just notify. So, in this case, once the Order has been Saved, we basically grab the current Order that's selected, and then we fire the OrderSaved event to notify the rest of the views that the Order has been Saved. Now that we understand the code, let's Run the application again, this time with a breakpoint, so we can see it in action. And I've put a breakpoint here you see on the OrdersList_SelectionChanged event. So as soon as the application starts, and the Orders are loaded, the first Order is selected, and once that Order is selected, I see the SelectionChangedEvent fires. Now, the OrderListView then in turn fires the OrderSelectedEvent to tell the other views that are interested, hey, an Order's selected. As soon as he does that, those views then receive that event, and they then update themselves accordingly. So you can see here now that my Header, my Detail, and my Order History all say 1000. If I then go to 2000, we can see now that the Order that's been selected is 2000, (Typing) and we see the same synchronization logic executing. Issues with Current Implementation Let's take a step back and see if there are any issues with the code that we just saw. For one thing, there's a lot of coupling between the publishers and the subscribers. You may have noticed that the MainPage has all the logic currently, and has to actually have direct references to each of the subscribers so they can wire them up. It also has logic, very specific logic of how to do that wire up. So, although today it does support adding new IOrderViews, it only will recognize those IOrderViews if they were added to the tabs. But what happens if there are other views that get added, which don't show up in those tabs, but they happen to be IOrderViews? The logic is not going to wire those up. Furthermore, if there are other listeners that are interested in one of the events, but they're not an implementer of IOrderView, they will also never get hooked up. This makes it very difficult to add new subscribers to the system, or to introduce new events. It can be done, but it's very difficult because it requires changes in many, many different places, and when we build systems that we want them to be maintainable, one of our goals is really to minimize the amount of change that we have to make to introduce new functionality for the system. Another problem that we have in the current implementation is there are several memory management issues that could lead to memory leaks. Basically, whenever you have a .NET event, the subscribers to that event are actually held as references from the publisher of the event. That means that those subscribers will not go away until the publisher goes away, or until they unsubscribe themselves. So we've got several events here that we're firing in the system that are each holding references to the subscribers. Now, the challenge you have, even --- if you want to handle unregistration yourself is how does a class know when it should unregister itself from the event? You end up possibly doing another event to tell the thing, hey, you need to unsubscribe yourself, and it's just very, very difficult to manage, which means often what you end up with is leaks where those classes just don't go away. And in a large system, that can really hurt you in the long run. Pattern Structure The Event Aggregator Pattern is here to help. The pattern is actually quite simple. It introduces, in between publishers and subscribers, an Event Aggregator. That Event Aggregator, basically, aggregates events. As you can see in the diagram, the subscriber is actually observing the Event Aggregator, not the publisher. The publisher only knows about the Event Aggregator, not the subscribers. That's the pattern. Demo: Using Event Aggregator Here's how it actually gets used. So in order to implement the pattern, both publishers, and subscribers, they need to get a reference to the aggregator. The publisher then calls methods on the aggregator to publish its notifications. And the subscribers, because they have a reference to the aggregator, they go and they just simply say, here's the events I'm interested in, and I'm going to subscribe to those. Let's see how we can now use the Event Aggregator within our OrderEntry application. What we're looking at now is a refactored version of the application we saw before, only now it's using Event Aggregator. So, if we jump into the MainPage, the first thing we see is we've got this reference to this IEventAggregator called of _ea. If we jump and take a look at that interface, it basically has two methods on it, one called Subscribe, which takes a subscriber, and a second method, which is a generic method called Publish, which takes in a TEvent. Now in this case, you can see the TEvent doesn't have any constraints on it, so it can just be any class. Any class, in this case, can be an event. And if we look below, we see that whereas before I had .NET events that I was using, in this model I've now defined classes called OrderCreated, OrderSelected, and OrderSaved, which will represent the different events that I will be firing within my application. Jumping back to our MainPage, we can see in the constructor that the first thing that I'm doing is instantiating an instance of SimpleEventAggregator, which implements the IEventAggregator interface. We'll come back to that later, but for now, we're just, let's focus on the usage of the Event Aggregator. Now, my OrderListView, as orders are selected, needs to notify the child views that an order has in fact been selected. So, we're going to pass the OrderListView the EventAggregator. If you remember our first implementation, basically what would happen is the OrderListView was throwing events, and all of the children were being wired up to listen to those events. But in this case, that's no longer necessary. Now, if we come down to our AddOrderViews, in the previous implementation we basically had to wire up each of our views manually to the events coming off of the OrderListView. In this case, we're just going to pass each of our views the EventAggregator instance, as you can see here. Now, whenever a user creates a new order, what we see now is instead of having to fire events using .NET events, we're actually using the Event Aggregator, and we're just calling Publish. And notice what's nice about this too is I don't have to have any conditional logic that checks to see if there are any subscribers, which I had in the previous implementation. I just fire the notification, OrderSelected, passing in the order. And remember that OrderSelected is just a class, it's not any kind of special event class, or doesn't have to implement any specific interface. In the same way, when the Save Click Event fires, we're going to also call Publish, and this time passing OrderSaved. So that covers the publication side of things. Let's see how this works now on the subscriber side. So we'll jump into our OrderView, and the first thing we can see is that's implementing two interfaces which derive from ISubscriber of T. It's implementing ISubscriber of OrderSelected, and ISubscriber of OrderSaved. Now, if we jump to the ISubscriber interface, we can see that ISubscriber of T has an OnEvent member, which has an arg of type T. In this case, because we've implemented ISubscriber of OrderSelected, and ISubscriber of OrderSaved, we have two separate methods, one for handling OrderSelected, the other for handling OrderSaved. The next question then is, how does this actually get wired up? Well, if we look in the constructor of the OrderView, which is receiving the EventAggregator instance, the first thing it's doing is calling Subscribe, passing in itself. When it does that, the EventAggregator will automatically wire it up such that it will receive the events that it's interested in. Now, there're several different approaches for how you can implement the Event Aggregator Pattern, and this is one that Jeremy Miller, the author of StructureMap, really promoted, and what's nice about it is that it allows the class that is going to receive the events to express its intent very clearly in the signature of the class. I don't have to read through the class to understand what are the different events that it subscribes to, because it's expressed it very clearly through implementing that interface. (Typing) Now the other thing that's really nice about this pattern is that notice that the OrderView doesn't have any reference to the actual publisher. This is that decoupling that I was talking about. All the OrderView has is access to the EventAggregator, and in the same way, if I jump back to my MainPage, we can see that the Publisher also has no access to the listeners. This is really the beauty of the Event Aggregator Pattern, because now I can introduce new Subscribers, new Publishers, and new Events, and I don't have to change the EventAggregator interface, and I don't have to change the public surface area of my APIs. One of the other nice things to mention about the EventAggregator, is the fact that it is very easy to test. Because you're passing in the aggregator as a dependency and it implements an interface, it is very easy to mock in a unit test such that I can verify things like, does the OrderView wire itself up properly to the events that it's supposed to listen to? Also, because I'm passing it in through the constructor, that means if I want to, I can use an inversion of control container, like StructureMap, or Castle Windsor, etc., to inject the EventAggregator at runtime. Demo: Details of Implementation Now that we've understood how we use the EventAggregator, let's take a quick look at the implementation. So first we can see that I have this SimpleEventAggregator, which implements our IEventAggregator interface. The EventAggregator's holding a collection of WeakReferences for each type of message. What this is for is to allow the managing of the references such that the subscribers are not held alive simply by the fact that they listen to a particular event, because the EventAggregator is only going to hold a WeakReference to those Subscribers. If we now take a look at the Subscribe method, see the first thing is that we're passing in the Subscriber instance. Next we're taking a lock, because of the fact that we're going to modify the collection of event Subscribers, and there might be multiple parties that are trying to do this at the same time, as the EventAggregator can be used with multiple threads. (Typing) The next thing we're going to do is look at all of the interfaces that the subscriber implements to see if it is implementing ISubscriber of T. If it is, we're going to create a weakReference for the subscriber. And then what we're going to do is foreach of the subscriberTypes, we're going to grab the collection of subscribers, and Add ourselves to that collection. Now, if we look at this GetSubscribers method, you can see that it's also taking a lock, because what it needs to do is, the eventSubscriberLists collection is a high level collection for all the different eventSubscribers, and if this is the first time we're ever subscribing to this event, that collection doesn't exist. So we take a lock so that if that collection has not been created yet, we're going to then create a new List of WeakReference, and Add this new collection to it, such that in the future, if others subscribe to this event we'll carry that information in the collection. On the Publisher side, the first thing we're going to do is take the event that was passed in, and we're going to create on the fly an ISubscriber of T to match that event. Next, we're going to call GetSubscribers to retrieve the subscribers for that specific event. We're going to then loop through each of the subscribers, and check to see if the subscriber is still alive, because remember, the EventAggregator is now using WeakReferences to hold onto the subscribers, so they may have been garbage collected in the meanwhile, which is fine. Next, if the subscriber is still alive, we're going to cast it to the specific ISubscriber interface that represents the current event. Now, the publisher and the subscriber might be living in different threads, so we're going to use the SynchronizationContext in case the subscriber is living on the UI thread, for example, and the publisher is not, to ensure that everything gets marshalled to the correct thread. And if there's no SynchronizationContext, then we're just going to instantiate a new one. Finally, we're going to post onto the SynchronizationContext to fire on the OnEvent, or to invoke the OnEvent method on the subscriber, passing in the Event class itself. Basically, when this happens, the subscriber will get notified. If however, the subscriber was not alive, meaning the instance has already died, we're just going to go remove that. Now, we can't actually remove it from the collection as we're iterating through, because you're not allowed to modify a collection. If you do, you'll get an Exception if you modify it while you're iterating it, so we've Saved any of these subscribers that we found that have already died, in a subscribersToRemove collection. Then at the end, if there were any items in that collection, we're going to do a lock, and we're going to now remove the subscribers. Consequences of the Pattern As a result of using the Event Aggregator, we see several benefits. First, we've now decoupled the publishers and subscribers. That means that I can reuse the various components of the system within other applications because of that decoupling. Also, through the decoupling, it's easier for me to test the components of my application if I'm doing something like test driven development. Additionally, we've now made it more easily to add new events to the system. Because of that decoupling, if I want to introduce a new event, my publisher just publishes that event, and my subscribers, they only need to have access to the definition of that event, but they don't need to have access to the publisher. Lastly, we've seen how using weak references in our implementation of the Event Aggregator, we've been able to reduce a lot of memory leaks, because the subscriber no longer has to worry about unsubscribing itself, as when it subscribes, that does not keep a strong reference between the publisher and the subscriber, or between the Event Aggregator and the subscriber. Known Variations There're several known applications of the Event Aggregator Pattern that you can find out in the wild. First, there's StoryTeller by Jeremy Miller, which, as I mentioned, the implementation that we showed is very similar to. The one primary difference is that rather than requiring the subscribers, which in his model implement an IListener of T interface, from having to themselves wire up to the EventAggregator, Jeremy uses his IOC container StructureMap and extends it in such a way that as anything gets created by the IOC, it looks to see if it implements the IListener of T interface, and if it does, it automatically wires it up, which is very elegant, and if you're using an IOC container, you can really go further at reducing the coupling from the subscriber standpoint, because they don't even need to have access to the EventAggregator. The next one is MVVM Light, which is written by Laurent Bugnion, and MVVM Light is basically a library for wiring up ViewModels primarily, and he introduces within MVVM Light a Messenger class, and that Messenger class basically allows you to publish, and subscribe to different messages. Now, it uses an approach that instead of just wiring up through the implementation of interfaces, the subscriber in that case basically uses lambda expressions to wire themselves up. So, what will happen is the subscriber will take Messenger as a dependency, and it will call the Subscribe method, passing in a lambda expression. Lastly, there's Prism from the Patterns and Practices Team. Prism also includes an EventAggregator implementation. It's a little bit different than the one that we showed here. It's closer to what MVVM Light uses, though Prism introduces actually an Event class that the publisher and the subscriber use, and derive from, and that Event class carries arguments, so they've separated out the Event class from the arguments itself. Related Patterns There're are several other related patterns you may want to look into. The Pub/Sub Pattern is a way of decoupling publishers and subscribers, but primarily it's used for messaging based solutions, where there actually is a physical boundary that separates the publisher and the subscriber, which differs from the Event Aggregator in the sense that the Event Aggregator is all in memory, and it's really just classes, they're not messages. And the Observer Pattern is basically implemented here because the subscriber is actually observing the EventAggregator to look for notifications on the Events. I mean, actually the EventAggregator notifies the subscriber, but the subscriber calls the Subscribe method, therefore it becomes an Observer. For more information on the Event Aggregator, check out these references. Summary In summary, the EventAggregator is useful for synchronization of different components in a complex system. It's going to reduce coupling, and it's also going to improve testability. And it may be overkill when you're building a really simple system, so the key here is if there is a lot of complexity, then the EventAggregator is going to help you. Facade Pattern Introduction Hello. This is David Starr, and welcome to this module on the Facade Design Pattern. I like the Facade Pattern because it's rather fun to learn as we go through the formal expression of the Facade Pattern, that what it proposes is probably something that you've been doing as a developer for years without even thinking about it. It's just kind of nice to know that this thing that I do naturally as a developer, it actually has a name. Intent It's a fairly common situation for software developers that we'll find ourselves working with a preexisting API that might be very complex. It might be really big, and have a lot of functionality. But the only thing we're interested in is a very small slice of that functionality, and it would be really nice if we could dress up that API, or wrap it in some other code that would make it a bit easier for us to consume. That's the whole idea behind the Facade Pattern, and the intent here is that we'll be able to provide an interface to this larger API, but this interface that we'll have will be very fit for purpose, and expose for us exactly those features and functions that we need to access. Now, that's not to say that we're going to have direct access into that API. We're going to create a little wrapper around it. That Wrapper class is the Facade. Now, one really good reason to do this is to make one very complex API much simpler to use for our express purposes. And when we talk about exposing an interface here, it could be a class definition. It could be a class definition defined by a .NET interface. But, in this case, when we expose what would normally be a set of complex interactions with a single simpler interface, it might just be a concrete class, and the interfaces we're talking about are the publically available methods on that concrete class. And it's not uncommon that people will use a Facade to sort of hideaway a poorly designed API, and this may be one that you've got as legacy code in your application, or in your organization. It might be one that you've purchased, inherited from some other place, but it's a fairly common desire to want to take a preexisting API, and abstract it behind a single class. That's Facade in a nutshell. Demo: Motivating Example 1 Here's a small application that uses several other services to do its work, and, in this case, we're going to start with my zipCode here in Boise, Idaho, and pass that into a GeoLookupService, getting back some information, and then talk to a WeatherService and a conversion, an English to Metric Units Converter, finally deriving the current temperature in my city and state in both Fahrenheit and Celsius. If we pop over to our command-line window, we can Run this application. It's just facade1.exe, and we can see what gets printed out. The current temperature is 86.5 degrees Fahrenheit, 30.3 degrees Celsius, in Boise, Idaho. If we pop back over to our code, there are several things that this method has to do. Getting the zipCode might simply be a matter of input parsing, so we're not so concerned with how that gets done, and the printing out here at the bottom, this is also not going to be something that we necessarily are going to abstract out of the application. But, if we look at what's going on here in the heart of our method, we can see that we're talking to what one, two, three different, fairly potentially complex APIs. We've got an EnglishMetricConverter that might simply be an API. We've got a WeatherService. That may indeed be a web service that we're making a call across the internet. So might this GeoLookupService. And, you know, rather than having my class here, my code, have to know about all three of these services, all I really want is to be able to take a zipCode as a string, and get from there to the current temperature with some city and state information. It might be nice to take all of this code and get it behind one very simple to use class, or method call, so that I don't have to know how to perform all of these lookups, and invoke all these operations against these multiple APIs. Okay, let's take a little deeper look at our project here, just so that you're oriented to it. We have a separate .NET assembly, this project down here is a standalone DLL, and we've got representative services and classes here for our Converter, a GeoLookupService, LocalWeatherService, and, oh, we're actually not using this class, LocalWeatherService. We just have this WeatherService. Several classes that are in a different, or preexisting API, and we have to know about all these little moving parts and pieces in order to take advantage of them. Demo: Motivating Example 2 I would also like to show you a very real world Facade implementation, and to start that discussion, let's take a look at some code that's used inside This Library, PS for Pluralsight.Search is the one that sits on top of the Search capability of, and underneath our Search, we use Lucene.Net. This is an open source port of a Java Search Engine. And when we look inside this DLL, we can look inside here using our Object Browser, you can see that this is a very large API. Just here within the Lucene.Net, and we're interested in some classes, Document, Field, things like that over here in this Documents namespace. We're interested in some particular Analyzers over in this Analyze namespace, but I've gone through and figured out exactly what we need from Lucene in our Search Engine, and the objects that we need to take advantage of. There aren't that many. Even though the API itself is quite large, we're only interested in a small subset of functionality. So, rather than asking the next developer who comes along in our project to learn all about Lucene, it would be really nice if I could provide just a single access point for Search on top of the Lucene Library, and we'll take a look at how I used Facade to accomplish that. Structure The structure of a Facade may come in a few different forms. One is that we might have a caller. Let's use this red box to represent an initial calling application that takes a direct dependency on an existing API. This API could, for example, be that Lucene Search API that we saw an example of a little bit ago, and we have this application that's currently taking a dependency on that API, and it has to know about all of the various interfaces, and all the various classes, the methods, and how to work with them inside that API. And what we'd like to do is change this dependency such that the calling application need only take a dependency on a Facade class that will wrap up all of the functionality of the current API. There's not necessarily a prescription for what the methods of that Facade will be, what the name of that Facade will be. Those are really all left up to the implementation. The idea here is simply that we're going to abstract away this functionality into a class, or interface, and that class, or interface will provide on it what it needs for the calling application. In a variation on the Facade Pattern, we can see that a Facade might be used to wrap multiple APIs, and this is what we'll do in our example code where we have multiple services, or multiple APIs that we need to talk to, but we really only want a very special purpose interface to accomplish one job and do it quite succinctly. And finally, I'll note that it's not uncommon to need a helper class to go along with the Facade. So, for example, if we have our new Facade, and we consider that an API, we can have the Facade class, which actually invokes Operations against the existing API, or APIs, but it may also require creation of some helper classes that this Facade will know about. And we'll see an example of this when we look at our weather zip code lookup problem. Consequences As with most patterns, there are some implications of using Facade, first of which is that we get this benefit, that the underlying API, or APIs that we are putting underneath our Facade, are made much simpler to use. However, we should note that we are exposing most of the time a very special purpose interface into those APIs. Therefore, we're probably not going to be able to take full advantage of all of the power in that underlying API through the Facade. And that can result in multiple Facades being created. Or, the Facade that we do have being updated, or have a need to be updated when we want to take more advantage of those underlying APIs. While this isn't necessarily a bad thing, it's definitely something that we should be aware of. Demo: Facade Pattern Example Recall the code that we saw in our command-line application that looks up weather by zip code. We said that we wanted to get all of this code behind a Facade. Well, let's see what that looks like. Over here, we have a new implementation of the same Program that effectively implements the exact same functionality. The way it does so is a little bit different this time, in that it's using a TemperatureLookupFacade. This is the name of the class that I created that is my Facade. I wouldn't say that it's a very typical thing to have the name of your pattern on your classes. We're really doing that for instructional purposes here. And we can see that what this Facade does, is we new it up, and then we have one method, and one method only on it, called GetTemperature. It gets a temperature by passing in the zipCode of the location we're interested in. Note too that the return type here is LocalTemperature, and we use this LocalTemperature object to do the same sort of output we did before, but this LocalTemperature type is definitely in collaboration with our TemperatureLookupFacade. Let's take a look inside the Facade at how it's actually implemented. We have a fairly well factored out class here that has several local fields. These local fields are the services that the Facade depends on. This, by the way, is just my implementation. A Facade can take various forms. We have a default constructor that news up those dependencies. We could be using an inversion and control container here, or something like that. We can also pass in on the constructor the dependencies that we want. Again, none of these things are really particular to the Facade Pattern itself. This is just a construction technique that I'm using in order to get some dependency injection capabilities on my Facade. This method, GetTemperature, is where the real work happens for the Facade. We've exposed one method, and GetTemperature uses the geoLookupService to collect some data, and uses the weatherService, and finally converts the Fahrenheit result that it gets from the WeatherService into Celsius, and puts all of that data onto a new local temperature object. This is really just a value object that's used as the vehicle for getting all of this data back from the method call. And that's really all there is to this Facade. Once that LocalTemperature type is returned, the members of it are used to populate the print string. And with that, we can jump over to our command-line application. We can Run Facade2, and see that we're getting the same results we were getting before. The difference now is that we have factored out the bulk of that code into a testable, and reusable class, TemperatureLookupFacade, and it makes use of this helper, or collaborator class, LocalTemperature to give us the data back we were looking for. Common Uses There're some common places we find Facade very useful in .NET programming, one of which is Data Access. It's a very common thing to do, to wrap up much of the functionality of ADO.NET behind some special purpose Facades that help us know how to work with, say a business object that we can get in and out of a database, rather than having to know all about command objects, and SQL connection objects, and SQL readers, and all that good stuff. Many applications have some sort of code that puts the ADO.NET API behind a Facade. Same is true for File and IO Streaming. We have a lot of options in the File IO namespace, particularly around streaming data back and forth to our disk, and it's very common to want to simply be able to hand off an object, and have it serialized down to disk, and so we might put that behind a Facade. And finally, we'll take a look at a very real world example now of how puts a Facade over the top of Lucene.NET, and we'll see how we've done that with Search. Demo: Real World Example Here we are back inside the Search code for This command-line application that we're looking at though is quite simply a wrapper around the libraries that were built to make Search available to the website. And this command-line tool invokes operations against that Search library, similar to how the website might use it. There are a couple of things going on here inside this Search method where I'm using a SearchEngineFactory that will bring back for me a SearchEngine, that would be a class that adheres, or implements rather the ISearchEngine interface. This ISearchEngine implementation for Lucene turns out to be my Facade class. Now as we saw earlier, there are a lot of classes and methods, and it takes some time to get comfortable with the API down inside Lucene.NET. Once I was comfortable with that API, I was able to wrap all of that functionality for our purposes on the website behind this one interface. ISearchEngine declares a Search method that takes a string, the number of hits to return, the maximum number of hits to return, and it returns an IList of RawSearchResults. Now a RawSearchResult is a type that I've also defined in my assembly that wraps Lucene, so this really is a collaborator with the Facade itself, the Facade being my class that implements this ISearchEngine interface. I'll go down inside that Lucene SearchEngine class, and we can see that it implements ISearchEngine, which gives us the Search method. Now, in addition to the ISearchEngine, this class derives itself from an abstract base class, IndexFacadeBase, which handles some of the setup and teardown of using the Lucene API for me. And I need to do that both when I search, and when I index my content, which is why we made it a base class. You can also see right away that down here on a private Search method, we're using a Query object. This Query object is actually defined inside the Lucene Library, and that's okay, but we don't want that abstraction to leak through outside the Facade interface into our caller code. Once we've done this, we're able to abstract all of the functionality that we really need away from the caller, so that the caller need only know that they have to get ahold of an ISearchEngine, and invoke Search against it. So again, our Lucene SearchEngine class is acting in the role of Facade in this case. If I switch over to our command-line, we can invoke our command-line search tool by saying Search, and a term that we'd like to search for, we'll search my local workspace of limited content for C#, and we got back some C# results. So it works, and it works very well for subsequent programmers who might want to come in and use the SearchEngine that we've implemented, and because I have it behind an interface, I'm able to put in a completely different search solution if I want to that isn't necessarily part of the Facade Pattern, but very useful nonetheless. Related Patterns Now there are some patterns somewhat related to the Facade Pattern, including Adapter, Flyweight, and Mediator. You can learn more about these in the Pluralsight Library. The thing that all of these patterns have in common is that they try and give a different outward facing appearance to some code that may do something more general, or more specialized than that which we're calling. So, we're basically wrapping up some already existing functionality, and putting it behind a class that gives us easy access into that functionality, and oftentimes that'll be by exposing a very fit-for-purpose, or special case contract that's useful not in all cases, but in a very specific case, like our Search example. Summary We learned here that we can use the Facade Pattern to expose a very formfitting specific interface so that we can take advantage just what we need to take advantage of in those APIs, without having to expose all of the underlying capability, and all of the underlying complexity. Another way people use Facade is to basically wrap up, or cover up legacy code that maybe they wrote, so that they can provide a different outward facing API to some team, or programmers that are part of the project. I call this shoving your dirty laundry under the bed. Works pretty well for a while. Facade can help you hide some of that legacy implementation away, if that's what you're trying to do. And one of the things I enjoy most about the Facade Pattern is the fact that most of us developers do it anyway, without even thinking about it. Raising up that level of abstraction turns out to be something that's almost primal in all of us developers, and odds are, you probably have done this several times in your life before you even knew it had a name. Thank you so much for joining me. This has been David Starr and I hope to see you in class sometime soon. Factory Patterns Introduction Hello this is David Starr, and in this module from our Design Patterns Library, we'll be taking a look at Factories. We're going to look at several different types of factories, including a very simple factory that doesn't necessarily conform to the patterns that were laid out by the original Gang of Four book, or subsequent books on the subject. We'll take a look at the Factory method. This is the more formal expression of the software factory, and finally the Abstract Factory Pattern. Motivating Example Now how do factories help us? We get the most benefit out of factories when we find our self in a circumstance where we have a class that implements an interface, as do many other classes, and we're unsure which object, which concrete instantiation we want to create and return to our caller. We don't want our caller to be tasked with having to choose which concrete instantiation of a class it's going to need. Factories are also applicable when we want to separate the instantiation of an object, the creation of it from its representation. For example, we may have setters, and have to call a bunch of set methods on an entity where we don't have access to the property setters, and we may want to wrap that up inside of a factory. And finally, any time we have a lot of if/else blocks, or select switch statements in our code, we might want to take a look at whether or not there's an opportunity for refactoring here that might lead us toward a factory. If what we're doing is simply returning an object based on some select parameter, odds are very good that we would get benefit from an object factory here. Demo: Example Here we have a very simple application, command-line executable, and it simply takes a command-line argument specifying the name of a car, in this case a class that we would like to instantiate. After we get that car, we get that IAutomobile instance back. This is an interface, IAuto, and we'll get that back from our GetCar method. We'll then take our car and Turn it On, and Turn it Off. And you can see in our GetCar method we're making the choice of which type of car we want to instantiate and return. We have cases for a BMW. We have cases for a Mini Cooper, and finally we have a default case, which returns NullCar. This is a use of the Null Object Pattern, which you can find more about in the Patterns Library. Let's take a look at how this works in practice. I'll switch over to our command-line where we can invoke our application. And we'll pass it to start off with a BMW, and the BMW is on and running. We can see that it was started, and then it was turned off. We can also Run, start and run a Mini Cooper. Now, we do have, in this case, a car that we would like to add to our list of cars that we have access to. Up here you can see that we have an AudiTTS. This car has been added to our classes under the Autos folder. In order to get this AudiTTS to be an available car from the command-line though, we'll need to include a new case statement, wherein we look for the word audi, and then return a new AudiTTS. Now that seemed like a small change, but what we really did there is we violated the Open/Closed Principle, which states that our classes should be open for extension, but closed for modification. We just modified this case statement to allow for the inclusion of a new car type. And it is there. I'll compile and hop back over, and we can now Run our Audi. And we can see that the AudiTTS is running, but there was an electrical fire. So we were able to include our new class, but unfortunately, in the process of doing so, a couple of things were true. One, the main application that's calling into our automobiles, that is the main Program here, has to be aware of the different types of IAutomobile implementations. Each of these Auto classes implements IAuto obviously, and the only thing that our Program really needs to be aware of should be the Auto interface. The other problem is that each time we add a new car, we'll need to come in and modify this switch statement to include that new car. Some of us have seen over time how these case statements can get huge. A really good example is when you're switching on a particular character, as you're doing file text reading. That can end up creating a case statement longer than an entire page of code in your IDE. Intent We saw that we had some problems in the code we showed earlier, and the intent of software factories is to correct those issues. First of all, we can separate the object creation from the decision about which object to create. Whether I want a BMW, an Audi, a Mini, or whatever, I need to be able to specify that without actually performing the object instantiation within my class, within my Program class, in our case. Also, we'd like to be able to add new classes, new cars, new functionality without breaking the Open/Closed Principle. That is, any time we want to add a new IAuto, that would be a factory-produced item, or any time we want to add factories themselves, so we may have multiple factory types that we would like to add, and we'll see more about that when we get to the Abstract Factory Pattern. Now, in many cases, we're going to store what type of object we'd like to create external to the application that's running. We'd like to store it in a database, or in a configuration file of some sort. A very typical example of this might be what type of membership provider we'd like to use in an ASP.NET application. We want to store that outside of the application, so that at runtime we can make a configuration based decision about what type of class to instantiate. Simple Factory Pattern In the first factory that we'll examine, I'm calling this just a Simple Factory, and its intent is to encapsulate object creation, deferring that away from the main Program executable. And this allows for deciding what type of class we're going to create based on configuration. We could store this in config files. We could store it in other persistent storage mediums, like a database, or like we're going to do in our example, we can make that decision based on input, and we're making our decision based on the input from the user in our sample application. What makes this particular factory unique, and some would argue not so great, is that the caller class does need to know what concrete factory class to call to do the instantiation. Let's examine how this looks in code. Demo: Simple Factory Pattern So in our Simple Factory, we have a very simple command-line application. This command-line application takes as an input argument a string that tells us what type of car we would like to instantiate. Once we have the name of that car, we'll then instantiate a new factory for making those automobiles, we'd create a new AutoFactory. And then we are able to invoke factor.CreateInstance passing our carName, and somehow the factory is making its decision about what type of car to instantiate, and passing it back to us in the form of an IAuto instance. Now, we don't know what concrete class is being instantiated under the covers, all we know is that we are receiving an IAutomobile, or an IAuto back, which lets us take that car and Turn it On, and Turn it Off. Let's see how this looks on the command-line. Actually Run our application, and we can pass in the name of an automobile to create. We want to run a BMW. So in this case, the BMW is created by the factory. It's on, we turn it on, and then we turn it off. And we can do the same with a Mini Cooper. We can turn one on, and then finally turn it off. Now let's take a look inside Visual Studio at how that's being achieved. The name of the car is being passed to the CreateInstance of the factory. And really what's important here is the interface of our factory itself, which has this one publically available method of CreateInstance. But let's look inside the creation, the constructor of the Factory, and see what's really going on. Well, the Factory is Loading the Types that it can return during its construction. So this particular Factory is loading up a Dictionary of Types that it will know how to create and return later. And it does so inside this LoadTypesICanReturn method. This method makes heavy use of reflection, which is a pretty common thing that we're going to find in factories implemented in .NET. What it does is looks inside the current executing assembly. This could look across multiple assemblies, if the code were written that way, and it pulls from this assembly all types that implement the interface IAuto, and it stores those inside this autos dictionary with the Name of the type as the key, and then the type instance itself as the value inside the object. When we call CreateInstance on the AutoFactory, it returns an IAuto. It does this by doing a lookup of the Type name. This would be the key that it's going to return. If we look in here, it's a very simple contrived example where we're ensuring that the type name Contains the string that's being passed. So, the string is part of the type name. If we find that to be true, we're going to return the Type itself, and then we'll use the applications Activator to Create an Instance of that Type as IAuto and pass it back. This is a very typical situation that we'll find in .NET applications. Note also that if we receive a null type back, that is we're asking for a type of car that we don't have a matching type for, then our factory returns a NullAuto. This is an instance where we're using the Null Object Pattern, and you can learn more about that in the Pluralsight Patterns Library. Specific qualities of this type of implementation are that our containing application, our caller, in this case the Program class, actually knows the concrete factory type that it's interested in. It knows about AutoFactory in particular. And so it's going to create its own AutoFactory, and using that AutoFactory it will make a call to CreateInstance, getting back the correct IAuto concrete class. Simple Factory Pattern Notes Here's a picture of our Simple Factory, and here we can see that the AutoFactory concrete class does not have an interface that it implements. That's what marks it as being this very simple type of factory. What it does do is, using the CreateInstance method passed back to the caller an instance of an IAuto. Now, we don't know what particular concrete class is being passed back from this CreateInstance method. It could be the BMW. It could be the Mini Cooper. It could be the NullAuto. We've encapsulated the instantiation, and decision making about construction into the AutoFactory itself. One note to pay attention to here is that all of the technique that we looked at inside the factory of using reflection, and activating the instance based on type, that's an implementation detail of this particular factory. We can achieve this in a number of different ways, but the key takeaway for the Factory Pattern itself is that we have this CreateInstance method that returns back an IAuto, the concrete class of which we're not quite sure. Factory Method Pattern Well now we're going to build on what we've already discussed with our simple factory by looking at the Factory Method Pattern. And the Factory Method Pattern gives us an opportunity to talk about the time-honored ancient tome of design patterns, that is the Design Patterns book by the Gang of Four, and that book describes Factory Method as shown in this quote. Define an interface for creating an object. That is, define an interface for a class that's going to be responsible for creating an object. Then let subclasses decide which class to instantiate. That is, let the different factories that adhere to the factory interface decide which class they are going to be responsible for instantiating. Factory Method lets a class defer instantiation to subclasses. While we may have an abstract based class factory at the highest level, we're going to have derived classes that are concrete factories that provide those concrete classes back to our application. And the major points here are that we're going to add an interface to the factory itself. So if we take the one from Simple Factory. and refactor out an interface for it, we'll have what we're after. Then we can defer that object creation to one of many factories. So, as before, we had one factory responsible for making all types of cars. Now we can have factories that specialize in their particular type of automobile, and our derived classes will achieve that functionality simply by overriding the Factory Method, that method defined on the base class, or interface, that is indeed the Factory Method. Demo: Factory Method Pattern On this class diagram, we can see that we have a base client class, this is our Program like we've had before, that is going to Load a given Factory using the IAutoFactory interface, and based on one of the Factories that we have in our project, we're either going to have a MiniCooperFactory concrete factory, or we're going to have a BMWFactory, one of these two concrete factories, either one adhering to the IAutoFactory interface, which provides a definition for the CreateAutomobile method that returns an IAuto. That means that this MiniCooperFactory is going to know how to create Mini Coopers, and the BMWFactory will know how to create BMWs. Each factory will do so based on whatever the needs of the concrete classes are it's responsible for creating. And, of course, both the Mini Cooper, and the BMW implement the IAuto interface, which is what actually gets returned back to the client from the factory interface reference. Alright, let's take a look at how this works in code. Over in our code, we have again a Console application, and our Console application, in this case, does something a little bit different than what we've seen, although it does look similar. We instantiate a Factory that adheres to the IAutoFactory interface. We'll take a look real quick at that interface. It merely defines in its contract a single method, CreateAutomobile, which returns an IAuto. Now IAuto is the car, the created object that we'll actually be working with. And then, after we got ahold of an instance of IAutoFactory, we're able to call CreateAutomobile on it, which provides to us IAuto, a car, which we can then TurnOn and TurnOff. And I'll go ahead and pop over to our Console, and Run the application. Note, in this implementation, I'm not having to pass a command-line argument. I'm no longer having to do that. The Mini Cooper S is up and running with a mighty roar, and then it gets turned off. So, obviously our Factory's working. We'll go back over to our code, and look a little bit deeper at what's happening here. It's not uncommon for us to configure which factory we'd like to use based on some sort of configuration setting, and it turns out that's exactly what we've done here. If we come up to Settings on our application, you can see that we actually have the Name of the Factory as a Value with a key of AutoFactory. So this is the Factory that we want to use to create Autos in our application. And if we look at our LoadFactory, it's going to dynamically instantiate that Factory based on the setting that we have in our Settings file, and so it will simply use reflection to Create an Instance of that type, and return it as an IAutoFactory. Now this allows us to configure our factories based on whether we are running in production, whether we happen to be running on stage, whether we happen to be running in a test environment. In fact, we can even provide fake, or mocked factories via configuration at the time that we're doing development so that we can write unit tests that don't have to deal with concrete implementations. Let's take a little deeper look at how these factories are implementing the IAutoFactory interface. We'll look first at the MiniCooper, seeing as that is the car that we've already run. We call CreateAutomobile. This Factory knows how to create Mini Coopers, and in this case, it's a Factory that knows how to create the Mini Cooper S. So, it news up its MiniCooper, and calls SetName. Now this is one of those types of calls that might need to be made on a class, or entity to get it setup properly, that we don't want people to have to guess about in the course of building their application. That's why we have a Factory here so that we can centralize that logic that says, you know, when you create a new Mini, you need to call SetName on that class in order for that class to be setup properly. So here we've done that, and then we can return that Mini and run it. Now, conversely, we have a little bit different implementation of IAuto in the BMW class. We'll open up the IAuto interface first, and see that it requires us to have a getter on a Name property, and have that SetName, as well as a TurnOn and TurnOff method. Now, if we look in the BMW class, this concrete class implements the interface, but it implements a little bit more functionality as well, including a non-default constructor that takes the name of the BMW it's creating as an argument, so that it doesn't require calling SetName. This is a good example of how we have two different concrete classes, both of which implement the same interface; however, they each need their own specific construction, and we can use our factories to centralize the logic of that construction. Now, we'll go up here to Settings, and we'll change our MiniCooperFactory to a BMWFactory, and go back, oh, we need to do a Build, just to push the config out to our Bin directory, and then we'll hop over to our command-line, Rerun our application, and sure enough, we're now getting a BMW back. We're getting a BMW M5, which is up and running. Now there are many ways that we might persist which Factory we want to instantiate, but configuration just happens to be one of those things I've run across many times in .NET development. Factory Method Pattern Notes As with most things in life, the Factory Method Pattern has some advantages and disadvantages. Advantages include the fact that we've been able now to eliminate any references to concrete classes at all for class instantiation. Both the factories, and the objects created by those factories are referenced by the application through interfaces. This is a great example of decoupling dependencies between classes. Also, specialized factories can be derived from parent concrete factories to provide even more specialized objects. Imagine if you will, a BMW Factory that knows how to create a basic car, but you have different Factories for different types of BMW cars that know how to put in say different engines, and different behaviors, and implementations of functionality. Also, we've centralized now the rules for object instantiation. We saw that our concrete classes that we're returning may have different requirements to be instantiated, and constructed, and initialized properly. Now, we've centralized all that logic. Now, there are some disadvantages associated with the pattern as well, including the fact that when we want to create a new car, now we must have a Factory to create it, in many cases. So, we may just have the need for a new concrete type, but in order to get that concrete type created, we also have to develop a Factory to support it, and that's a really good example of how the hierarchy of dependence between the concrete factories, and their classes that they instantiate, is tightly coupled. There's a pretty tight coupling between those concrete classes and the things that they produce. Abstract Factory Pattern Here we're going to go one level deeper with our factories, adding a bit more complexity with Abstract Factory, and this pattern, as described by the original book, Design Patterns by the Gang of Four, provides an interface just like we saw with Factory Method, but in this case our factories will know how to create different types of products. They may not just return one product type. They may in fact know how to create different types of products based on some input parameter to the Factory Method, or by some other means. This should make sense if you think about a factory responsible for creating database connections. We may have one factory of OleDb connections, another for SQL Server connections, and another for Oracle connections. Each one of those factories may in fact know how to create different types of connections based on the input parameters that it's been given to create the connection. Correspondingly, with our examples here, we may have a BMW Factory that knows how to create several different types of BMW cars. Therefore, some of the major bullets around the Abstract Factory Pattern are factories now can create different types of concrete objects. We can think of these as products. A Factory really represents a family of types of objects that it might create. And factories, this is just a side note, not particularly prescribed by the Abstract Factory Pattern, but a note here that factories may indeed have more than one Factory Method. Now, I mention that because that happens to be the technique that I've chosen to use in the sample code that we're about to see. That said, we could still have all our factories implement a single Factory Method, and parameterize that method somehow to help the Factory make the decision about what type of concrete object to create. Now here's our class model for Abstract Factory. We can see that we still have our IAutoFactory here, but now we have several different Operations. This again, is just my implementation. We could just have one Factory Method, but we have several. We have Create an Economy Car, Create a Luxury Car, and Create a Sports Car. We have correspondingly a MiniCooperFactory and a BMWFactory. These are concrete classes that know how to create IAutomobiles. IAutomobiles, same interface we've been dealing with so far. We can simply Turn them On, Turn them Off, and BMWFactories obviously are going to know how to create BMW vehicles, and the MiniCooperFactory will know how to create MiniCooper automobiles. Let's take a look at how this works in code. Demo: Abstract Factory Pattern Here's our Main entry point for our Abstract Factory implementation. We Load up our Factory via the interface. This is exactly how we loaded our Factory last time. We're doing it through configuration. Again, if we look up at Properties, we can see in our Settings that we've got our AutoFactory key, and we have the Value here of the type that we'd like to Load for that Factory. So that's how the factory's getting instantiated, just like last time. This time, we've got a little bit different implementation here, in that we have several different cars that we're creating, so we're going to call a SPORTS CAR, Turn it On and Off, a LUXURY CAR, and finally an ECONOMY CAR, Turning each of them On and Off. Let's go ahead and Run our application. I'll do a quick Build. Pop over to our command-line, and Run our Factory, Run our application. Remember it was set on Mini Cooper in our configurations, and we can see that we had several different types of Mini Coopers created. We had a Mini Cooper S created, and we also had a Mini Cooper with leather upholstery. Apparently, that's Mini Cooper's idea of a LUXURY CAR, and finally we had an ECONOMY CAR, just a plain, simple Mini Cooper. For those of the uninitiated, the S stands for SPORT in Mini Coopers, we'll see in our code here in just a moment. So we'll flip back over to our code, and let's have a look at what's going on. If we look at the interface definition for IAutoFactory, we see that we have these three methods. Now again, what we could do is simply have something like this, (Typing) and create some parameter that would help the Factory decide what type of car to make. That just so happens to not be our implementation here. So, we have this interface, let's take a look at how the MiniCooperFactory implements that interface. Well, it looks like we only have one MiniCooper object that we're working with. We can see that a new MiniCooper object is what's being created here, here, and here, and the difference in the IAutomobile that's being returned is simply that the Factory knows to call certain methods that tweak the options of the MiniCooper before it returns it back, adding the Luxury Package, and the Sport Package. And that's a little bit different than how the BMWFactory chose to implement, and if we look at the BMWFactory, we can see that if you Create a Sports Car at the BMWFactory, you're going to get a dedicated object, a BMWM3. If you Create a Luxury Car, you're going to get a dedicated object, a BMW740i, etc. And that means, if we look under Autos, we look under BMW, we have different types here for our different BMWs, and they all share a Base class, and under the Mini, we only have one MiniCooper class, yet we're still using a Factory that responds to the need to Create a Sports Car, Luxury Car, etc., based on configuration of that one MiniCooper concrete class. We can come up here, and change our Factory to now use the BMWFactory. Do a quick Build just to push that config file out. Hop over to our command-line, Run our app again, and we can see that our BMW is now being returned, our BMWFactory is being used, returning different types of BMWs. So two different approaches to how those factories, and the concrete classes are implemented, but all of the interfaces are being shared. Abstract Factory Pattern Notes Just a few notes about Abstract Factory. As with the Factory Method, we can add new factories and classes, concrete classes that those factories return, without breaking the Open/Closed Principle. Becomes a little bit harder when you choose the technique that I just chose where I have different methods per different type of car that you want to return that parameterized technique where we push in a parameter to our Factory Method, might make that a bit more extensible, and be a bit safer with the Open/Closed Principle. Again, we get to defer the decision about what classes get created to the factories themselves, and we localize all of the construction logic within those factories. And one note is that we can now use private, or even internal constructors, where the factory and the concrete classes are in the same assembly, and when we do this, when we put internal, or private constructors on those concrete classes that the factories return, we can absolutely guard against newing up the objects by some means other than the factory. Real World Examples Now, I'd like to share with you just a couple of real world examples of using factories, and I'll show you a little bit of code from the actual source of, and then we'll take a look inside the .NET Framework itself. So, we can start here with a Factory that we have in Keith Brown wrote a course that's available on _____ that you can go watch too, around implementing Undo in ASP.NET. He uses here an UndoProviderFactory. The Factory Method on this Factory is MakeUndoProvider. So we have this MakeUndoProvider, he returns back an IUndoProvider. An interesting note, he's using the Simple Factory that we discussed early on in this module, because there's no, he's not implementing an interface for his Factory. He's just got one UndoProviderFactory, and that seems to be working okay. Now, the way we configure in our website is using an IOC Container, such that we sort of mirror that technique that you saw, this sort of takes the place of that technique that you saw where we configure things using configuration files. Here we're getting an Undo Factory. He's newing up that Factory, and then down here, he's registering with the IOC Container to say, anytime anybody wants an IUndoProvider, send back that IUndoProvider from the Factory. So you got that Provider and it's sending it back here. And then later, we get to use in the actual code, this happens to be a Presenter class, an IUndoProvider. When I ask for this IUndoProvider from my IOC Container, it's provided to me from that Factory. So that's one example of a real world implementation of a Factory. We have others. And we'll take a look at our Object Browser here. Let's go to Object Browser, and I'll Search just within the .NET Framework4 for the word Factory, and it turns out that the .NET Framework itself has a ton of Factories in it. You can see all of these Factories. Let's go down to System.Data, and this is exactly what we were talking about earlier in one of our examples where we said there is a DbProviderFactory, and then there's subfactories to that, where we have an OdbcFactory, we have an OleDbFactory, Oracle, etc. So, Factories, very popular, very useful. And we can see that they're used in, no kidding, real world software as well. Summary And there are some other related patterns that you should be able to find, if not now, soon in the Pluralsight Patterns Library, the Singleton, Builder, which is a bit more complex construction model for Factories, Object Pool, and Prototype. These are all just creational patterns, ways to create objects. And we saw, and referenced a couple of ideas here in this module, including the NullObject, which you can learn about, and the Open/Closed Principle, also available as a module of content within the Library. As we saw, there are various levels of complexity and sophistication that we might want to bring to bear in our Factories, based on the different scenario that we need to support. In our toolbox is that very Simple Factory that we saw. Also, the formal Factory Method Pattern, which defines an interface for our factories themselves, and the subclasses are then created by the implementations of that factory creation method. And then Abstract Factory, which provides different factories that think in terms of families of objects, and can return multiple object types, concrete types that make sense for that particular factory. And just one last note is that it's very common for factories in .NET to take advantage of reflection so that they can return concrete objects without ever really needing to know their type. So that's a way to decouple the dependency between the concrete factory itself, and the objects that it's going to return. Thank you very much. I'm David Starr, and I hope to see you in class sometime soon. Flyweight Introduction Hi. My name is Niraj. In this module we'll walk through the Flyweight Pattern. Many people consider Flyweight to be a creational pattern, as it revolves around use of a Factory. But the major focus of the pattern is on structuring objects so that they can be shared across multiple contexts. This module will help you understand the Flyweight Pattern, showing you how you can leverage it across UI applications. Let's get started by looking at its intent. Intent All of us have written object-oriented programs. While object-oriented programming brings unprecedented flexibility, it also comes with a set of challenges. Those challenges pop up when we try to model everything as an object. Consider a Word document with all its characters stored as an object. Such programs would cause a great amount of runtime overhead. This is where Flyweight Pattern comes to rescue. It helps to reduce storage costs for programs having a large number of objects. It allows us to share objects across multiple contexts. And last, but very important aspect of the pattern is while sharing objects, we still retain the object-oriented granularity and flexibility. Let's look at a hypothetical example to understand things better. Demo: Motivating Example Consider an interior design application. While an interior design application can have a lot of elements, but this specific example, our focus is on Tiles. Tiles are broadly categorized into Ceramic, Stone, and Quarry. Tiles can be used across rooms, kitchens, bathrooms, or backyards, among others. Application allows picking your choice of Tile and applying to a selected area. Problem though is application creates an object per Tile. Imagine designing interiors using this application for large apartments, malls, theaters, etc. For instance, if a commercial establishment needs a million Tiles, application would end up creating a million objects. Let's take a look at the structure of the classes this application uses. Overall, the program is very much object oriented. It has a base interface called ITile, which contains Draw method. And there are classes implementing the base interface. For simplicity we'll assume two concrete classes, StoneTile and CeramicTile. Both classes have their own Brush, and also have coordinates to store Tiles Location. Draw method is overridden by both classes, and it uses the underlying Brush to provide Tiles look and feel. It is the Draw function that provides necessary object oriented flexibility, which we would like to retain at any cost. Let's take a closer look by digging into the code of the application. As you can see in this Visual Studio Solution, I've got two projects. The first one is the HouseInteriorApp, which is a Windows-based application, and I've got DomainModel, which is a C# class library. As we saw in the earlier slide, I've got a base interface, called as ITile. And this ITile interface has got a method called Draw, which takes a parameter g, which is of type System.Drawing.Graphics. CeramicTile is a class in here that implements the base interface ITile. CeramicTile has a member called paintBrush, and for simplicity, I've mapped CeramicTile to a Red color. Class also contains coordinates, which identifies Tiles location in a given area. Draw method leverages these members to Draw the tile using FillRectangle method of Graphics class. There is also a static member variable, called ObjectCounter, which I'm using to track the number of objects created for CeramicTile class. StoneTile is similar in structure to CeramicTile. It is mapped to a Blue color, and has the same member variables as CeramicTile. StoneTile too has an ObjectCounter to keep track of number of objects created. Coming to HouseInteriorApp project, it has a Windows form in it called TileDemo. Inside the form, I'm overriding OnPaint method to create 20 CeramicTiles and 20 StoneTiles. To keep things focused, I'm using System.Random class to supply coordinates to Tile objects at runtime. This will block Tiles at random locations, but in reality, you might specify an area, and depending on Tile dimensions, start plotting each Tile. There is also a status bar, which I am using to track the number of Tile objects created by the application. Let's try running the program. As you can see, the output doesn't quite distinguish between the CeramicTiles, and the StoneTiles. I mean the red ones, and the blue ones. This is intentional, as the core focus of the demo is on total number of Tile objects created by the application, which in this case happens to be 40. As discussed, this can be quite alarming for areas that require a huge number of Tiles. Let's take a look at an entire approach to this problem. Many developers, in order to reduce the number of objects, prefer creating a large class to carry out all the required operations. But such a class doesn't result in any space savings, and also makes the code base unmaintainable. As shown in the diagram here, the BigTileClass attempts the same. It uses collections to store Coordinates and paint Brushes, which hardly result in any space savings. Moreover, all the Draw code attempts are now present inside this large class, which would take _____ object level of granularity, making it very difficult to manage the code. Next, we will see how we can apply the Flyweight Pattern to this scenario to create shared objects, which would not only bring down the storage costs, but also help us retain the object oriented granularity and flexibility. Structure An ideal solution to our motivational example is to create shared tile objects. So instead of requiring a million objects, our job gets done with as few as possible. Now, let's see the structure of Flyweight Pattern that will help us achieve this. Important aspect of this structure is to distinguish between the extrinsicState and the intrinsicState. Identifying the states, and separating them is the key for creating shared objects. In the context of the pattern, the shared objects are also called as Flyweights. ExtrinsicState depends and varies with the Flyweight's context, hence it can't be stored inside the Flyweight, but has to be supplied as an event required. As you can see in this diagram, extrinsicState is applied to the Flyweight when the operation is invoked, but is not stored inside the Flyweight. Mapping this to our motivational example, the coordinates specifying the Tiles location are contextual, hence they can be moved out of the object and supplied when the Tile is being drawn. InstrinsicState on the other hand is stored inside the Flyweight. This state doesn't depend upon the context, and hence is shareable. Coming back to our motivational scenario, the paintBrush is a classic example of intrinsic state. PaintBrush used to Draw the Tile remains the same irrespective of Tiles location, hence a single paintBrush can be shared to draw Tiles of the same color. Great. So you see the way of reducing storage costs by moving the extrinsicState out of the object, and sharing the intrinsicState. But we still have a minor challenge at hand. How do we ensure that everyone across the system doesn't end up creating their own Flyweight? I mean, _____ a Tile object as a refactor to allow sharing, everyone would still carry their own local copy, and an answer to that is to use a FlyweightFactory. A FlyweightFactory creates and manages Flyweights. When a client sends a request for a Flyweight, the FlyweightFactory supplies an existing instance, or creates a new one, and adds it to the pool. A final word about the Unshared Flyweights. Like Flyweights, Unshared Flyweights too are created by the FlyweightFactory. This provides an informative face to the client to interact with, but as the name indicates, Unshared Flyweights are not shared, and they contain the entire state within themselves. An example could be a distinct tile with a distinct location. Next, we will see the consequences of applying the Flyweight Pattern. Consequence The most obvious consequence of applying Flyweight Pattern is replacing a given group of objects with few shared once. It's really important to understand from where the storage savings are derived. First, of course, is the reduced volume of instances. Once we reduce the instances, we automatically reduce the runtime overhead of a program. Second, the intrinsic state. This is a shared state, and hence you gain that much space per object, which you were losing earlier. Last, the extrinsic state. Calculating extrinsic state savings though can be a little tricky. By storing extrinsic state outside the object, you still end up paying for it. But instead, if we compute the extrinsic state, we can still have substantial space savings. Like in our example, there is no need for us to store the extrinsic state. We know the area. We know the Tile dimensions, and using those at runtime we can compute Tile coordinates. Finally, remember shared objects don't have identity. Once the Tiles are plotted, you can't refer them individually. So this is something you must consider for your application before using the Flyweight Pattern. Demo: Implementing the Pattern As you can see in the class diagram here, I've refactored the code off of our motivating example to apply Flyweight Pattern. Coordinates of the Tile, or so called extrinsic state, is computed, and supplied at runtime. While the intrinsic state, the paintBrush, is stored within the object. There is also a newly added class called TileFactory, which manages the pool of Flyweights. This factory is the single point of contact for any client trying to get hold of shared tiles. Other thing to notice, we still retain the object level of granularity that Draw coordinates are still separate, and clients that program to an interface instead of a specific implementation. Let's have a detailed look at the code. Here are our two projects, and I've modified them to incorporate Flyweight Pattern. Let's start with Tile classes. The extrinsic state here is commented, also to say, moved out of the class. Extrinsic state is now supplied at runtime, as in when it's required. The intrinsic state, on the other hand, is very much inside the class. Coming to TileFactory, it uses a Dictionary collection to manage the pool of shared Tiles. When a client sends a request key, it returns the corresponding Tile, and in case the Tile is not found, it creates a new Tile, and adds it to the pool. Client code too in the HouseInteriorApp project has undergone a couple of changes. First, it supplies random coordinates to Draw method instead of Tiles constructor. Second, it uses the FlyweightFactory to retrieve Tiles. Let's Run the program and see the output. As you can see, the output still isn't quite distinguished between the Stone Tiles and the Ceramic Tiles, but the striking difference is we have only 2 shared objects instead of 40 that we saw earlier. That's the power of Flyweight Pattern. Demo: Real World Example A great real world example to understand Flyweight is to look at string handling in .NET Framework. To reduce string storage costs, .NET runtime internally maintains a string pool. Let's take a look at the following piece of code. Here I have two strings, s1, and s2, and both are storing flyweight as their content. In the next line, we are trying to compare those two references. Now, before we run this simple program, remember, strings are reference types, and two references are only equal if they are referring to the same object. So, in this case, if I were to write a program to make string s2 refer to s1, then obviously the output of the program is expected to be true, which it is. But in this case, s1 and s2 are two separate strings, and hence the output should be false. Let's see. Surprisingly, the output is true! This is because .NET runtime in order to save space, internally manages a string pool, and replaces this individual string with a shared instance. Let's make example more interesting by accepting strings at runtime. So, I will make use of Console.ReadLine to accept a string at runtime, and assign it to s2. Let's Run the program, Input the same string Flyweight, and, and a surprise, the output it false! While .NET runtime by default doesn't replace runtime strings, which are instances, we can still check if your string is present inside the shared string pool by using string.Intern method, like this. Intern method is more like the FlyweightFactory we discussed earlier. It returns a reference to an existing string if it is part of the pool. So let's see what happens when we Run the program. Enter the same string, and finally we get the output as expected, both the references are equal. Cool! A couple of considerations pertaining to this real world example. First, space occupied by the intern strings is not released until the .NET runtime terminates. And second, a slight variation over the original pattern is to place a string inside the string pool a line was first created. Related Patterns Quite often you would find Flyweight Pattern being used with a set of related patterns? These related patterns happen to be Composite, Strategy, and State. Let's walk through these patterns quickly. Composite Pattern allows you to compose objects into restructures, thus making it easy to interact with object hierarchies. Leaf object of this hierarchies are often found to be Flyweights. Strategy allows you to encapsulate and interchange you algorithms. The Strategy objects which encapsulate the algorithm too can be implemented as Flyweights. Finally, the State Pattern helps you to alter the behavior of an object depending on its State. State Pattern does this by separating each branch of behavior into a class of its own. Objects of these branch classes are often reused via Flyweight Pattern. You can find more information on these patterns from Pluralsight's OnDemand! Pattern Library. Summary In this module, we learned how we can leverage the Flyweight Pattern to restructure objects, and share them for better program efficiency. We also saw how the pattern helped us retain the fine grained objects versus creating a monolithic large class. This is Niraj Bhatt, and thanks for watching this Flyweight Design Pattern module. Interpreter Pattern Introduction Hi! This is John Sonmez from Pluralsight, and in this module we are going to be talking about the Interpreter Design Pattern. The Interpreter Design Pattern is a different kind of design pattern. It doesn't fit in with a lot of the other design patterns, and a lot of people are confused by this. This is one of those patterns that's pretty easily overlooked, and people don't tend to really understand how it works. But, by the end of this module, my hope for you is that you will have a solid understanding of the Interpreter Pattern, and know exactly how you can both apply this, and implement this. Break Down So, let's start off by breaking down the Interpreter Pattern. Now, this is the formal definition given in the Design Patterns book by the Gang of Four. It is, given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Quite a mouthful here, but I think we can just break this down, and make this a little bit more simple. So, given some language, this could be any kind of language. A language is some structure that we use to communicate something. So, there're a lot of different types of languages. We have programming languages, we have written and speaking languages, and we have other languages that are composed of symbols, and signs that we use to communicate some information. So, given that we have this language, we need to define a representation for its grammar. So, defining a representation for the grammar of a language simply means that languages have some rules, and grammar is the rules for that language. For the English language we have quite a complex set of rules. For mathematical languages, those rules are a little bit more simple, but they can be fairly complex, depending on what kind of equation that you're creating, and equation is a type of a set of rules. So, all we're saying here is that whatever language we have, let's define the rules for it. Then, we're going to define an interpreter that uses that representation, so something that's going to use those rules to interpret the sentences in the language. So now we have this idea of a sentence, or some kind of statement, an atomic thing that you can communicate in the language, and we need to be able to break that piece down so that we can interpret it, and understand what does this sentence mean based on the grammatical rules for that language. So simply put, to implement this design pattern, we're going to identify a language, we're going to identify the rules for that language, then we're going to create something to interpret those rules, and make some comprehendible action, or function out of the sentence in that language. Bar Codes So there's actually a really good real world example of an interpreter, and that is a barcode scanner. Barcodes, or the barcode language, is a language that it's interpreted by a scanner, by the software net scanner that interprets these lines that you see on a lot of products that you buy in a store. And in this particular instance, we're going to look at the UPC, because there's lots of ways that you can have a barcode, but a barcode in general is going to meet the criteria, that we had talked about, about the Interpreter Pattern. First we said that we needed to identify a language. Second, we said that we needed to have some rules, or identify the grammar for that language. And third, we said we need an interpreter to be able to make sense of some sentences in that language, based on that grammar. So if you look at this picture of a barcode, you can see that first of all it has a language. The language are the bars. Second, it's got a grammar. You can see that there are some rules to how this barcode is arranged, and we'll get into some more specific rules for a UPC in a second here, but you can see even just a barcode itself has some very particular rules. And then third, we're going to have an interpreter. Our barcode scanner's going to interpret a barcode, which we can treat as a sentence in this language, and it's going to make sense of that. It's going to do something with that, and produce some kind of result. If we look at these bars, it doesn't make much sense to us, but we can interpret those bars to have some kind of result. How Bar Codes Work So let's take a look at an example of a more specific barcode, a UPC symbol. If you're not familiar with BNF notation, I'm showing you how a UPC symbol works in basic BNF notation, which is just a way of defining a grammar. And this is a great way to work in the Interpreter Pattern, because if you can define a grammar, then you can implement an interpreter for that grammar. It always helps to be able to define a grammar first. It's okay if you're not familiar with BNF. This example's pretty straightforward. I think you'll catch on pretty quickly. The first thing that we're doing here is we're saying a UPC is defined as a Manufacturer ID, followed by an Item Number, and a Check Digit. Then we define each one of those elements. So we say, Manufacturer ID is composed of six Digits. An Item Number is composed of five Digits. A Check Digit is just a single Digit. Then we define a Digit as a symbol from 0 to 9. So, you can see how this represents a set of rules that make up a language of UPC, and we can use that language to be able to mark products. When you buy something in the store, it has a UPC on it, and it's something that can be interpreted so that we can get some understanding from it. A UPC by itself has no meaning, but the interpreter, and this grammar give it meaning. So next time you go to the grocery store, and the clerk is scanning items that you bought, and is adding up your total based on that, you can think to yourself that that clerk, that store is using the Interpreter Pattern. A Challenge So I've actually got a challenge for you that can help you to understand the Interpreter Pattern better based on our barcoding. So, what I want you to do is to go ahead and try and make your own barcode interpreter. It's fairly simple as far as interpreters go. You're going to have a manufacturer ID. You're going to have a product code. And what I want you to do, based on that manufacturer ID, you can create a Manufacturer ID class, and a Product Code class, and you can populate those with the Digits, I want you to spit out a barcode. Just a numerical representation is fine. If you want to, you can try and draw the lines, that's even better, but the idea here is that you're going to create a barcode that has a check digit. And you can find out how to calculate the check digit on this link that I've put here on a Wikipedia article on Universal Product Code. But if you're curious, the way that that last digit in the barcode is determined, that check digit, is basically you add up all of the digits in odd positions; the 1, 3, 5, 7, 9, and 11. You take that number, multiply it by 3, then you add together all the digits in the even positions, and then you add those together, so that some of the even position digits, and the odd position ones that were multiplied by 3, then whatever result you get from there, you can figure out how much you need to get to the next multiple of 10. So, if you're at 105, for example, you need 5 more to get to 10, and that number is your check digit. So the idea of this exercise is just to get you used to defining something in BNF notation, or defining a grammar for something, and then implementing an interpreter for that grammar. This is one of those design patterns where it really helps to go ahead and try it out, and try to do this in order to understand it a little bit better. Sandwhich Demo Overview I've created a code example of an interpreter so that we can see how you might actually implement this in code. And in this case, I have already created this example. We're not going to type this out because there's a lot of typing to this, and I don't want to waste a lot of time having you watch me type. But I'm going to go over this, and we're going to learn exactly how an interpreter can be created, and we're going to see how we can use this interpreter. So, the idea of this example is that we want to create a sandwich builder. We want to create a sandwich language, and we want to be able to spit out the result of the instructions for building some kind of sandwich. So, I've put all of the code here in one file just for convenience in this case, because there's a lot of different classes and interfaces. So, before we get into the actual structure here, let's take a look at the BNF notation for this sandwich that we want to define. We're going to say that a sandwich is composed of a piece of bread, followed by a list of condiments, then the list of ingredients, then the list of condiments again, and then another piece of bread. And we can define what condiments are. And again, if you're not familiar with BNF notation, that's okay, it's pretty simple to understand once you start going with it, so let's take a look at condimentList. So condimentList is defined as, and when I put something in these brackets here, it means 0 or more, so, 0 or more condiments. The ingredientList is composed of 0 or more ingredients. Bread is defined as either whiteBread, or wheatBread. A condiment is defined as either a mayoCondiment, a mustardCondiment, or a ketchupCondiment. And an ingredient is defined as either a lettuceIngredient, tomatoIngredient, or chickenIngredient. So that's our language. It's slightly limited. We can't make the most delicious sandwiches with this limited set of condiments and ingredients, but this will work for our purpose here. And we can see that based on this language, there's only a finite number of possible sandwiches that we could construct if we said that we can't repeat any of the condiments or ingredients. So, let's take a look at how we actually implement this. Now, the first thing that I've done here is I've created this interface called Expression, and on this Expression we have a method called Interpret, and Interpret takes a Context. So the idea here is that everything that we're looking at, the sandwich, this bread, condimentList, all of these things are Expressions in this language. In a grammar, we have expressions that make it up. So, each expression should be able to be Interpreted. It must mean something. A sandwich itself is an Expression, so it must mean something. And really, in order to determine what the sandwich means, we need to know what bread means, and we need to know what condimentList means, and in order to know what condimentList means, we need to know what each condiment means. So each one of these things have to be interpreted. So, each Expression will implement this Expression interface, which gives it the ability to be Interpreted in a given Context, and in this purpose, we're just going to use the context for our output. Because as we're interpreting the sentence, we need to know where we are in the sentence, what's happened already in the sentence. In this case, it's going to be pretty simple, but we're just going to concatenate these ingredients together to make the sandwich. So let's look at our Sandwich class. Sandwich implements Expression. And Sandwich has a constructor. In this constructor it takes exactly what we had said in our BNF notation. It needs bread, condimentList, ingredientList, condimentList, and then bread. So, we'll go ahead and be able to Build our Sandwich, specifying all of those things. Then we have an Interpret method. In our Interpret method, we're taking in our Context, and you can see we're just adding to the output. The first thing we're going to do is we're going to make this pipe symbol, then we're going to tell the topBread to Interpret itself. Then we're going to do some more symbols here. We're going to tell the topCondiments to Interpret themselves, the ingredients to Interpret themselves, the bottomCondiments to Interpret themselves, and finally the bottomBread to Interpret itself. So, we can look at each one of those. So an IngredientList is an Expression. And an IngredientList is going to have a list of ingredients as its constructor. And when we want to interpret that IngredientList, given a Context, we need to go through each ingredient and Interpret that ingredient. Pretty straightforward so far. Now, I've defined an interface here called Ingredient, and it's an Expression. This is so that we could define what an Ingredient is. If you remember this BNF notation up here, we said that ingredientList is composed of ingredients. And we said that an ingredient is composed of these three possible ingredients. So, we're forming some rules by saying here that in order for you to be an ingredient, you have to implement this Ingredient interface. So, we have a tomatoIngredient, and the way that we Interpret this one is since it doesn't have any children, it can be Interpreted by itself. So we'll just take our Context, and we'll add to it the word Tomato. When we Interpret our LettuceIngredient, we'll add to it the word Lettuce. Chicken, same thing. Now we have a CondimentList, which is implemented exactly the same as the IngredientList. It's an Expression. And in order to evaluate, or Interpret our CondimentList, we have to Interpret each condiment in that list. So again, we have a Condiment, which is an Expression, and each Condiment implements that Condiment interface, so we have Mayo, and all it does is put Mayo into the output, Mustard puts Mustard, and so on and so forth. The same thing with Bread. Bread is a type of Expression, and you have WhiteBread, or WheatBread, and they put out White Bread or Wheat Bread. So now we have a grammar, we have a language defined, and we have these classes for this. So now we can actually Interpret any kind of sandwich that we can construct, because we are able to start at the top level. If we look at our Sandwich here, and we can Interpret the Sandwich by Interpreting each of the things that make up that Sandwich. So this is a lot easier, if you think about it, then trying to write this code on your own. If you are just trying to parse through a Sandwich, and figure out all of these things, you'd have to write a lot more code. This makes it a little bit simpler to understand. You can break things down into this BNF notation, and then from there you can Build an Interpreter just by interpreting these rules. So, we simply said for the Sandwich rule, since it has to have these things, we can create a constructor that has to have these things. For the condimentList, since it can take a list of condiments, we created a constructor for CondimentList that takes a list of condiments, and so on and so forth. We just followed the rules that we had setup ahead of time. Sandwhich Demo So now let's go ahead and test out our Sandwich Builder. So I'm going to go into our Main here, and I'm going to do a Console.ReadKey so that we can stop on our output here. And let's create a sandwich. So, I'm going to create a sandwich. I'm just going to do new Sandwich, and remember the Sandwich constructor is going to take Bread, CondimentList, IngredientList, CondimentList, and Bread. So, we'll go ahead and break this apart here, and the first thing that we're going to need is Bread, so let's do a new Bread. And you can see here we have the choice between WheatBread or WhiteBread. Let's go ahead and do WheatBread here. Then the next argument is a CondimentList, so we'll create a new CondimentList, and in this list we need a list of condiments, so we'll create a new List of Condiments here, and let's create some. So we'll do, let's put Mayo on, and then we'll put some Mustard on that side of the Bread. Then the next thing that we need here is an IngredientList. So we'll go ahead and do this one here. We'll do a new List of Ingredients, and then we'll define this list. We'll do new, we'll do Lettuce first, and then we'll put some Chicken on. Then the next thing that we need here is another CondimentList to go on the other side of the Bread, so we'll create our new List of Condiments. And inside here, let's just add some Ketchup, and then the last thing we need is another slice of Bread. Let's continue the WheatBread here. So we've defined our Sandwich here. And because we're using an Interpreter, we're defining our Sandwich already in this kind of what's known as an abstract syntax tree. We're not parsing anything. We could have defined some kind of language that defined how a sandwich should be created, or how the object tree should be created, but we're not doing that step here, because that's not part of the Interpreter Pattern. But you could definitely do that if you wanted to create a full DSL, or full domain-specific language. In this case, we're starting from, some of that might already be parsed. So, all we have to do to interpret this sandwich is call Interpret, and we pass in the Context. So, we'll just create a new Context here, and we'll go ahead and Run this, and what's going to happen is Sandwich Interpret is going to call each of its parts, and then call Interpret on them, so all the Expressions that make up that Sandwich, and then finally we'll hit some leaf nodes in our tree here, and those we'll just add to our Context. So let's go ahead and Run this, and you can see here we've ended up with a representation of a Sandwich. We've got our Wheat Bread, and we've got an arrow that indicates that our Mayo and Mustard should go on that side. Then we have Lettuce and Chicken. Then we have Ketchup that should go on the other side of the Wheat Bread. So that's the basic idea of the Interpreter Pattern, and we could construct a lot of different kinds of sandwiches using the set of rules, and we can very easily just interpret what that sandwich means just by calling Interpret on that root Sandwich object. Formal Definition The formal definition of the pattern that we have just seen, the Interpreter Pattern, you can see here in this UML diagram. It's not that complicated. The basic idea here is the same thing that we've seen in our demo code. So, we start off by having our Client. Our Client needs to create our Context, and it needs to use an Abstract Expression. That was our Expression interface. Now an Abstract Expression can either be a Terminal Expression, meaning that it ends, it doesn't have any children, or a Nonterminal Expression, meaning that it contains one, or more other Abstract Expressions that need to be Interpreted. So, the basic idea here is that you'll have an Interpret method, or some method on your Expression that allows it to be interpreted, and this is going to look very similar to the Composite Pattern. If you're familiar with the Composite Pattern, it's the same thing here. We're just applying the Composite Pattern to create an Interpreter. And a good guideline that you can use for determining when to use this Interpreter Pattern is when you have some kind of construction of something, and the construction of something is defined by some rules, and you have some derived meaning from the way something's constructed. So, in our example of the barcode, we had exactly that. We had our barcode. It was constructed of a set of rules, and there was some meaning to that. Same thing with our Sandwich. We had defined some rules for how to Build a Sandwich, how it should be Built, and we had an Interpretation of what that representation was, which gave us some instructions for building a Sandwich. Summary So that's the basics of the Interpreter Pattern. It's one of the more difficult patterns that few people really understand. So congratulate yourself that you now understand the Interpreter Pattern, and should be able to apply that pattern to your code. And it is one of those things that you're probably not going to use that often. It does have a very specific set of circumstances when you can use, but it is a great pattern that solves a very hard to solve problem when you apply it correctly. So in this module, we learned about the pattern itself. We broke it down to say that basically for an Interpreter Pattern, you need to have a language. You need to have a grammar, a set of rules for that language, and you need something to interpret that language to make sense of a sentence in that language. Then we looked at an example of the barcode, and if you are up for it, go ahead and try and do that challenge of creating your own barcode interpreter. Then we looked at a demonstration of this Sandwich class that you see here, where we had been able to create our language for defining a sandwich, and be able to interpret that sandwich that we had constructed. And finally, we took a look at the formal definition of the Interpreter. Iterator Pattern Introduction Hi. This is Steve Smith, and in this Pluralsight module, we're going to take a look at the Iterator Design Pattern. Let's start by considering the motivating example for why we need to have an Iterator Pattern. Imagine that you work with a number of different collection, or aggregate types, and you need to be able to traverse these different types of collections, preferably without knowing about their internal structures. You also don't want every collection to have to be bloated with an interface that allows you to traverse it. What the Iterator Pattern allows you to do is abstract away the actual iteration from the collection itself, giving you a way to access the collections members sequentially without violating its encapsulation, or SRP, the Single Responsibility Principle. Pattern Usage This graphic shows the results of a design pattern usage poll that I conducted in the summer of 2011. Now, the trailing drop off in numbers correlates to the order in which I listed the patterns, so you can't necessarily say that the one at the bottom is the least popular, it's just that many of the users that took the poll only answered a few of the questions toward the top, and then gave up. So, if you want to know which of these are the most popular, you really want to look at which ones have the widest bands for the Daily and the Regularly colors, which are in the far right of each column. If you look at the Iterator, which is J, you'll see that 80 for the responses for that particular pattern said they used it daily, and another 59 said that they use it regularly, with 62 saying they use it occasionally, which is pretty good. It's actually, I'm surprised that it's not the most used design pattern since it is built into the .NET Framework, and the audience that I was pointing this poll at, are mainly .NET developers through my network on Twitter. You can see though that there are 63 responses there that said they haven't used it at all, and another 28 that said they're not sure, or they don't even know what that pattern is. So, a significant number of people at least think that they're not using this pattern. I'm going to bet that once I show you how it's built into .NET, you'll agree that you do already use this pattern, assuming that you're already a practicing .NET developer. Without Iterators Now let's consider what would we have to do if we didn't have the Iterator support in .NET? So, just for a moment, forget about the built in support, and imagine that you need to traverse an array. That code is going to look something like this, and each time you need to pull the element of an array out, you would use an indexer into it. In this case, we have a C# syntax to use the square braces for that purpose. Now let's imagine that we have another collection type. We'll l say it's a super collection, and it exposes a method called Get that allows you to get the current item out of the collection. You can see the syntax for Get is different from the array indexer syntax. Now if we want to be able to work with different types of collections polymorphically, the question then is how can we abstract out this iteration in such a way that we can reuse that logic, and not have to have two different types of loops, and two different types of accessors for each, well, for two different types of collections. If we have N-different types of collections, we might have N-different ways to access them, and so the Iterator Design Pattern is designed to make it so that we can do this in a consistent fashion. Intent So the intent of the Iterator Pattern is simply to "provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation." This is taken directly from the Design Patterns book by the Gang of Four. Now, you can also say that the Iterator Pattern defines interfaces for both the aggregate and the iterator, and each of these must be implemented for every collection that is going to support the pattern. You may also refer to the iterator as a cursor. Applicability As with any design pattern, it's important to know when it's appropriate to use the pattern, and so the applicability of the Iterator Pattern suggests that you use it when you need to traverse a collection, and you want to abstract the collection iteration logic out, so that you're able to follow the Single Responsibility Principle, as well as the Don't Repeat Yourself, or DRY principle. You can learn more about both of these principles, by the way, in the Principles of Object Oriented Design course, also here on Pluralsight. You also don't wish to break the encapsulation and expose your collections' internal organization, or design, globally. That is, the iteration process should work the same for any calling method without having any knowledge of how the collection is organized internally. Let's consider the structure of the Iterator Pattern. The Client represents the calling code that wants to be able to iterate over a collection. The Client does not depend on the collections' implementation directly. Instead it only references interfaces. In this case there are two interfaces. There's an Aggregate interface, which simply exposes a createIterator method, and we'll see that this represents a Factory Method, and there's also the Iterator interface, which simply exposes a next method. Now, it may also expose additional methods depending on the implementation. Then for any given collection type, there will be that concrete collection type, and it will implement that createIterator method. There will also be a ConcreteIterator, and that concrete createIterator method will return a ConcreteIterator of a particular type for that collection. For example, if we see how it's used, each collection type requires two implementations. There's the Aggregate interface where it has to specify the createIterator method. Again, this is an Abstract Factory Pattern being used here. Then the Iterator interface must be implemented for each collection type as well. The Client retrieves the Iterator from the Aggregate, by calling its createIterator method. And then the client is able to traverse the collection by using that iterator. Iterators in C# Now I mentioned that .NET has great built-in support for Iterators, so let's talk about how this pattern translates into the .NET world, and also how C# influence some of these patterns in its keywords. First of all, the Aggregate interface that the collections expose is one that you've probably heard of. It's called IEnumerable, and in the Iterator interface that is used to actually iterate over the aggregates, or collection, is called IEnumerator. And so basically you have an IEnumerable that is able to give you an IEnumerator for each type of collection. Anywhere that we talk about an aggregate, you can substitute collection, and vice versa. Now this enables a C# language feature called foreach. Foreach operates on any type that implements IEnumerable, including basic arrays. This lets you do some much simpler code. Consider the two following examples. On the left, you can see the use of the foreach statement to go over a simple array of strings. On the right, you can see that this code is doing the exact same logic, but using the built-in GetEnumerator method, which is coming off of that IEnumerable interface, and then on the enumerator, which is the IEnumerator type, it's calling MoveNext, and then its referencing enumerator.Current to get the current value. When C# is compiled, essentially the code on the right is generated from the code on the left. Two other areas in which IEnumerable and IEnumerator play a big part in the latest versions of C# are the use of LINQ, or Language Integrated Query, which makes it very easy for you to filter, and sort, and select, and transform collections. It supports both the IEnumerable, as well as another interface called IQueryable, and then also the C# yield keyword is something it ties in very closely with IEnumerables, and in fact, you can create a simple method that returns an infinite number of enumerable items through the use of this yield keyword. Yield is beyond the scope of this particular presentation. I'll be using it a little bit in the demo, but if you want to learn more about it, I highly suggest that you check out the C# Fundamentals course available here also on Pluralsight On-Demand. Collaboration Let's look at how the different types collaborate when we are using the Iterator Design Pattern. First, you have a concrete Aggregate implementation, which is set up to return a specific concrete Iterator. The concrete Iterator implementation works with this particular Aggregate, or collection. The Client will access this Iterator, or enumerator, from the collection type, which is the enumerable type, by calling its GetEnumerator, or GetIterator method. When using a foreach, or LINQ, the enumerators never need to be referenced directly by our client code. Those details are abstracted by C# and its compiler. Consequences Using the Iterator Design Pattern yields a number of positive consequences. First, each Iterator implementation is able to use its own particular algorithm for traversing the collection. If we want to change the algorithm that's used, we can simply create a new iterator instance. Iterators also have the effect of simplifying the collection interface, because they reduce the number of methods that it needs to support. And then by separating the iteration from the aggregate itself, the collection no longer needs to be responsible for keeping track of what the currently selected item is in a particular iteration. Thus, each Iterator is able to maintain its own traversal state, and therefore multiple iterations of the same collection can take place simultaneously. Demo Now let's look at a demo and see how we can add the .NET iterator support to a custom collection type, and also examine how some of this code would work without the Iterator Design Pattern in place. For this demo, I'm going to create a simple tree data structure. It's going to be the DemoTree of T, so it'll work with any particular type that we want to store in it. And it's going to have a notion of a LeftChild and a RightChild, so it's a simple binary tree. Now, I've gone ahead and I've built this thing in a test-driven mode, so I've built-up a set of Tests, and these Tests do things like verify that when I create a new tree, that the value starts off null. If I create a tree, and I add a Value of 1 to it, I expect that I'm going to get a Value of 1 back from the root node. If I had a Value of 2, I expect that the LeftChild is going to get the Value 2. And then if I add a third Value, so I'm adding 1, then 2, then 3, I'm expecting now that the RightChild is going to be 3, and so on and so forth. So, the structure that this tree is going to get is going to look something like this. So, if I were to add 6 nodes to this tree, they would go in as the root node, followed by 2, followed by 3, followed by 4, followed by 5, followed by 6. Make sense? So now we want to be able to iterate over this tree, and this is where we're going to apply the Iterator Pattern. And so the first thing that I do in this example here, is I'm not using the Iterator Pattern, and I'm going to just create a method of my own called List. And let's find that here. So, here we go. I've got now a method here called ToList, and then I'm going to cheat a little bit, and I'm going to use a LINQ extension method called ToArray that going to take my List and convert it to an Array for me so I can Join it and get out this set of values. Now, my ToList method is doing what's called a depth-first search, so my assertion here is that it's going to ListValuesInDepthFirstOrder. When you talk about traversing a tree structure, you can typically do it, you can do it a number of different ways, but two that are very common are depth-first, or breadth-first. So depth-first traversal would go from 1 down to 2, down to 4, and then it would see that 4 has no children, so it would come back up to 2, and try the next child, and get 5, and then it would see 5 has no children, so it would come back up, come back up, go down to 3, go down to 6. So the order would be 1, 2, 4, 5, 3, 6. And you'll see that's the order that I'm asserting here, 1 2 4 5 3 6. Now if we look at that ToList method, its right here, you'll see that we simply Add the current Value. If the LeftChild is null we're going to go ahead and Add its ToList method. And if it's not null, if the RightChild is not null, then we're going to Add its ToList method. And so it's pretty simple to implement a depth-first traversal of a tree. The downside to this approach is that I've cluttered up my interface of my collection with this new method called ToList, and in fact this is going to get in the way of the existing ToList method that's available as an Extension method from LINQ, and what's more, I've had to implement all this code in my collection, making it now responsible for more things than just how to store its data. It now has to know how to iterate over itself, and list its data, and it's made an innate decision to do that in a depth-first fashion, and there's no way for me to change that now. If I decide that I really need a breadth-first traversal of the tree, I don't have any way to do that that doesn't require me to either take this list and reorganize it somehow, or actually go in here and change this code. So now I'm going to violate the Open/Closed Principle because my class is not open to extension without coming in and modifying it. And you can learn more about the OCP principle in my Principles of Object Oriented Design course. Okay, so that's our challenge, is we need to create an enumerator, and implement the IEnumerable interface for this DemoTree data type. And then the last thing I wanted to show before I switch into the code that implements the enumerator, is that I also have implemented serialization, and the nice thing about serializing something to XML is that XML is inherently a tree structure. So, you can see here, this is what our tree would look like in XML form, and you can see the root Value of 1. You can see that it has a LeftChild with a Value of 2. That one has a LeftChild with a Value of 4, and a RightChild with a Value of 5, etc. So, it provides a very simple and easy way for you to visualize a tree structure if you simply serialize it into an XML structure. So now let's look at what this looks like with the enumerator added to it, and the Iterator Pattern implemented. So now I've opened up the code that's in the final folder in the code examples that come with this course. And you can see that the DemoTree type now implements IEnumerable of T. And if we see what that means, we can scroll down here, and we'll see that there is currently a couple of new methods here. There's a public IEnumerable of T GetEnumerator, and I have it set up so that it's going to either return a BreadthFirstEnumerator, or just a standard DemoTreeEnumerator, and we'll look at those in just a moment. I added this property here that obviously is used in the GetEnumerator to determine which one we want, and then there's also here an IEnumerator interface being implemented. This is there for backward compatibility in any code that doesn't know about generic enumerators, it will call this one, and use the previous .NET 1.0 enumerator type. So you can see it's fairly straightforward to add the implementation of IEnumerable to an existing collection type. All you have to do is implement GetEnumerator, and technically you have to implement it twice, but the second one just returns the first one. And have it return your enumerator type. Now, normally you wouldn't have to even have an if statement in here, I just have that in place as part of this demo. But typically you would just return a particular enumerator. So now let's look at what that enumerator has to do. If we look at our DemoTreeEnumerator of T, which implements IEnumerator, we'll see that it has a few methods implemented. The first one is MoveNext, and the other one that it has to support that's public is the Reset method, and the Current method, and likewise this one also has an IEnumerator.Current that's there again for backward compatibility for things that don't know about generics. But the strongly typed generic T Current method will return back the strongly typed Value of the underlying collection. Now, I'm not going to make any claims that this is the best possible code that you could use to traverse a tree, but it does work, and all my tests still pass, so I've taken the code that we had built into the ToList method, and essentially converted it into something that can live in its own type. And so if we come in here, when you're using the Iterator Pattern, the assumption is that at the start you're pointing at something before the first node in the tree. And so you have to call MoveNext in order for you to be pointing at the first node. This will set Current to be the first item in the tree. And so whenever I command and Current is null, I call Reset, which is down here, it really just sets current to null again. And then I'm going to say current equals my tree. This tree was passed in in my constructor, and then assigned to a local instance _tree, and I returned true, saying I was successful at moving to the next element in the tree. Now if I have a LeftChild, and Current is not null, then I'm going to call TraverseLeft, and I'll return that result, and if I have a RightChild, I'll return TraverseRight; otherwise, I'll return TraverseUpAndRight. So let's look at each of those in order. When we TraverseLeft, I simply push Current onto a Stack, which is my breadcrumb type. You can see here it's a Stack of these trees. And then I say that Current equals the LeftChild, and I return true. I'm going to use that Stack when I have to go back up the tree. Now when we TraverseRight, we do pretty much the same thing, we just push something onto the Stack, and set Current to be the RightChild, and return true. When we don't have a Left or RightChild to traverse, then we go to TraverseUpAndRight. And in this case we are going to basically see if the Stack has anything on it, and if it does, we're going to set previous equal current, and then while true will continue popping items off the Stack, looking for a RightChild, because we know we've already gone down the left path. If we have a RightChild, then we will again push things up onto the Stack, set current to be the next non-null RightChild, and return true. So, a little bit of technical tree for traversal info here, but at the end of the day, it does the job, and goes through a depth-first traversal of our tree. So if we look at our Tests, Run the Tests, here's our old one that calls our ToList method that's still there. We have a new Test that says we're going to List the Values Depth First Order With our Enumerator, and to do that I'm going to get rid of that .ToList call, and I'm just going to use the .ToArray extension method. And the .ToArray extension method can be used with any IEnumerable type, and give me this valueString, and I'm expecting it once again to be 1 2 4 5 3 6, because that would be the depth-first way that we would go through this, 1 2 4 5 3 6. So if we Run this Test, we'll see that it passes. Now let's consider if we want to traverse the tree in a different fashion. I already talked about depth-first searching, but breadth-first is basically going one layer at a time, so we would start with layer 1, and next we would do layer 2 and 3, because they're on this layer of the tree, and then we would do 4, and then 5, and then 6, and go across until we had all the items that were at that level. Now, there are different times when you want to do a depth-first, or a breadth-first search, one that in particular is if you're writing a game, and you need the AI for the game to evaluate the different possible moves that it will make. It's better if it considers the moves it might make, followed by the moves you might make for each possible one of its valid moves, before it goes down, let's say, N-levels deep down just one path. If I do this, and then he does this, and then I do this, and then he does this, typically you only have a limited amount of time in order to do your processing as the AI for a game. It's better for you to evaluate, you know, maybe this item right over here wins the game for you. It would be better for you to quickly get to that item, than for you to go down 15 levels deep down the left side looking for all the possible moves. So, AI is one example where a breadth-first search makes more sense. So, when we Run it in the breadth-first manner, we have the exact same Test code here. The only thing we're going to change, we're going to set the Iterator to use the Breadth-First one with that property, and then we're going to Run it, and we expect now to get them in the same order that I numbered them, which is 1 through 6. And if we Run this Unit Test, we'll see that, yay, it works, 1 2 3 4 5 6, so let's look at how that breadth- first enumerator was implemented. It's essentially the same as the other one. It's the same interface. So, you can see that there is a MoveNext method that does most of the work. Everything else looks pretty much the same. The way that you can implement a breadth-first search is by having a collection of enumerators. And so we're actually going to use the Iterator Pattern inside of our Iterator to implement this particular algorithm. Now there's more than one way that you could skin this cat, but essentially what we're doing is here, is if we look back at our diagram, I'm going to have an Iterator of the first tier, and then I'm going to have another Iterator of the second tier, and the Iterator of the second tier is going to basically be number 1's children. So it's going to be 2 and then 3. The Iterator of the third tier is going to be 2's children, appended to 3's children. So that gives us the correct thing. Now the way we do that is we add the Iterators onto a Queue instead of a Stack this time. And so I've got a Queue here of enumerators, and when I go in here, in MoveNext, if current is null, we're going to set everything up, so we're going to set current to be the tree, and we're going to Enqueue up the current's Children.GetEnumerator. Now this Children method is something that I had to add to DemoTree because originally it just had a LeftChild and a RightChild. It didn't have anything I could enumerate, so what I did is I took advantage of that yield keyword and created a Children method, that allows me to yield back the LeftChild if it's not null, followed by yielding back the RightChild if it's not null, and then just breaking if I've already gone through those two items. So you see, this returns back an IEnumerable, and that IEnumerable will have 0, 1, or 2 items in it depending on how many child nodes this particular node has. The nice thing about using an IEnumerable here is that I can then keep that enumerator in this queue. And so at this point, I have queued up an enumerator of node 1's children, and so I have an enumerator that's pointing right here ready to MoveNext to get number 2, and then MoveNext again to get number 3. The next time somebody calls MoveNext on my tree, if I have an enumerator Count greater than 0, which I do, I'm going to Peek at it, I'm not going to Dequeue it, I'm just going to look at it, and I'm going to call its MoveNext, so I'm going to set the current tree value to be an enumerators Current item, so that means Current is now 2. And then I'm going to Enqueue up current's Children's enumerator, so that means I'm going to add 4 and 5 to my Queue. Now, notice I didn't Dequeue off that first enumerator, so I still have an enumerator of 2 3 in there, 1's children, and I've now queued up 2's children to it. And then I return true. Now when we loop through this one more time, again we're going to Peek, and we're going to get this same Iterator, 1's children, but now we're at this point, we were just passed 2, so when we call MoveNext, we're going to get back 3, and we're going to Queue up 3's children, so we're going to add to the Queue 3's children. And so our Queue now has 1's children, followed by 2's children, followed by 3's children, which is what we want. And then we're going to hit it one more time. We're going to Peek again at this enumerator, and we're going to call MoveNext, but MoveNext on 1's children is going to return false because it's at the end of its list. And so when it returns false, it gets Dequeued, and so now it's removed, and the only things that are left in the Queue are 2's children, which will 4 and 5, and 3's children, which will be 6. And you can do this obviously recursively as far as you want. Now, you'll end up with N-enumerators in your Queue, so there's a little bit of memory involved in this particular approach, but it is kind of an interesting way that you can use Iterators within an Iterator to iterate over a particular structure in a particular fashion, and so I thought that was interesting to share as part of this Iterator Design Pattern talk. Now again, you've got all this code here in the final bits inside the source code for the samples for this particular module. I encourage you to take a look at it, and see how it works. It is possible that this is not the most robust tree traversal code ever. There are, of course, tests that I have not yet written where they may fail. I'll leave that as an exercise for the student, but with that, I hope that this helps clarify how you can use an enumerator from your client code. A great way to show off how to use code is, I think, through the use of tests, and so you can see how I'm using it from these tests, and what I expect the results to be with each one of these different scenarios. So, if you're ever trying to learn yourself, I encourage you to try and learn by writing tests that show that what you expect to happen is in fact what you see happening as you go through the exercise. Related Patterns Alright, so we just saw a demo of how you can use the Iterator Pattern with a binary tree, and do both a depth-first, or a breadth-first traversal of that structure. And you can see that there are some related patterns to the Iterator Pattern. The first, and most obvious one is the Factory Pattern, because Iterators have to be created by a Factory method on the aggregate, and that Factory method can simply always return a particular Iterator, or it could have some logic in it that determines which type of Iterator it's going to return. Polymorphic Iterators for Factory methods often are configured to set up, and return the appropriate Iterator for the type that is being used. Another related pattern is the Composite. A tree, like the one I just showed you, is an example of a Composite Pattern, and you can usually use Iterators to recursively traverse such Composite structures. In my examples, I didn't actually use too much recursion, but you certainly could write an algorithm that would recursively traverse such a tree structure. You can learn more about both of these patterns in the Pattern Library. There are a number of different references that you can look to for more information on design patterns. The canonical reference is the Design Patterns book itself shown here. I also highly recommend Design Patterns in C# as another reference book, and my favorite design patterns book by far is Head First Design Patterns, which is one that is written in a totally novel, and unique way for a computer science book, so if you haven't checked out that book, I recommend it. There's some more online. There's the Wikipedia entry, of course. There's a great article on Code Project on the Iterator Design Pattern. There's some good coverage of how the Iterator is used in the .NET Framework today in this MSDN article, and also, I have a blog post where I've sort of rolled together a bunch of common design pattern resources, and you'll also find the results of that poll that I mentioned at the start of this module, at this URL here at the bottom. Summary So to summarize, the Iterator Pattern is useful because it separates the logic of iterating over a collection from that collection itself. This allows for common collection based operations, and ultimately things like LINQ to be used as a language feature. The collection itself has a simplified interface because it doesn't have to deal with the iteration methods, and furthermore this allows for multiple different types of iteration strategies to be implemented without having to modify the collection itself. Lastly, because the collection doesn't have to maintain its state with regard to how an object is iterating over it, this allows for multiple iterations to take place simultaneously without any of them stepping on one another. This does, of course, depend upon either the iterator getting a copy of the collection, when it starts off, or some kind of locking being in place so that the collection is not being modified. So, assuming that you have a read only collection, you can certainly have multiple iterations taking place over it; otherwise there are some additional considerations, just so you know. So this concludes our module on the Iterator Design Pattern. Thank you for listening. My name is Steve Smith. You can find me on line at my blog,, or on Twitter as Ardalis, and I hope to see you again real soon. Thanks! Lazy Load Pattern Introduction Hi. This is Steve Smith, and in this Design Patterns module we're going to examine the Lazy Load Pattern. The Lazy Load Pattern is generally used to increase the performance of an application by reducing the amount of work it needs to do, when that work is unnecessary. Let's get started! Motivating Example Let's consider the motivating example for the Lazy Load Pattern. You can think of this example as being the reason why this pattern exists, and the problem it is designed to solve. In this case, consider that you have an application where you work with objects that need to be loaded from a persistent store, such as a database. Now, you want to avoid loading portions of the object's state that you don't necessarily use, or need at this point in time in your application. The reason why you want to avoid it generally is to increase the performance of the app. This is especially important when you're talking about portions of state that require a separate request to fetch, and/or which are just simply expensive to retrieve from the storage. Ideally, you want the client code to be ignorant of the fact that the object is performing this lazy loading. The client code should assume that the object is a perfectly valid object that it can retrieve its state from. Now the Lazy Load Pattern describes several different strategies that can achieve these goals to a greater, or lesser extent. In particular, this last item where the client code may or may not have knowledge, this can vary to some extent depending on which strategy you choose, as we'll see in just a moment. Intent The intent of the Lazy Load Pattern is to interrupt an object's loading process for the moment, leaving a marker in the object structure so that if the data is needed, it can be loaded only when it is used. This is taken from Patterns of Enterprise Application Architecture by Martin Fowler. Martin Fowler also goes on to say, "As many people know, if you're lazy about doing things you'll win when it turns out you don't need to do them at all." This is basically the whole reason for the Lazy Load Pattern to exist. There are times when your application by default will load portions of an object state that aren't needed at that point in time when you're referencing that object. The Lazy Load Pattern allows you to easily take those pieces of state and avoid fetching them, but make it so that when they are needed, they're fetched automatically at that point in time. This also follows the acquire late, release early best practice of software development. There're several variants of the Lazy Load Pattern. These include lazy initialization, virtual proxy, value holder, and ghost, and we'll take a look at each of these in this module. Applicability Like most design patterns, the Lazy Load Pattern should only be applied when it's applicable. You don't want to add it to everything by default, because it adds some complexity to your design. So, specifically, you want to look to use the Lazy Load Pattern only when you have an object whose structure is such that it requires multiple calls in order to populate its data, and, in this case, where you're using the object, you don't need some of this extra data that is coming back. You can get by with just the state that the object has without some of these calls. You should only apply this design pattern as an optimization technique when you're tuning an application trying to improve its performance. Again, don't just apply it everywhere, because actually adding Lazy Load throughout your application can oftentimes hurt its performance because of something called ripple loading, which we'll see in just a few moments. Generally when you're optimizing your application for its data access using a technique like lazy loading, what you're trying to do is balance how many requests you're having to make to the data store with the amount of data that you need. Ideally, for something like a web application, you should have exactly one request to the data store to get all the data you need for a given web request. Although it's unlikely that you'll be able to achieve having just a single request for each page in your application, it is important that you try and minimize the number of requests. What you want to avoid is having to make many, many requests, especially when you're fetching a collection, for example, because this can have a dramatic negative impact on your application's performance. Lazy Initialization The first flavor, or technique of the Lazy Load Pattern that we're going to look at is called Lazy initialization. Now, the benefit of the lazy initialization approach is that it is very simple. All you need to do in order to implement this is have every property in your object checked to see whether or not its backing field has already been populated from the data store. If it's already been populated, then it simply returns that field. If not, then it goes ahead and calculates, or fetches that value, and then returns the field. Now one of the problems with this particular technique is that it violates the Don't Repeat Yourself Principle, which you can learn more about in the Principles of Object Oriented Design course on Pluralsight On-Demand. The reason for this is that you have to do the same check in each and every property that you need to Lazy Load in your object, and so obviously this can get rather tedious and repetitive. Another point with the lazy initialization technique is that even within the object itself, all access to the value should go through the property, not through the backing field. Unfortunately, there is not a way in C# to force a backing field to only be accessible via its property, but I will show a technique using a feature in .NET 4 called the Lazy T type that lets us get around this issue. If you're not using .NET 4, then this just requires some discipline in your coding practices to ensure that you always refer to this particular property through the property accessor, and not directly to the backing field. Now this also requires some knowledge on the part of the object as to whether or not the field has previously been calculated. Now for most types, if it's null, then we can assume it hasn't been populated, and if it has a value, then we can assume it has been populated. However, in some cases, null is a perfectly legal value, it might be the value that was fetched from the data store. So, in this case, what would have to happen if you were doing it yourself is that you would need to store some sort of a flag that specified whether or not the value had been loaded previously. And then check that flag, and populate it from the data store if the flag was false. If you use the Lazy T type, this again is not necessary, because the Lazy T type already implements this for you, but it's only available in .NET 4. Demo: Lazy Initialization Now let's look at a demo showing how we can achieve lazy loading using the lazy initialization technique. For these examples, I've created a small project, which I've called LazyLoad. You'll find this in the exercise files that you can download with this module on Pluralsight. I'm using nunit and I've installed it from the package manager here by just saying install package nunit, and when you do this, it's going to actually pull down nunit.exe, so what that means is that you can run the test that I'm going to show you on your machine, even if you don't have a plugin for Visual Studio, like I have, such as ReSharper. So, when I look at my Tests here in my TestFixture class, I can right click, and I can say Run Unit Tests, and they'll run in ReSharper's test runner. If you don't have ReSharper, however, what you can do is you can open up your Windows Explorer, and go into the Packages folder, which you'll find inside of the LazyLoad folder, and from within the Packages folder, you'll see here, this NUnit2.5 package. Under Tools, you can Run nunit.exe, and then you simply can go and Load after you create a Project. You can add the assembly that we're looking at, and in this case, we're looking at the LazyLoad assembly here. And you'll see all the Tests now that you can Run as well. So now let's look at how we're going to implement lazy loading. In this case, I have an Order class, I've called it OrderBad in this case, because this isn't the ideal way that I want to use this particular technique, but the key technique that's done with lazy initialization is shown here with the Customer property. As you can see, I have a private backing field of type Customer, and I have a public Customer property, and this public Customer property in its getter is going to check to see whether or not the backing field is null, and if it is null, then it's going to go ahead and instantiate the Customer. Now, at this particular line, right here, this is where you would typically go to the database. Now it might be that when you new up a Customer, it automatically fetches its state from the database using an Active Record Pattern, or more likely, you'll have some sort of a repository it's involved that you might pass through into the Order, or into some kind of factory that creates it. There're a number of different techniques there, but the important point to note is that the instantiation, and access to the database only occurs here when something tries to reference the Customer's Get method, and it has not previously been initialized. Now one problem with this is that it's not thread safe, so what that means is that if a particular thread comes in and asks for the Customer, and reaches this line, and says, okay, I have the Customer, and the backing field is null, and then another thread at that same moment comes in here and does the same thing, you might end up with multiple threads here doing your load logic. Now, if all it's doing is fetching a row from the database, and the two rows happen to be the same, it's probably not the end of the world that two threads are fetching the same row from the database, it's just slightly inefficient, but it is something that you need to recognize, and it can be a problem in some multi-threaded applications. It's more of a problem if one of them is going to then persist the Customer back to the store, or if both of them try and persist to the store, because one of them might overwrite the other's results. Now, as I mentioned, when you're using the lazy initialization technique, you need to make sure that even within your class, you always go through the public accessor here, capital C Customer. If you instead use the _customer type here, it's likely that this will cause problems. For example, if nothing has referenced the Customer's public accessor yet, _customer is still going to be null, and so as you see here I've got a comment that says this probably results in a NullReferenceException. And if we look at my Test here, all I'm going to do is with this BadOrder, I'm going to instantiate the Order. I'm going to call PrintLabel. PrintLabel is this method here, and the first thing it's going to do is call _customer. So if I throw a breakpoint there, and we Debug this test, (Typing) we'll see that we stop here on this line with the PrintLabel, and if we do a Step Over on this, (Typing) you'll see that we get a NullReferenceException, and the reason is that _customer is null. Now if we look at how we would do this in a better way, we'll look at OrderGood, and the only difference that we're doing here is we've made it so that now we're going to refer to Customer using its public accessor in the PrintLabel method, and everywhere else in this object as well. And so what this will do is when we Run the Good one, you Run it's Unit Tests, and we'll see that with the GoodOrder we're green, right, so we've done it correctly. Now the other thing we can note, if we look at this, is when we come in to OrderShould here with the GoodOrder, when we first instantiate Order, we don't want it to talk to the database, and get the Customer. We only want it to do it when it needs it, which is going to be here, when we do PrintLabel. So, again, if we Debug into this test, we're going to see, let's look at this Output Window down here at the bottom. When we now Step Over, and I'm going to have to do it using the Window, because I can't use F10 while I'm recording, you see at this point we get Initializing Customer. So, when we call PrintLabel, that's when Initializing Customer occurred. Alright, and that's important because we didn't do it when we instantiated the actual object, we only did it the first time we needed it, which was on PrintLabel. Now the important thing about how this lazy initialization works is that we only fetch the Customer the first time. We aren't going and fetching it each time that something is referencing this getter. So to show that, we'll go back to our Test, and we're going to go ahead and Debug into it. So we'll Debug the Unit Test, and we're going to use the Output Window again to show us when we're actually Initializing the Customer. So, watch the Output here as we Step Over. You can see we Initialized the Customer. Now if we roll back to that same line, we're going to run this result order PrintLabel again, and Step again, you'll see we've now Stepped past it, but we did not Initialize the Customer a second time. So the call to Initialize that type is only done the first time it's requested. Now let's look at how we would use the Lazy T type. So if we look at OrderLazy, you can see that there's a new type in .NET 4 that's called Lazy of T. In this case, the T that we're going to use, the type, is the Customer type, and what we're going to do is we're going to still give the same public signature, so we're still going to have a public Customer, but the backing field is going to change. So now instead of using a private Customer, we're going to use a private Lazy of Customer, and name it a customerInitializer, and we're going to set up this Lazy type in our constructor. So, in the constructor we're going to initialize that customerInitializer. We're going to set it to be a new Lazy Customer, and we're going to pass in whatever it is that is required to initialize this value, and we're going to do that with a lambda expression here. Now, in this case again, we're just newing up the Customer, but if you were doing some loading from a data store, you would do that at this point in time. Now, when we call PrintLabel, we can still refer to Customer through its accessor, just like we did before, but it's also okay for us to access the backing field, and refer to its .Value. Now its .Value is of type Customer, and then we can refer to its properties, its Address, its CompanyName, things like that. So either approach is now acceptable, and we're not going to have to worry about getting an NullReferenceException when we hit this. Now the other thing that we can do is we can set whether or not we care about thread safety when we initialize this Lazy type, so one of the overloads here is simply to say, is thread safe, and we can set that here to false if we know that we're only going to be accessing this from a single thread. This will give us a slight performance increase. Now, by default, it's true. So if we leave it off, that's going to give us a thread safe initializer that we're guaranteed will only be done by a single thread in a multi-threaded application. If we go and we Run our Test for PrintLabelLazy, what we're expecting is to get back this result, but more importantly we're expecting to only initialize customer when we call PrintLabel, just like we saw before, so we'll put a breakpoint here, and Debug into this Test. And we'll clear this out, and Step Over again, and you can see that we Initialized the Customer at that point. So it's fairly simple to use the Lazy T type, and it can be done as a backing field here, which makes it so that it's transparent to the end user. They can still refer to the object with an irregular type. You could also use the Lazy T type as your property, at which point you could even just use an auto property, and not have to have a backing field. The downside to that is that you're calling types, your client code, would have to refer to this properties .Value instead of simply referring to it as the type itself. One last thing I thought I should show you is a sequence diagram for how the Lazy T type works with loading up the Customer. When we load up the OrderLazy type, and in its constructor we new up a Lazy Customer, you can see that this is what the sequence diagram looks like. So coming in from my unit test of this OrderShould PrintLabel, we're going to create the OrderLazy type. Within its constructor, we're going to new up a Lazy Customer, and in here you can see we're going to pass in a lambda that news up a Customer. And so this, as you can see, is noted as a Deferred Call, so it does not happen at this point in time. But when it does, it's going to create the Customer and new it up. Now, if it were actually going to the database, you can imagine there'd be another database line here, and another call here, going out to the database, and coming back with the state from the data store. But, again, this is Deferred, and when we get down here to this PrintLabel, the sequence diagram is just showing PrintLabel running and returning, but actually it's at this point in time that this Deferred Call occurs. So, you can think of this as taking place right here at this point in time within the sequence diagram. Virtual Proxy Now let's talk about another way of achieving a Lazy Load Pattern called the virtual proxy. Now Proxy is actually another design pattern in its own right. So, essentially the proxy looks like the real object, but controls access to it, and in the case of the virtual proxy for lazy loading, what it's going to do is it's going to look like the actual object, but it's not going to have fully loaded its state, and any time you go and make a request to one of its properties, it's going to go ahead and fetch it from the underlying object, or data store as needed, achieving the lazy loading. And you can learn more about the Proxy Design Pattern in general, since it has use cases beyond lazy loading, in the Pattern Library. One of the downsides to the virtual proxy technique is that it can introduce identity problems within your application. What that means is that if you try and compare two different objects of what you think are the same type, but one of them happens to be a proxy, and the other one happens to be the actual object, you can get in a case where you incorrectly don't see the two as equal, even though they happen to be representing the same conceptual object in your system. This recommended way to alleviate this problem is to override equality, which is to say the Equals, and GetHashCode methods of your proxy. The other problem with virtual proxies is that you tend to have to generate a lot of them. You might have to have one for every different object that requires any kind of lazy loading, and so this can oftentimes expand to include many different objects in your system. Now, if you're using an Object Relational Mapper, or an ORM tool, these will oftentimes create what's called dynamic proxies, which are proxies that are generated at runtime. They don't actually exist anywhere at compile time, and these are used to represent entities in a tool like nHibernate, or Entity Framework, which supports some lazy loading intrinsically. So, that eliminates some of the issue of having to create a bunch of these things by hand. Now, if we consider the structure of the virtual proxy, it looks like this. You have a Client, which is the code that's using your object, and it refers to your object, which in this case is the Subject. Now it might refer to it by an interface, or more likely it's going to refer to it by its type, which we can consider to be the Base class. And then we have both the RealSubject, and the Proxy, both inheriting from this interface. Now, if the Subject is simply the type itself, let's say it's the OrderObject, then the Proxy would just inherit from the OrderObject, and we wouldn't actually have a separate interface for an IOrder, or something like that. But in either case, the Proxy is of the same type as the Real object, and so through polymorphism, they can be used interchangeably. Demo: Virtual Proxy Now let's look at a demo showing how we would implement a virtual proxy in order to achieve lazy loading. For this example of showing how a virtual proxy can be used to implement the Lazy Load Design Pattern, we're going to go back and use our Order type, just like we did in the lazy initialization, but we've made a few small changes. First of all, we've created a new property called Id, which is going to be used to refer to the identity of a particular object in our system. We've also implemented GetHashCode, and are simply returning the Id here, and we'll see that this gets to be important when we're doing equality's checks on the order. Now, in order to use a proxy, typically you need to have some kind of a factory, or repository, or something that gives you instances of your type. If your code is just newing up the order directly, then there's no opportunity for the Proxy to be intercepted, and given in place of the type itself. So, in this case, I've created a very simple OrderFactory, which is able to create orders from an Id, and what it does is, although it's returning back an Order, it actually returns back an OrderProxy. Now if we look at the OrderProxy type, you can see that it has a Customer that it's overriding, so if we note one important feature of Order, the Customer property here is virtual, so we'll able to override it. In the proxy, what we're going to do is check to see if the base Customer is null, and if it is we're going to go ahead and return a new Customer. This is our initialization occurring at this point. And then in either case, we'll return base.Customer. Now you can see here, we've also overridden Equals on the proxy. This allows us to take an OrderProxy, and compare it with an Order, and as long as both of them have the same Id, we're going to treat them as equal. If you don't do this, you can get into the identity problems that I eluded to in the PowerPoint portion of this module. And we've also implemented GetHashCode by simply returning base.GetHashCode. So, really this is superfluous. Now, if we Run our Tests, we can see that when we call this, we're able to get our Order from the Factory, and verify that our Order Id matches. So we'll go ahead and Debug into this Test. (Typing) And we'll clear this, and you can see, we'll see when the Customer initializes. So we'll Debug, Step Over, and our Assertion did not fail, so this passed. And now when we do the PrintLabel, just as before, with lazy initialization, this should cause the Customer to be Initialized, so we're going to Step Over, and you see here in our Output Window we get the Initializing Customer at this point, as expected. And finally, we'll just go ahead and continue, and we'll see that the Test did in fact pass. So the key thing with the proxy is that we need to be able to establish some way of implementing equality so that it works whether it's a proxy, or the actual object itself. Another key factor for the proxy is that it needs to be able to override those properties that you want to LazyLoad, so they need to be marked as virtual, and you'll see if you're using an ORM Framework, like Entity Framework, or nHibernate, they also have a requirement that the entities, or domain types that they are lazy loading need to have virtual properties in order for them to do their dynamic proxies. And then finally you need to have a way to get your types that does not allow your client code to simply initialize the Order itself. You need to have some sort of a factory, or repository, or something that issues back Orders, but is able to replace them with proxies. Proxy Consequences With the virtual proxy, there are a few different consequences. You need to be able to manage identity, which means overriding Equality and GetHashCode. It also requires your objects have some type of identity separate from their actual object instance state. Typically, this is their primary key in their data store, such as an Id property. You also need to create many of these virtual properties, or virtual proxies, one for every class that needs to have some lazy loading implemented for it. One of the things that is interesting to note is that the virtual proxy is very appropriate for use with collections. The reason for this is because these problems with identity, and with having to create many, many different proxies, don't tend to present themselves with collections. Collections are value objects. They don't have an identity intrinsic to themselves. There're not very many collections typically in a new application relative to how many objects there are, and oftentimes collections are the very things that give you the most bang for your buck when it comes to optimizing with lazy loading. So, oftentimes virtual proxies make a lot of sense, specifically for collection types on your objects. For instance, if you have a Customer, it might make sense to have a virtual proxy for their List of Orders, because that List could be quite long, and oftentimes you might need to reference Customer information without referring to their Order collection. And so, having that loaded lazily would make a lot of sense. Value Holder The third lazy loading technique that we're going to consider is called the value holder. Now the value holder gives up some of the encapsulation benefits that we've seen, and it provides lazy loading, but the client knows about this lazy loading functionality. The reason is that the calling code knows that it's working with a Value Holder type, it's not actually working with the underlying type that it expects. Now, for Value Holder's pattern to be achieved, you actually have to create several new types. These include the ValueHolder type itself, the IValueLoader, and potentially some Factory, or Mapper classes. Now the way this works is the ValueHolder uses the IValueLoader through a Strategy Pattern to load the value when it's first accessed. The ValueHolder, and the IValueLoader are reusable, so you don't have to create these for every different object that you're going to LazyLoad, but you do have to create them once for your application. Now the ValueHolder approach is actually very similar to the Lazy T object that's built-in to .NET 4 that we already looked at. You can think of the Lazy T type as being the ValueHolder, and the IValueLoader type is not really used by the Lazy T type because it uses a lambda expression instead. So, instead of passing in an IValueLoader implementation that has code in it for loading up that Value, we pass in a lambda that knows how to load up that Value. It's still an implementation of the Strategy Pattern, but it's an implementation that uses a lambda expression instead of a separate type. Demo: Value Holder Now let's look at a demo of how we would implement the Value Holder technique to achieve lazy loading in our application. For this example, we're going to go ahead and use an Order type once more, but in this case, we're going to reference a collection as the property that we want to LazyLoad. This is going to be a List of OrderItems that are related to this particular Order, and we're going to reference this List through this public property here, and the backing field for our property is going to be of type ValueHolder of T. Now in the actual code that's presented in the Martin Fowler book, Patterns of Enterprise Application Architecture, that book predated the implementation of generics, and so it used an object type, and there was a lot of casting involved. With generics, we can make this a little bit simpler, but as I already noted with the Lazy T type that we saw with lazy initialization, we can pretty much implement this whole pattern using Lazy of T, rather than using a ValueHolder, and a separate IValueLoader interface that implements this Load method. So, if you're using .NET 3.5, or earlier, this ValueHolder technique is valuable, but if you're using .NET 4, or later, you're probably better off to simply use the Lazy T type that I showed in the previous demo. Now, when you look at the ValueHolder type shown here, you can see it's generic. It works for any given type, and it knows about an IValueLoader of that type. It simply has a Load method that is able to Load that type. The IValueLoader is injected through the constructor. This is the Strategy Pattern. You can learn more about the Strategy Pattern in the Design Pattern's Library. And then it simply has a Value property of that type that you can refer to, and this familiar if check to see whether or not the item is null is then applied, and only on the first access will that value get loaded using the loader that was injected. So, if we look at the implementation of our loader here, we're going to simply call for a given orderId, we're going to return an empty new List of OrderItems. This is just demo code. Really, at this point you'd be fetching these items from the database. We're going to represent that with this Debug Print to say we're fetching the items. And when we go into our Test, we're going to expect that we can take our OrderFactory and Create our Order, and then we're going to Assert that the orderId is the same here. That's just to make sure everything is copasetic with our type, and more importantly we want to verify that at this point in time, we have not yet triggered the database call, but at this point in time we will trigger that call. So, if we Run this Test and Debug into it, it'll Build. We can clear our Output Window here. We can see we got through our Assert, so that passed, and when we Step Over this line here, we're going to see that we're now Fetching OrderItems from the Database. And we can finish the Test, and see that the items.Count is in fact going to be 0 here with our ValueHolder, it should not load until referenced. Now the reason that we're using the OrderFactory here is because we're setting the way that the ValueHolder is going to work in the factory. So, this is simply to make it so that the Order doesn't have knowledge of how it's loaded. It's up to you whether or not that's important in your design, so in this case, I've abstracted a way how the value gets populated, so that it's not held within Order itself. If we look back at the previous example using the Lazy of T, you can see that I baked that knowledge directly into the type, so within the Order type it knows how to new up a Customer, and in the case of fetching it from a database, it would know how to fetch it from a database at this point in time. A somewhat better solution in terms of Separation of Concerns, and the Single Responsibility Principle, is to have this factory responsible for specifying how, in fact, the Order is going to populate it's OrderItems, and in this case it's using this new OrderItemLoader. This whole bit could also be done using an IOC container, where you would inject that stuff in based on the types that you had setup in your IOC container's registry. There's another module on Pluralsight, actually a whole course on IOC containers that goes into more detail on how you might do this, but essentially instead of hardcoding in these new types within IOrderFactory, the IOC container is basically a factory on steroids, is how I like to think of it, so you can use your IOC container instead of a particular factory that you actually have to write, and have it specify exactly how, and which types are going to be used to fetch the actual underlying values for your Lazy Loaded types. So key things with the ValueHolder are that you need to have a ValueHolder type. It's going to be reusable. It can be generic if you're using a .NET version that supports generics, and you can just take this exact code here and use it in your applications today. You'll need an IValueLoader interface as well. It's very simple and just has a Load method. And then you'll need to implement this for each type that you need to Load. So, you'll have an OrderItemLoader that implements IValueLoader, and this is where you'll actually put in your logic for fetching from the database. Once you have those three things, you need to simply specify either in your Order itself, or in the Order's Factory the fact that you want to use the ValueHolder with this particular Item Loader passed into it. That's it, that's the ValueHolder technique for using lazy loading. Ghosts Now the fourth and final technique that we're going to talk about for lazy loading has kind of a cool name, they're called Ghosts, or Ghost objects, and it's kind of appropriate since I'm recording this the day before Halloween, that we're going to be talking about these Ghosts. Now, a Ghost is simply a real object, but it's only in a partial state. So, in this case, we're talking about objects that are responsible for managing their own state, and one of the benefits of this particular technique is that it can do things a little more chunkily instead of chattily. What I mean by that is that while initially the Ghost only knows about its ID, and so it's very lightweight, what it'll do is, as soon as you access any of its properties, the Ghost class is going to go ahead and load all of its state from persistence. So, in a number of different scenarios, this is preferable to having something where every single property loads itself, because you can do all of this in one hit to the database instead of lots of small hits, which is sort of death by a thousand cuts when it comes to your application's performance. What this means is that the object is essentially its own virtual proxy, and so this eliminates some of the identity concerns that the virtual proxy solution had. However, it does violate the Single Responsibility Principle again, because now this object is responsible for all the things it's normally responsible for, and this lazy loading of its state from persistence. Demo: Ghosts So, now let's look at a quick demo of how we would implement lazy loading using Ghost objects. To show how you can use Ghosts to implement lazy loading, we're going to go back and again refer to an Order type. In this case, our Order is inheriting from a DomainObject type that's going to implement some of this Ghost behavior for us. So, we're going to have a few different types of properties. We're going to have a simple string called ShipMethod, and the ShipMethod we'll see is just something like FEDEX, or UPS, or something like that. Then we're going to again have our favorite property called Customer, and we're also going to have our property of a collection type, in this case an enumerable of OrderItems, and we'll see how each of these gets referred to. Now, when implementing the Ghost Design Pattern for lazy loading, every one of your properties needs to call this Load method on its getter, or setter. Now, if you're using some sort of aspect oriented programming, this is an ideal candidate for that, because you can easily weave this into your code after you compile it by using an AOP Framework to do that. However, if you're not, then it's simply something that you need to add by hand to every single getter and setter. Now, this Load method is implemented in the base class which is this DomainObject we'll look at in just a second. Then, the other thing that you need to do after you've got your properties here, we'll just minimize those for a moment, is you need to override a couple of methods. Now, the first one is this DoLoadLine, and what this does is loads up some of the data for the Load method, so when you call Load, it's ultimately going to do some other stuff, and then implement the actual loading of this particular object using the contents of this method. And typically what you'll pass in is a dataRow from your database, so if you're using a SqlDataReader, this could be a dataRow from a DataReader, or it could be any other sort of object collection, or DTO, Data Type Object, that's holding the data for your object. Then the GetDataRow method here, this is the one that actually simulates fetching a dataRow via a DataReader, so you could pretend that we'd be doing some sort of data access here. In this case, I'm just creating an ArrayList, and the ArrayList is there to represent my dataRow, and I'm filling it in with some hardcoded values here for test purposes. So, I've got FEDEX, I've got the Customer Id that we're going to use to fetch the Customer property, and we're not actually going to populate anything from the OrderItems at this time, but we'll see that that's being handled up here with this Lazy T type that's going to use my OrderItemRepository to list those Items. So now let's look at DomainObject looks like. This DomainObject is something that you would use throughout your application, and so you would typically have many different types in your app that all inherited from DomainObject, and implemented this lazy loading, and each of them were Ghosts objects at that point. Now, every one of these has a Status that's used internally. It's called LoadStatus, and if we look at this, it's simply an enumeration that states whether or not this object is still in Ghost state, whether it's in the process of Loading, or it's Loaded, in which case we know it's populated its state from persistence. There's a method called IsGhost, and a method called IsLoaded, that simply check the Status using enumeration. We have methods to say whether or not we want to Market as being Loading or Loaded, and again, these just set that LoadStatus for us. And then we have the Load method. This is what's being called by all of our property gets and sets, and what it does is if we're not a Ghost, which means we've already been populated, or we're in the process of populating, we're going to just return, and then otherwise we're going to go ahead and load up our data, and so this is the line that's going to actually fetch the data, but the abstract DomainObject class doesn't do it itself, it's going to call the GetDataRow method, and GetDataRow is actually this abstract method down here that the actual implementation is going to implement. So our Order class is going to implement this. Once we have that data, we're going to call LoadLine to populate the actual properties from that data. So there's one call to get the data, and another call to map that data back to our object. Now, ideally you can separate out your persistence and mapping to separate classes, and if you want to see how you can do that, there's a few pages on that in the Patterns of Enterprise Application Architecture book that I would recommend you check out, but in the time available for this particular module, we're going to keep it simple, and we're going to just do it all inside of our Order class as I showed you. Now the LoadLine method, as well as the Load method, are both making use of another design pattern called the Template Method Pattern. You can learn more about that pattern as well in the Pattern Library, but what Template Method does is it specifies a template, and then it leaves in some spots where the underlying type can override how this particular template behaves. So, in this case, the Template Method is Load, and the part that you, as the class that's overriding this can change the behavior, is you get to implement GetDataRow. And the LoadLine method, this is the Template. The thing that you, the actual implementer of the type get to do is you get to implement DoLoadLine, and so you can see that the two abstract methods here, DoLoadLine and GetDataRow, and how those work with these two Template Methods. So, in our Order, when we go to fetch the data, this would go out, call SQL Database, fetch back a DataReader, get a dataRow for that particular Order, and spit that back, and then our DoLoadLine would take in that dataRow from that DataReader, and it would set our properties. So, in the case of the ShipMethod property, we are simply going to set it to the string value, so a simple, basic type. In the case of the Customer, we're going to set this to be a new Customer, and our Customer is also going to be a Ghost type. So, when we create a new Customer and pass it in this Id, which is going to be this 123 in this case, we're not actually going to get a fully loaded Customer, we're going to get a Ghost Customer type, and that's because the Customer is also going to be inheriting from DomainObject and following this same pattern. And finally for the OrderItems, we're not actually going to get back OrderItems either. What's going to happen is we're going to set the backing field of OrderItems to be this Lazy type that then can go out to the OrderItemRepository and get all those values. If we look at our OrderItemRepository, we're going to do a Debug Print to say that we're fetching those items. We're going to just create three new items and return them. So this is where we would actually talk to the database. So now if we look at a Test for this, we're going to do a few different things. First, we're going to create a TestOrderWrapper type, and this is just something that we're going to create so that we can inspect what our Order is actually doing in our Test. So, we're going to inherit from Order, and add a few different diagnostic properties, like whether or not Load was called, and how many times we called GetDataRow, so that we can check that in our Test. So when we override Load, we're going to set WasLoadCalled to true, and then call base Load. And when we call GetDataRow, we're going to increment our Count and then return the base GetDataRow. And this is just so that we can verify through a Unit Test whether or not this lazy loading is actually working the way we expect it to. So now in our first Test, we're going to say that we want the Order to Load itself only once on a property access. What that means is we don't want it to have to make multiple calls to the database for each different property that gets accessed. As soon as we reference one of those properties, we want for it to Load the entire state. Now that only is for other properties other than the Id, so when we refer to order.Id, we expect that WasLoadCalled is going to be false. And furthermore, that GetDataRow count is going to be 0. Now then once we refer to ShipMethod, now that should've triggered the Load to be called, so we'll assert that that's true, and the GetDataRowCount should be 1. And then if we go and check the Customer, the WasLoadCalled should still be true, but the GetDataRowCount should only be 1, it shouldn't have gone up. So, it shouldn't be 2 just because we've referred to two properties. And if we Run this Unit Test, you can see that it passes, so it's behaving as we expect. And if we do another Unit Test here that says we're going to Load the Items in a single call on that property access, what this is checking is, we don't want to make multiple calls to instantiate up each of the OrderItems as they are fetched. We want to fetch the entire collection all at once. And so, we're going to make sure that we only call the Repository right here, so we're going to put a breakpoint at that spot. We're going to Debug into this Unit Test. We'll clear out our Output Window, and Step Over that line where we're going to grab those Items, and you can see right at that point, we're fetching the order Items from the database. If we back this up and do it again, you see you don't get another line, so we've loaded it once, and only once, and we can verify that we did in fact get those three items. And if we look at our Test, you can see that it's, yeah, right here, it's passing as well. So that's the example of showing how you can implement Ghost objects. Requires a little bit more code than some of the other options, but it does give you the benefit of an object that is responsible for its own lazy loading, and is able to do it in a software more intelligent fashion, because it knows which parts of itself are loaded yet, and which ones aren't through the use of this Load Status implementation. Now, there're a few downsides to using Ghosts as a technique. One of them is it violates the Single Responsibility Principle because it has to know about all this persistence. And also, it's using this base class DomainObject, so if you have some other base type that you're using, you won't be able to implement this easily because you don't have multiple inheritance in C#. But if you're okay with having your domain types inherit from a common base object, this can be useful. One last thing to note about Ghost objects, is that they don't have to load all their state on a property access. You could have some intelligence here that said, I have some properties that tend to get used together, and so when any of those are referenced, all of that group get loaded. And then I have other properties that tend to get used less frequently, or under different scenarios, and I'm going to load those in a different group. And so you can implement separate groups of state within your object that get loaded. So, again, this is something you would only want to implement in response to a real performance problem, and not as a premature optimization, but it does give you some great flexibility for tuning your application's access to the database by using this technique. How It Is Used So in terms of how lazy loading is used, typically the client does not know whether or not it's working with a Ghost or a proxy. Ideally, it's working with something that it thinks is the real object. Now, depending on your implementation, the client may have more or less knowledge of this, and the lazy loading may not be fully encapsulated in the object, but ideally the client can work with it as if it were the real object. It's worth having some kind of trigger for the client code to be able to set whether or not it wants lazy loading to be on, or off, especially if you're writing a framework like an ORM tool, like Entity Framework, or nHibernate. In these cases, it's often valuable to be able to say, no, I want to eager load these particular properties even though by default they might be lazy loaded. You also should consider using the Lazy T type which is available in .NET 4. It's thread safe by default, and provides a very simple way to implement lazy loading of any given type. Consequences Some of the consequences of the Lazy Load Pattern include the ability to greatly improve the performance of your application by eliminating unnecessary calls to the data store. However, it can add some complexity, and in particular, it can be difficult to keep your domain objects ignorant of mapping and persistence logic when you're implementing lazy loading. In fact, it can take quite a bit of extra code in order to keep this separation of concerns in place. So that's one thing to keep in mind when implementing this pattern. You need to determine how much purity you want in your design in terms of how great your separation of concerns, and your following of the Single Responsibility Principle you need to have balanced with how many objects and how much complexity you want to introduce into your design. Now you want to be aware of something called ripple loading when you use lazy load. For example, if you have a collection of objects that you iterate through, and each one of them you are going to reference some property of them that's lazy loaded, or perhaps each one of them is a Ghost object, and as soon as you refer to them, the Ghost object instantiates itself, what you often will get is something called an n+1 behavior where you fetch the collection once, the list of Ids once from the database, and then as you iterate through these, let's say, 50 different items, you make 50 additional calls to the database, where you say give me the first order, give me the second order, give me the third order. This is extremely inefficient, and it's much better for you to fetch all of those rows in a single request. So, the way that you implement this is you want to treat your collections separately when you implement lazy loading. You want to make sure that when you fetch a collection, the collection itself can be lazy loaded, so you only will fetch the collection when some portion of that collection is referenced, but then when you do fetch the collection, you fetch the whole thing. Now, for some very large collections, this isn't practical, but even so, with large collections, you might at least batch up the request so that you fetch the first however many rows, and implement some kind of paging, or other technique, so that you're not doing a single request for every single item in the collection. Finally, and most importantly, you want to make sure that you're tuning your application so that it only loads the data it needs when it needs it, and that it gets that data with as few requests to the data store as possible. This will result in optimal performance, and that's what you're going for when you're implementing this pattern, is you're trying to tune for the performance of the application. You're trading some simplicity in your design for some better performance, so you want to make sure you don't do this prematurely, or across the board, but rather only in response to an actual performance problem that you're trying to solve. Related Patterns We saw that there are several related patterns to the Lazy Load Design Pattern. These include the Proxy, which is used for the virtual proxy technique, as well as the Strategy Pattern used by ValueHolder, and the Template Method, which we saw was used by the Ghost implementation. You can learn about each of these in the Pattern Library on Pluralsight. References I also want to recommend a couple of books that you can go to learn more about the Lazy Load Pattern. In particular, the Patterns of Enterprise Application Architecture book by Martin Fowler, has an excellent chapter on the Lazy Load Pattern, which was used extensively in researching this particular module. And of course, the Design Patterns resource itself, the original book by the so-called Gang of Four, is also required reading if you're interested in learning more about design patterns. You can find a little bit more online on Martin Fowler's website about the Lazy Load Pattern. It's basically a short summary of what's in the book, so if you don't have the book, you can check that out at the URL shown here. Summary In this module, we took a look at the Lazy Load Design Pattern. This is a pattern that you can use to reduce the number of data access calls you need to make. In particular, when you have parts of your object that you're not using, you can eliminate those calls to the data store, and make those calls only as needed. You want to avoid adding lazy loading until you need it, because it adds some complexity to your design, so, premature optimization is the root of all evil. Avoid it. There're are several different approaches, each with pros and cons. We looked at four of them. We have the simplest of them, which is the lazy initialization. Then we can go take that a step further and use the virtual proxy, but that has some identity problems. We can implement the Value Holder Pattern, which is a little bit more complex, and actually is implemented using Lazy of T in .NET 4. And finally, we saw that we can use Ghosts objects, which are a little bit more intelligent, but again, additionally complex, and also violate the Single Responsibility Principle. Remember to use Lazy T as a good first step when you're doing these optimizations. It's an awesome, and underused type that's been available since .NET 4 came out. And that's it. I want to thank you very much for listening. I hope to see you again real soon on Pluralsight On-Demand. My name is again Steve Smith. You can follow me on my blog, or on Twitter, where I'm Ardalis. Mediator Pattern Introduction Hi, this is Donald Belcham, and in this Pluralsight on-demand video we are going to look at the Mediator Pattern. Motivating Example With any design pattern we should consider the uses of it. If you are working with many objects of a similar type and each of those object instances is required to communicate with all of the object instances, the mediator pattern may be applicable. Let's take a look at a situation such as this. Demo: Motivating Example Let's consider a domain whereby we have a group of aircraft flying in a given airspace. For safety reasons, each aircraft needs to know about the other aircraft so it can tell if it's too close, too far, trailing within an unsafe distance or any number of other things. To do this, we populate our airspace with three different flights, flight1 gets created, flight2 is created in the airspace, and then flight2 says, hey, I know about flight1, and flight1 returns and says, yeah, I accept that flight2 is also something that I know about. So now these two different flights and these two instances of objects know about each other. If we introduce flight3 to the airspace, and again, flight3 has to go through the process of saying, I acknowledge that flight1 is in my airspace, flight1 reciprocates, flight3 then says I know about flight2 being in the same airspace as me, and flight2 reciprocates to flight3 as well. By doing this, we've created a web where all objects know about all other objects. All we're doing inside of each aircraft is creating a list of the aircrafts that it knows about. It can then take that list and do things with it. So let's think about the fact that some aircraft can trail closer to other aircraft safely while others can't, so each aircraft has a distance that it can be safely within based on the aircraft that is flying in front of it. If we take a look at our Airbus321 class here, we have an instance of IsTrailingGapAcceptable method, and for it to say is this acceptable, it has to go through all the other aircraft that it knows about and determine, am I trailing behind it and if I am, how close behind it am I, and is that acceptable or not. So we have here just a simple bit of logic, much simpler than it would be in the real world, but a simple bit of logic that says, this aircraft that I have acknowledged, if it's of a type, in this case, Boeing737200, do some logic, figure out how far I am behind that specific aircraft, and then make use of that aircraft's safe distance trailing distance, and return out a true or false. And then it does the same thing all over again for the Embraer190, making use of different values because this aircraft has different safe trailing distance between the Boeing737200 and the Embraer190. The more and more types of aircraft that we create, the bigger and bigger this gets. And you also have to remember, this is going to be necessary in every different type as well, so every type has to say, am I safely trailing the aircraft around me. In an instance such as this, we are able to make use of the Mediator Pattern to bring our code into one centralized location and not have an instance such as the airbus321 class having intimate knowledge about the Boeing 737200 or Embraer190. Definition Let's take a look at the definition of the Mediator Pattern. Mediator Pattern states that we should have one centralized component, the Mediator that is responsible for the communication between all of the other components. It's this centralized encapsulation of the communication that allows us to give better single responsibility and a much easier process for objects to communicate within one another without having to have intimate knowledge about the existence of the others. In the Mediator Pattern there are a number of different components. The first one are Colleague components. These are the components that are planning on communicating between each other. In the case of our example we were looking at before, these are the different types of aircraft that were in the airspace. Every one of those items wanted to communicate with each other, therefore, they are colleague components. It's not uncommon for those colleague components to be of the exact same base type. That might be that they implement the same interface or, in the case of our example, they all implement to the same base abstract class, which was aircraft. The one thing that we didn't see in our example, but we will in the next demo, is that those base colleague components all have knowledge about the Mediator class. So rather than knowing about each other, so the Airbus321 knowing about the Boeing 737, these components know about the mediator class. So that's the one place that they need to rely on to communicate. So instead of communicating amongst themselves, the components communicate to the Mediator class. The second type of component that we have is that Mediator class. The Mediator itself is just a single centralized component, most likely one class that has all of the logic necessary for handling how these colleague components are going to communicate. So, it's going to have the logic that says, when I need to find a new flight level for my aircraft, how am I going to know whether I am infringing on the flight space of another aircraft or not, and then how do I communicate back to the requesting object or to the other objects in that area that are affected? Usually you want to have an abstraction for your Mediator class as well, so when we're working with our colleague components, they have to have an intimate piece of knowledge about the Mediator component itself, but instead of working with the concrete Mediator class, they will work with the Abstracted class an interface or a base abstract for the Mediator component itself. Demo: Mediator Pattern Let's take a look at the sample of a Mediator Pattern. The first thing we were talking about in the slide deck was the colleague concept. So these colleague classes in our example are different types of aircraft. Right now we're looking at a colleague that is the Airbus321, so you can see it implements the aircraft base class, that's what it inherits from. If we were to look at the other classes like the Embraer190, it is a colleague and it implements the same base class of aircraft, the same thing for the Boeing737200. All of these now are colleagues, and we could add many more different types of aircraft as long as they implemented the aircraft base class, they would become a colleague. The aircraft base class itself is really the definition, in this case, of the different things that an aircraft can do. If we were to be implementing this without the Mediator Pattern, we'd likely be in the aircraft base class, but possibly up in the specific colleague classes where we would be writing code that would do things like check off who do we communicate, how do we communicate with them. You can see here and in the Airbus321 class that there is no reference whatsoever to a list of other aircraft anymore. Instead of that, what we have is this reference here to the AirTraffic Controller class, the iAirTraffic Controller interface actually. It's this iAirTraffic Controller interface that is the abstract definition of our Mediator. So instead of the aircraft, whatever type of colleague it is, knowing about each other, we have the colleague classes knowing about the Mediator class. So as part of creating an aircraft, you have to give it a CallSign and a Constructor, plus you have to also give it an AirTrafficControl that is taking over ownership of the communication for this aircraft. When we go to do communication between the different colleague classes, it is the AirTrafficControl interface that we work with. So we can see down here in the altitude, when we set a new altitude the AirTrafficController is notified, the aircraft location is changed, and in this case, we're simply passing in the instance of this class, and there it can tell what the altitude is and other values, and it's inside the Mediator the decisions about who should we tell about the altitude change, and things like that are happening. So let's move on to the Mediator class itself. If we take a look at the interface, it's a simple definition. We're saying there are two types of communication that can go on in here. One is that we can receive the aircraft location and another is that we register the aircraft under guidance. So we just jump back to the aircraft itself. If we take a look in this constructor, we'll see that right away in the constructor, we say register this aircraft as being under the guidance of this Air Traffic Controller. So we've now told the Mediator, hey, we are one of those objects that you may need to communicate with. If we go now to our actual concrete implementation of the iAirTrafficControl interface, you can see here that we have registered the aircraft under guidance, and again, it's a lot like what we looked at before. All we're doing is putting a list of those aircraft together that have said, yes, we are things that you may need to communicate with. It's then inside of the ReceiveAircraftLocation method that we're seeing a bit of logic starting to creep in where we're saying when we receive the location, look through all of the aircraft that are under our guidance, except for the one that is reporting at this point in time, and go ahead and do some math and say, are we within 1000 feet of the aircraft we're currently looking at in the under guidance collection. It's at this point here that you would implement communication. So this may be something like, we might say instead of the reportingAircraft we might do currentAircraftUnderGuidance.WarnOfAirspaceIntrusionBy, and then the (reportingAircraft). So now we can say every aircraft can now receive a piece of information saying, I'm being warned that my airspace is being intruded upon, so things are getting too close. All we have to do here, we'll just create this method and we can do something in response to the warning. So we've now just established our communication. If we jump back into our Mediator here, our class original object has said, hey, we want to tell people things, so it said, we're going to tell people that our location has changed, and you've done that by calling this ReceiveAircraftLocation method. Then we're going to determine who should be notified about that happening. We loop through all the aircraft under our control, do a little bit of logic to determine who should be notified, and we go ahead and say, hey, I've got that aircraft, I'll communicate to that aircraft that something is going to happen. If we take a look at the program where we're kicking off how we deal with the Mediator, you can see it's a little bit different. If we go and look here, we can see we actually create a Mediator object and then we create our classes. And with those colleagues, we pass in the Mediator to them because a colleague has knowledge about the Mediator. That's all there is. So every time a new instance, in our case of an aircraft, is coming into scope, we just have to say, here is your Mediator and the communication will take place for it. Down here on the bottom line, we're saying the first flight, the Airbus321 is going to have its altitude change by 1000 feet. If we jump into that piece of code, we can see that this is where the value, Altitude change, the Air Traffic Control, the Mediator is being notified, and then all of that logic we were just looking at kicks off about finding who should be notified of a possible intrusion. Advantages and Disadvantages As with any pattern or technique that you use, there are advantages and disadvantages. Some of the advantages you'll see out of using the Mediator Pattern revolve around the fact that you're centralizing the communication between many different objects. Instead of having each of those objects know about each other, you've decoupled that away and now the objects only know about their Mediator and they have their communication with it, and it's responsible for communicating out to the other objects. The problem that it solves is this concept of having many objects communicating with many other objects, so many-to-many relationship if you were to think in database terms, and turning that around and turning it to a many-to-one and one-to-many relationship between the colleague objects being many to one Mediator and the reverse. The one biggest disadvantage that you'll see in the Mediator Pattern is that the communication methods inside of it can become very large. Imagine if you have many different conditionals based on the type of object that is coming in or requesting the Mediator to take action. These methods inside the Mediator will have lots of if statements, select statements, things like that. Those can be mitigated by using single responsibility to a certain extent, but it is something to be aware of, that your Mediator can become very complicated. Summary In summary, the Mediator Pattern is a tool you can use when you have a large number of objects that need to communicate with each other, but you do want to retain centralized control over how that communication is enacted. It is also a great tool for decoupling those objects that need to communicate with each other in the sense that each object no longer has to have intimate knowledge about the other objects that it's communicating with. This has been the Mediator Pattern. Thank you for attending and I hope to see you at more Pluralsight on-demand courses in the future. Memento Introduction Hi, this is Steve Smith with Pluralsight on-demand and in this video we'll take a look at the Memento Design Pattern. Memento is a useful pattern for implementing Undo/Redo functionality in your applications. Let's get started. Let's first consider a motivating example for the Memento Pattern. This example is basically meant to show you when you would want to consider using the Memento Design Pattern within your application. The classic case for the Memento is when you want to provide some kind of a rollback or Undo functionality to an object or to your entire application. Adding Undo functionality directly to classes within your application would violate the Single Responsibility Principle, since presumably those objects already have other responsibilities. You can learn more about the Single Responsibility Principle in the Principles of Object Oriented Design Course available on Pluralsight. You also don't want to simply provide access to an objects internal state, as this would violate Encapsulation. Instead, you can use the Memento Pattern in order to capture that object's internal state without violating Encapsulation or the Single Responsibility Principle or SRP. Intent In the Gang of Four's Design Patterns book, they describe the intent of the Memento Pattern simply as "Without violating encapsulation, capture and externalize an object's internal state so that the object can be resorted to this state later." The Memento Pattern involves two objects: the originator and the caretaker. The originator represents the object whose state you need to track, while the caretaker is the object that performs the operations on the originator and also handles any sort of undo or redo operations. Applicability It's important to consider applicability with any design pattern. In the case of the Memento Pattern, you're going to want to use this pattern whenever you have an application whose state you need to track and you need to be able to restore previous states as needed. This can apply to the application state as a whole or to a particular object within your application. You want to use the Memento Pattern when it's important that you abstract this reuse, so that you don't violate encapsulation, and also you don't repeat this Undo/Redo logic across many different objects in your application. It's also allowing you to follow the Single Responsibility Principle as I already mentioned. Finally, you want to make sure that you don't break the encapsulation of the classes whose state you are tracking and managing, and the Memento Pattern provides a simple way to achieve this. If we look at the structure of the Memento Pattern, you'll see that there are three players involved, there's the originator, which is the object whose state we wish to track, there's the caretaker, which is essentially the object that manages the originator and handles access to it, as well as any kind of Undo or Redo or versioning of the originator, and then there is the Memento itself, which is simply a value object that holds a state property. How It Is Used Now let's consider how the Memento is used. The Memento itself simply holds on to the state of the originator. The originator should be the only thing that has access to this internal state that the Memento holds. The caretaker should have an interface to Memento that does not allow it to get access to this state, that would break encapsulation. The originator can create Mementos or it can restore the state given a Memento. And the caretaker is responsible for maintaining the Memento objects, but without being able to operate on their contents. If the application requires a lengthy history of various states, such as with a long Undo stack, the caretaker is responsible for managing this stack. Undo / Redo One of the most common use cases for the Memento Pattern is Undo/Redo functionality. This type of functionality is typically implemented using a Stack. When a change is performed, a Memento containing the current state of the object or application is added to the Undo Stack. Then, when an Undo operation is performed, the current state of the application is replaced with a state that is removed from the top of the Stack. If Redo functionality is also being implemented, the current state of the application is stored in the Redo Stack before it is removed. Next, when a Redo operation is performed it's sort of the opposite of the Undo. The only difference is which stack is being used, so the current state is replaced with the state removed from the Redo Stack while the current state is then stored once more into the Undo Stack. In this way, it is possible to Undo and Redo an arbitrarily large number of operations forward and back. Collaboration Let's review how the different actors in the Memento Pattern collaborate. Whenever a change is made to the originator state, the caretaker requests a Memento from the originator. The caretaker stores one or more of these Mementos until they are needed. If or when required, the caretaker passes a Memento back to the originator. It's possible that a Memento that has been stored by the caretaker will never be used if the user never implements an Undo operation. Mementos should be implemented as Value Objects, holding state but no behavior. And only the originator that created a Memento should be able to assign or retrieve its internal state. Consequences Now let's consider some of the consequences involved with choosing to use the Memento Pattern. Some of these are good, and some of these are less than good. For instance, the Memento Pattern shields other objects from potentially complex internal state within the originator. Obviously this should be considered a good thing. And as opposed to the originator maintaining its own versions of its state, the Memento Pattern allows us to keep the originator simpler. However, creating and restoring state may be expensive. Memento may not be appropriate if the state contains a large amount of information and there's no way to break this up into smaller pieces. It also may be difficult to ensure that only the originator can access a Memento's state. Different programming languages have different control over this and we'll see how in C# we can achieve this to some degree by using the object type as the Memento's state type. And finally, the caretaker is responsible for managing Memento's, but typically will have no idea how big or small they may be, and thus the caretaker may not make ideal decisions on how and when to store the Mementos given how big they may be for a particular object. Keep these things in mind when you implement Memento in your own applications. Operations One alternative implementation to the Memento Pattern is to store the operations that are being used to change the state of your application rather than the state itself. This may require significantly fewer resources. For instance, if we had a simple calculator example and we started out with an initial state of 10 and the operation that we wished to perform was +5, then we could simply store the reverse operation of -5 into our State Change Collection or our operation history collection, and then we'd store our new state of 15, but if the user chose to perform an Undo operation, we would simply apply the reverse operation that was topmost on the stored stack, in this case, -5. That would result in a New State of 10, as expected. This particular technique works very well when you have objects that have operations that are completely reversible, resulting in the exact same state. However, there are some situations where this is not the case. For instance, you may have a graphics application where when you move an object from one location to another on the screen, there are side effects. And if you try and undo that move by simply re-moving the object back to its original position, those side effects may still be in place, such as auto-centering of other objects or things of that nature. Likewise, it's well-known that translation is an operation that typically is not reversible. Let's look at an example of that. If we take the original text of the intent of the Memento Pattern as shown here and we translate it from English to German, in this case using an online translation tool, you can see the translation in German shown here. I'll spare you my reading of it. And then if we try to perform an Undo by applying the German to English operation rather than restoring the original state, you'll see that we get pretty close to the same text, but with some minor changes as shown in red here. Thus, in this case, using operation-based Undo is not going to be effective if it's important that we come back to the exact original state that we had before the operation. Iterative State Another option to consider, if saving the entire state of an object is too expensive, is the Iterative Memento. This is similar to storing just the change operations, but instead of storing the operation itself, a change set is stored rather than the complete state. For example, a version control system such as Subversion or Git, is able to check in only the changes made to each file rather than the complete file each time a change is made. This requires significantly fewer storage resources in order to maintain many different state changes. However, it may require more resources to re-create the complete state since it may have to walk through many different change sets in order to reproduce the New State from the various changes to the original. Demo: WPF Paint Now let's look at an example of how we can use the Memento Design Pattern to add Undo functionality to a simple WPF Paint application. You'll find the beginning part of this demo inside of the download available for this course. It's in the Before folder or you can get it started yourself by simply creating a new WPF project, name it Paint if you like, and then within the main window go ahead and add an InkCanvas object, and in this case we're going to name it canvas1, although we'll probably change that later. Now if you run it, you should see the window pop up like this and you can go ahead and start drawing on it using ink, so we can make a little happy face here, and that's our application right now. Now we want to use control Z, which you can hear me clicking right now, but you see it's not doing anything. We want Control Z to be used for Undo functionality because if I accidentally mess something up on my beautiful picture here, I want to be able to easily undo that, and so far it's not working, so we're going to go ahead and correct that. So let's just jump into our Code View and the first thing that we're going to do is we're going to add a type to represent our Memento, and so for that I'm going to create a new interface. And so this is my new interface for IMemento and you can see it very simply has an object State with a get and a set. Now we'll come back to that in a moment, but I think it's important to call out that we're using the object type here so that the calling code has no knowledge about the internal state of this object that is being passed around. Now next we need to decide who the collaborators are going to be in our application as part of the Memento Pattern. We have to have a caretaker and an originator. The caretaker in this case should be the main window application since it's responsible for managing the state of the window. However, our originator is the InkCanvas type and unfortunately we don't have a way to add the Memento interface that we need on that type directly, so we're going to go ahead and subclass it. I already have the code here, so I'll save you from having to watch me type. Here's the example of the InkCanvasWithUndo type and so you can see that we're implementing the pattern of Memento by adding two methods to the existing underlying class. First of all we have the CreateMemento method and then we also have the SetMemento method. I've also implemented the Memento type that we're using as an internal class on the InkCanvasWithUndo type. Notice that the type that's being passed around publicly is an IMemento, so when we create the Memento, we return back an IMemento, not an InkCanvasMemento. And likewise when we set that same Memento it's simply taking in an IMemento as well. This ensures that the window class will not have access to the actual InkCanvasMemento type that's being used. Now let's look at how we would implement this Undo functionality within the window itself. Something I would like to know as we go through this is how many of the states of the application have been retained as we move through the steps. So I'm going to go back to the markup and we're going to add a label. And, in fact, I think I'm going to go ahead and just add a little bit of layout as well, so that we can change this a bit and have our label be in a separate grid location. So I'm going to take the grid that we started with here and I'm just going to replace it with a new one. We're going to use our new InkCanvasWithUndo type here for the actual InkCanvas that we're going to use and then I'm going to make the main window a little bit bigger that should work. Now if we come back here, I just want to be able to set that label's value when we need to. So once we have some state operations being completed, we'll go ahead and store the count of those operations to that label. So let's next create the Stack that we're going to need for Undo. So we'll create a private read-only Stack of IMemento, and we'll call this states and we'll just initialize it right here. And then inside of our main window there's a couple of bindings that we're going to have to add. The first one is for Undo. Now it turns out that the Undo command is well-known to Windows applications, and so you can simply do this and specify ApplicationCommands.Undo, and we'll go ahead and generate this method. And within that method, I'm just going to assign my window and call the Undo method if it's an Undo command being passed. So that code is going to look a little bit like this, and we'll go ahead and create this method as well. Now to implement Undo, we simply need to take the state off of our Stack and apply it to our InkCanvasWithUndo. And so we only want to do that if our Stack has at least one state on it for us to pull off, and in fact, the way I'm implementing this the current state is always going to be on the Stack as well, so we're going to need to make sure that there's at least two items in there before we do our Undo, and the code is going to look like this since we changed the name of this. So we'll call this States. Now looking at this code, we're going to say if the state.count is greater than 1, so there's 2 or more states, we're going to throw away the current state. Again, this represents the existing current state of the application and then we're going to pull up the last state, which is the previous one by just peeking at the Stack, not actually removing that item. And then finally, we're going to set the state by using the SetMemento method. Then we'll update our label to states.Count. Now the last thing we need to do is actually store the states, we've left that out for now, so we need a new method. We're going to call it StoreState, and we'll just add it here. Now when we store the state, all we're going to do is take from our InkCanvasWithUndo, we're going to create a Memento, and then we're going to push that onto our state Stack and, again, update our label. Now we're going to need to initialize this, so we'll do this in the constructor we'll initialize it, and then we'll also need to do this every time some kind of operation occurs on our canvas. Now there's a bunch of different operations that might occur with a canvas if you were to build a full- featured paint application. For our purposes, we're only concerned with mouse activity and so we're just going to wire something up to the MouseUp command, and then we'll implement this. And whenever this happens, the only thing we want to do is call StoreState, alright. So at this point we're done, I think, we've wired up the Undo command, we've wired up the MouseUp command, and we stored the initial empty state of our application onto our Stack. Whenever we lift up the mouse, we're going to store the state again with the new latest state of the InkCanvas. Whenever we get a command that happens to be Undo, we're going to route that to the Undo method here and this is going to pop off the current state from the State Stack, and then read the last state that we have previously, and set that to the InkCanvas, and then update our label. And then if we look at StoreState it's just going to do a Create on the Memento and a push of that state onto our state stack. Looking here one last time at the InkCanvas, you can see that we create a copy of the state of the strokes collection. This stores all the different strokes that make up the current canvas. And then we turn that inside of a Memento, and in the SetMemento we simply take our Strokes collection and set it to a new collection made up of a Stroke array from the Memento.State. So, now for the moment of truth, let's run this. Here's our application, here's our current state count. This is representing the single state of empty that you see here. If we start drawing on this, you'll see our state count is updating and I can start, you know, drawing HI! to you. And then if I accidentally screw this up and say, oops, I didn't want to do that, we can do Undo, and we can continue doing Undo, and you can see the number decrementing. Now at this point we don't have Redo implemented. I mentioned in the presentation how that would look. We'll leave that as an exercise for the viewer. Basically what you would need to do is go and create a separate state stack for the Redo states and simply whenever an operation takes place for an Undo you need to add that state back onto the Redo stack. Related and Summary There are a couple of related patterns to the Memento Pattern. The first one is the Command Pattern. Commands can make use of Mementos internally in order to provide Undo functionality to whatever the commands function is, and the second one is the Iterator Pattern. You can use the Memento to represent each iteration state when you're implementing an Iterator. You can learn more about these patterns in the Pattern Library available on Pluralsight on-demand. You can learn more about the Memento Pattern from the Gang of Four's Classic Design Patterns Book shown here as the first link or from Design Patterns in C#, which also has a good implementation of this pattern available from the second link. Online you'll learn more at Wikipedia and also there's a codeproject article shown here that also describes the Memento Design Pattern very effectively. To summarize, the Memento Pattern provides a simple way for you to manage the state of a class and implement Undo/Redo functionality without breaking encapsulation of the class whose state you are managing. Using Memento, you will be able to follow the Single Responsibility Principle and the Don't Repeat Yourself Principle as you implement Undo/Redo functionality. And finally, you should try and avoid exposing the Memento's state to any object other than the Originator. One way that we saw that you can do this using C# is to simply not provide a strong type to that state, but implement it as just an object type. This is not foolproof, but it does make sure that your classes will have to at least cast it to something else before they can try and access its intrinsic values. This has been another Pluralsight on-demand module on the Memento Design Pattern. My name is Steve Smith and you can follow me on my blog at or on Twitter where I am Ardalis. Model View Presenter (MVP) Pattern Introduction Hello, my name is David Starr, and in this module we're going to be talking about the Model View Presenter or MVP Design Pattern. Now this design pattern is intended to be used in applications where we have a user interface and this pattern is designed to help us separate various components of our user interface so that we don't end up with those giant code-behind files that we might be used to in Windows Forms or Web Forms applications. This pattern is very popular and especially so with Microsoft developers because the two technologies we just discussed, Windows Forms and Web Forms, those two technologies benefit a great deal from using the Model View Presenter Pattern, and as such, this pattern has a fairly long history, not just within the Microsoft stack. One thing you'll find is that there is a lot of opinion, there are a lot of different variations about how to best implement this pattern, and what we're going to try and do here is show you how we implement the pattern on, because we know that that particular style or variation of implementation works pretty well for us. Now we will cover some of the other ways that the pattern can be implemented, but we'll focus on a very simple model that we use here at Pluralsight. Why You Care Now a reasonable thing to ask would be, why would I be interested in using this pattern in the first place, and I can tell you from my experience, if you've seen code like this, like what we see here on the screen, this is a good reason. Particularly with .NET and some of the technologies that we have, like code-behind files for both Windows and Web Forms, we tend to find code that has tons of business logic rolled up inside those code-behind pages. Now those code-behind pages can get very difficult to maintain when we have a lot of logic going on particularly in things like the event handlers within the ASP.NET pipeline, things like that. And if you find that it's difficult to read, understand, and maintain your code because when you open your code-behind files you see tons and tons of lines of code, this could be a really good sign that you want to consider something like the MVP pattern to help you get out of that condition. Also, we'd like to be able to tease apart some of the pieces of our user interface code so that we can test in isolation each of those pieces, and that's definitely where the MVP Pattern comes in. Intent Now the intent behind using this pattern, first and foremost, is to provide a very clear separation between these things, which all constitute parts of our user interface. Well, there's the data that we want to show on the screen that has its own concerns. We want it in its own class or set of classes, its own bucket. We want to also have a separate container, if you will, for our business logic. Now this isn't necessarily the business logic that you'll find way down inside your application where you are doing persistence or you're updating entities, things like that. This is the part of the application logic that controls how things behave on the user interface itself. It's very handy to pull that set of logic a little bit back from the code-behind file. And then finally, there's the display of the data itself. This is the code that governs where things are laid out, what the positioning is on the screen, things like this. And in a Web Forms application, for example, that would be our aspx and our code-behind files. Now it's not uncommon to think that the code-behind file is where we want to code this, but in fact, the business logic of our application should really be pushed out into supporting object structure, supporting classes, that we would find inside of a domain package, some sort of namespace or collection of classes that provides that capability for us. Now providing that clear separation ensures that each one of these collaborators in the pattern that is the classes that work together to form the pattern, these collaborating classes each have their own single responsibility and they include the Model. This is the class that we'll use that represents the data that we want to show on the screen, the View, this is the class responsible for layout. We talked a little bit about that being the aspx and its code-behind file. The same is true for Windows Forms application. The Windows Form and its code-behind file, that would be our View. And then finally, a Presenter class, the Presenter being a class responsible for coordinating updates between the View and the Model. When we achieve this separation, it turns out to be extremely useful for us if we are using unit testing or test-driven development so that we can test each one of these classes, each one of the collaborators, in isolation. And this, of course, leads ultimately to higher quality code. A Note on Variations The MVP Pattern definitely has an interesting history. Back in 2004, Martin Fowler published documentation of the MVP Pattern in his Patterns of Enterprise Architecture book, and later in 2006, he came out with a statement that from his perspective he was going to be retiring the MVP Pattern, and you can read about that decision here at the MVP Pattern Retirement Note on Martin Fowler's website. And what he proposed is that there are variations of the MVP Pattern, such that it deserved to be broken into two, one variation benign the Supervising Controller, and the other variation being the Passive View. Now with Supervising Controller, the View interacts with the Model. It knows about the data Model that provides the information that'll be shown on the screen, and it does this so that the View can do data binding and things like that, that make it easy to just wire up the plumbing on those views. Now the other Model Supervising Controller is one wherein the View knows nothing of the Model, and the Model knows nothing of the View at all, and this is achieved by causing the Presenter, in this case, to coordinate all data movement between the Model and the View, so that if my Model happens to have a Name Property I would, for example, maybe have a set Name method on my View and the presenter would get the name from the Model and call over to that View to set the name. So those are two different ways of looking at the MVP Pattern and you can follow up with all of Martin's documentation of it here, but also on MSDN there is a really great article explaining the nuances and the differences between these two different variations of MVP, the Supervising Controller and Passive View. I'll leave the subtleties of the pattern exploration to you as an exercise and I would suggest that article on MSDN as a great place to get started. Again, we'll be inspecting a version of the MVP Pattern that we have found particularly effective and it adheres to, sort of, that classic definition of MVP that we knew before Martin Fowler proposed splitting it into multiple patterns. Structure and Organization Rather than looking at the structure of this pattern with formal Models, we're going to use a little bit more simplistic big-box style of drawing here, and we're going to take a look at the structure and how the View, Model, and the Presenter interact with each other. First of all, the Presenter gets an instance of the Model via some mechanism, and again, this is a representation of that data that we know we want shown on the screen. It then makes calls into the View to update the View with the data from the Model. Now the thing is that the View has a reference of the Presenter as well and it does that for a couple of reasons. One is that in both Web Forms and Windows Forms applications, in both of those technologies, when a new form is instantiated, that's an instantiation of the View. And the View, it needs to instantiate a Presenter to control itself. That's why we'll see instantiation of our Presenter class inside the View, because when we call from one Windows Form to another or from one Web Form to another, the first thing that we're going to run into is that View class. So that View class not only instantiates the Presenter, but can also make requests of it. So, for example, if the Presenter has a method on it that says change my name, then View can call, respond to an event, maybe that a user takes on the screen, and call change my name on the Presenter, which will then do some work, potentially talking to a domain Model, re-fetch the data that should go back onto the screen, and then update that View with the data. Now, in this model, the View and the Model known nothing of each other as we've stated, and the Presenter's job here is to coordinate the information flow between those two other collaborators. We can expand on this in a Model where the Presenter provides to the View an instance of the Model itself. And this is done so that the View can simply show the data that the model is containing. Now this variation is more akin to the Supervising Controller variation and the implication of it is that the View and Model are no longer distinctly separated, although the Presenter does still provide coordination between the Model and the View as we'll see in code. Now before we move on from our base structure here, I want to call out one thing, and that is that oftentimes people will have the idea that the Model, well this must be my data entity that I'm getting back from my database. Let's say, for example, I have a database of Contacts, I've got a person inside that database. When I fetch that person object back, it may very well have some methods on it like Change my name or whatever a person object might have, set my address, things of that nature. That would be a formal entity, something that we might find if we built it up with entity framework or hand it, whatever, but that is an entity with its definition line primarily within our domain, and using that type of object for a Model is not what we're after here. This model, the one that we're looking at that's part of the MVP Pattern, really exists just to provide exactly what the View needs and only what the View needs. Now to be fair, is it possible for me to use that person object in here as part of my model? Could I have a Model class that has an array of person objects hanging off of it? Well, yes you could. For testability and succinctness purposes, and we'll talk more about this when we get into code, we really advise against doing that. The genuine intent that we have here for our MVP Pattern is that it resides 100% within the UI layer and, in fact, that's what constitutes our UI layer. Now our Presenter may very well interact with domain objects, like repositories, entities, services, things of that nature, in order to get some work done and to fetch the Model, for example, and build up the Model that it's going to need to pass to the View, but when that Model does end up inside of our UI layer here, we expect it to be fairly anemic and that is to say, the Model itself is not typically part of the Business Domain. There may be pushback on that, you may have different experiences, and I understand that is something that can be done. And if we're just throwing a quick app together, you know, this can work, I can take that person entity right out of the entity framework and bind it right onto my View. What we're saying with this approach of having a Model dedicated to our View, in other words, a View Model, is that we're going to only serve up in the Model exactly what the View needs and nothing more. And we do that for testability reasons and to ensure very clear separation of concerns within our collaborators. Demo: Web Form Example 1 Alright, enough slides, let's look at some code. Now before we jump into that code, let's just see the application that we're working with. It is a very simple Web Forms application that shows a list of automobile manufacturers. These are coming from some data repository. For each one of the manufacturers, we had the option to click this hyperlink, which will take us to a list of automobiles made by that manufacturer, or there's a rather hokey little feature on this page. If I click the Name link, watch the names and the order they're in, I'll click it, and we'll get a sort on that list of names. I'll click it again and that will be unsorted. So we have a feature on this page where we can sort and effectively unsort the list of automobile manufacturers. So that's the first page of our application. Note that this is deafult.aspx, so that's the page that we're going to be looking at. Let's jump over to Visual Studio and we'll see the code-behind page for this aspx. Let's actually see it, there it is, default.aspx and note that this page is implementing this interface, IManufacture ListView, projects in our Visual Studio Solution, we have our Domain Library, which is intended to represent the idea that we may have entities and repositories and things like that that are part of our Business Domain. That's separate from our user interface. Our user interface is encapsulated within this library, which is containing all of the elements of our MVP Pattern, the Presenter, the Model definitions and interfaces for our Views, and then the Web Forms application, which has within it the default.aspx and the supporting C# files for that aspx page. These are all part of the View, and so what that helps us understand is that default.aspx, the designer file, and the code-behind file, all of these are actual concrete implementations of our View from our MVP Pattern. Okay, so now that we have that, let's take a look at what our View is doing. It is, as we said, implementing IManufacturerViewList, so we'll take a look at the definition of that interface. It has one, and only one, method on it called Show. So Show needs to be implemented by our View. So we'll come back over and see that, indeed, it is implemented by our View. We're going to take a little more detailed look at what's going on here in just a moment. Let's also note that what we have here is a Presenter. So we have a private member variable that is a Presenter. That Presenter is going to be up inside of our Page_Load. Before we see how that's done, let's take a look at the signature of our Presenter. Our Presenter has an IManufacturerListView as a private member variable and here it is, this field, this listView field gets set by the Constructor, which is called when the Presenter is instantiated, of course, and the View passes an instance of itself. A little bit later, the Presenter's Init function will get called, at which point the Presenter will go off and get a viewModel and it does so through this GetViewModel method. This is a private method for the Presenter down here. We'll take a little bit closer look at how this is occurring, but for now let's just know that we're getting back a viewModel. That viewModel is a strongly-typed Model, here it is, ManufacturerListVM, VM for viewModel, and I'm calling it viewModel specifically because this Model is optimized just for this View. So once we have that back, we're going to call Show on our View, remember we got that passed in in our constructor, and we'll pass the viewModel, and then the View is free to do with that Model as it pleases. Back in our implementation of the View, let's see how we're initializing the Presenter. We initialize the Presenter, each pass through Page_Load, and if this is a PostBack, I'd rather if this is not a PostBack, then we'll call Init or initialize. And remember what that does, that effectively causes this method to be called, Show, on the View. So when Show is called, the View sets this property with the viewModel that gets pushed into the Show method, and the property is now available, not only to this code-behind page, but it will also be available in the View pages we'll see in just a moment. Now some things are maybe not convenient to set in the aspx markup page itself, and so we can set them here. we're storing a Boolean off of the viewModel, which happens to be IsSorted, and we're binding up a data source here, a manufacturersRepeater, we have a Repeater on our page and we're binding that Repeater up to a set of manufacturers that's placed on our viewModel. Now let's actually look at the definition of our viewModel real quick, and we can see what it has, it has a title. This would be the title of the page. Sometimes you would actually be pulling this title out of a data source or a database, and that's why we would want to have it on our viewModel. In our rather contrived example, it would probably be just fine to put an H1 on that page and put the markup right in the H1. But you could be pulling that out of a dynamic data source. We have an IEnumerable of ManufacturerVM. Now we said that the ManufacturerListVM, that's this class obviously, and it has an IEnumberable or a list, a collection of ManufacturerVMs. Note that that's an internal class which specifies for each row in that list of manufacturers, exactly what that View might need to render onto the screen. It's got a Name, it has a ListAutosUrl, this is the URL behind the hyperlink that's used when we click to go to a list of automobiles created by that manufacturer, and it has an ID. I happen to be using GUIDs for all of my IDs because it's simple in our little in memory data model example. It could be any form of ID. It has this IsSorted Boolean, and we'll go back over to default.aspx and note that as soon as we set the viewModel, we're going to take advantage of some controls that we've put on the page, a HiddenField, a Repeater, and we choose to set those things up right here in the Show method. Alternatively, if we look inside default.aspx we can see here that we're using the viewModel property directly to output the title to the page. So, as you can probably see, this is definitely an implementation of Supervising Controller, the MVP style, and that is that the View definitely knows about the Model. Now it's set on the View by the Presenter. And what's going on when we click sort. Well, if we look at the link button that is the Sort, we can see that it calls this OnClick event. The OnClick event is, in turn, simply going to call presenter.Sort, and pass to it a Boolean that is the current sorted state of the list of manufacturers, and this Boolean, remember, was set on the View by the viewModel. Effectively, this is just being passed right back in from the viewModel. So if we look at presenter.Sort, what is presenter.Sort doing? Well presenter.Sort gets a ViewModel and checks to see, do we need to sort? If we do need to sort, then we'll go ahead and Sort. We do an OrderBy on these manufacturers and reset them up. And then flip the bit on whether or not those manufacturers have been sorted, and finally makes another call back to listView.Show, and what that effectively does is cause the page to refresh. Now one note that I'll make here is down inside GetViewModel, we haven't looked at this because it's really not part of the pattern, but somehow this Presenter needs to get that ViewModel and get it instantiated. The way it's doing so is by using something called an Assembler class. This one's called ManufacturerListVMAssembler. We'll take another look at Assemblers probably in a different module dedicated just to Assemblers, but for our purposes what we can know is that this Assembler is going out and talking to our Domain, which is, again, down inside these libraries, and coming back with just what's necessary to populate our manufacturerListVM class, that's what gets returned back to the View. And once we've wired all this up, we simply hit Go and we've got ourselves a web page. Demo: Web Form Example 2 We've already seen that our default.aspx page in our little application is implemented using a Supervising Controller variation of the MVP pattern, and we saw that we're holding state in the Form itself, in View state, and in some controls, taking advantage of controls to hold that state across PostBacks. Now we're going to go a little bit deeper into viewing our automobiles, so we'll click the link for BMW, and we can see here that we have a list of vehicles that are created by BMW and this page is implemented using more of a passive viewModel and we'll take a look at that code. It turns out this list is here under Autos, we've got this List.aspx. And note right away one of the differences we can see is that there are no instances of script on this page that's looking at a ViewModel property. So, for example, we cannot say ViewModel, because there is no ViewModel property in the code-behind page. Well, what we have instead are some controls that are going to be set by the code-behind page, and ultimately by the Presenter directly, and we'll take a look at how that works. If we pull up the code-behind page, we can see right away that we're implementing IAutoListView. So let's look at IAutoListView. Remember in our previous view interface we had one method that we had declared called Sort. Now for this code, I've implemented the IAutoListView interface, the Presenter, and the ViewModel, all right here in this one code file to make it a little bit easier to navigate, and note it's over here in the MVP.dll. I'll look inside the View interface and we've got three methods, and that's because the Presenter is going to make very discrete and explicit deliberate calls to the View, to say set this one little piece of data, set this next little piece of data, and that's very characteristic of what we'll find in a Passive View variation. This does allow us to test our concrete implementations of our View, to test very fine-grain behaviors of our Presenter, but I've come to the conclusion over time that writing tests that test the behavior of the presenter to simply call these methods, isn't nearly as useful as one might think, and it's very, very convenient to be able to reference my ViewModel directly from my markup page or my code-behind page. So that's why we've chosen to take a bit more Supervising Controller implementation in Well this is our interface, and let's jump back over to our code-behind and our concrete implementation of our interface for the view, and see what's going on. We can see that we're getting a manufacturerID. Now it turns out, and we didn't highlight this, but back on our web page you can see that an ID, I know it's ugly, this is a big GUID up here, is getting passed as a query string parameter, and so we need to hold that in state on the page. Sometimes we'll be coming back with a PostBack if we happen to click a control perhaps. So you can see that I'm getting manufacturerID when I do that. I'm going to look to see, is it a PostBack. I'll pull it off the query string, otherwise, I'll get it off of a HiddenField control, but in either case we're going to get our manufacturerID, this is the GUID for BMW, and using that, we're going to instantiate our Presenter. Note in this case, the Presenter is taking not just the View on its constructor, but also a little snippet of data. It's very common for us to think about passing a Model into the Presenter so that the Presenter can set itself up properly. This manufacturerID is the model in this case. Just like in our previous example, if this is not a PostBack, we're going to call presenter.init. Note that we have discrete methods. These are implemented right off of the View's interface, SetManufacturerName, and that's done by setting the text of a label, SetManufacturerID, that's done by setting the value of a HiddenField. So the View is making the choice of how to implement these features, because it might be a web page, it might be a Web Form, but in either case it's being directed to do so at a very granular level as opposed to our previous example that had Show where the View was making the decision to go through and set up all of these things in a sequence of events. And then finally we see BindAutoList, which receives an IEnumberable of ViewModel types, and it binds up the Repeater that shows us the automobiles. Now let's go and look at the implementation of our Presenter. We can see here that the Presenter is merely setting up some fields with its constructor parameters, and when Init is called by the View on the Presenter, it goes out and using an Assembler, assembles a Model, gets the ViewModel back. We can see the full type there is AutoListVM, VM, and then uses that ViewModel to invoke these little discrete methods against the View, instructing it to set the View up. It does not actually pass an instance of the Model back into the View and one could argue that's sort of what's going on here with this BindAutoList, because in this case, in order to take advantage of a Repeater control, I need to do one of two things. I could expose a Repeater control off of the View so that I could call View.Repeater control.datasource =, but if I did that then I would be exposing so much information about the View that I wouldn't be able to write another more generic View that wanted to instead use something like a table or some sort of manual iterator instead of the control that would be exposed on the interface. The bit of a leaky abstraction there, that was a deliberate decision, that's okay. And finally down here we can see our AutoListVM. This is the Model itself which contains Manufacturer Name and ID, and an IEnumberable of AutoVMs. This is all the information needed to construct and display the link for each model of car in our list of cars. So what are we seeing here? The primary difference between our two implementations is whether or not we're using very discrete methods on the View interface in the View concrete classes versus just pushing the whole ViewModel over to the View and saying, let the View handle it however it chooses. And again, this is more of the Passive View Model, named accordingly, because the View has fewer decisions to make about how it will behave. Demo: Windows Forms Example Now we've seen how MVP works using Web Forms, but what about Windows Forms? We alluded to the idea that we can share this pattern inside Windows Forms and it turns out that you absolutely can. Here we have a little Windows Forms application, very simple, very small, all it does is implement the same behavior of listing manufacturers that we see on this front page, and we also get that sort capability that we have right here on the web page by clicking Name. This Windows Forms application is using the same MVP infrastructure, same classes, as the ones being used by the Web Forms page. Let's take a look at some code here. It turns out that, let's close up our previous code files, we put these classes, the View definitions, View interfaces, Presenters, Models, Assemblers, all those classes we put here in the MVP library so that we could share them, and they can be shared not only with this WebForm, but also with this WinForm over here. It's really nice to put those classes in a separate DLL. That keeps my Web Forms application extremely thin, such that the only thing I have in that Web Forms application are Views. This is true even if I have no intention whatsoever of putting a Windows Forms application on top of my MVP code. So here's our Form. We're going to open up our code and look inside the code there of our Form and we can see that it also implements IManufacturerListView. Remember this is the exact same ListView that we were using with our Web Forms page, and we can see how it does so. Now when the Form initializes there is no PostBack Model, of course, in Windows Forms, so we simply call Presenter, the Presenter, and then we hit Init. We're going to call Sort on the Presenter, passing in the current Sort state. Now we did store this state somewhere. We could have held in a ViewModel attribute, but I elected instead to put it in the tag of the Sort button, so there is our ViewModel populating our interface. This is the Supervising Controller Pattern within the WinForm so that we are binding up our ListBox to our ViewModel Manufacturers. Note a ListBox needed to have a specific type that it can bind to. It needed a list or an IList drive type, so we went ahead and created one using the IEnumerable we got back off the ViewModel. This is a very similar code file to the one that we wrote for the implementation of the View when we used Web Forms, the code looks very, very similar, and that makes sense because we're using the same type of UI infrastructure in that MVP Pattern, we just happen to be pulling it off now inside of a Windows Form. Now this is a bit of a review for us at this point, but we'll look at the collaboration. Collaboration Among Objects Between the collaborating classes, we have a Model. The Model, of course, holds data. That data is particularly well-suited and particularly constructed massaged to be surfaced by the View. And the View itself is instantiating our Presenter, it is requesting that the Presenter do work. For example, when we would call Sort we would ask the Presenter to actually do the Sort for us, we did not do that sorting in the View. And we also know that there are two variations that we looked at, Passive View and Supervising Controller. You may or may not have a reference directly to the Model within the View. The View may instead rely on the Presenter to hard-wire up the data that it gets from the Model directly into the View. And finally, we know that a Presenter has the job of responding to requests from the View. This would be like that Sort call, and in some circumstances where I have some dynamic data, I may have an observable type of data Model, so that I've got data dynamically changing under the covers. If that's true, I can subscribe, the Presenter can subscribe to events on that data Model to know when that data is changing or when there's a need to change the form and re-show data on the View. So sometimes, and we didn't show this, but it's very useful to know that our data has changed, respond to an event from that data change, and push that data back up into the View, and that would be the job of the Presenter to monitor those data changes. And obviously the Presenter does update the View with data from the Model, whether it does so by handing over the entire ViewModel or whether it does so in small discrete chunks, that's up to you, that's up to your variation of the pattern. Consequences Now we didn't have time to focus on unit testing, that wasn't part of learning the pattern itself, but know that each class, each one of our collaborating classes here, is now very testable, and independently so, if we happen to be using Unit testing or test-driven development. Great stuff, I highly encourage it. Each one of our collaborators has very clear separation of concerns. We just saw what those concerns were on the collaboration slide, and each collaborator also has a single responsibility, which is great. We're adhering to some good Object Oriented Design Principles here. And it just turns out that this produces code that is far more readable and maintainable than finding business logic, you know, that initial slide that we saw where we had a lot of business logic in our Web Forms, code-behind or in our aspx pages. Known Uses Now as we've discussed, obviously makes extensive use of MVP behind our Web Forms application that is In addition to that, there are a lot of MVP frameworks for .NET. You can go out and check some of these frameworks out on your own. They will give you some nice generalizations and easy ways to plug in and reuse things like Models and Views and save you some code writing. And the fact that there are so many frameworks, MVP frameworks for .NET, lets you know just how important this pattern has been in our technology stack. And finally, there are many, many Web Forms and many, many Windows Forms applications that are using this pattern in production today. Related Patterns There are related patterns. These are all what we might think of as Model View separation patterns. We have Model View Controller, we'll definitely be seeing Model View Controller in another module in the Patterns Library, and we have Model-View ViewModel. This one turns out to be very useful in WPF applications and Silverlight applications. We see MVVM. We have Supervising Controller and Passive View, obviously as the two variations of MVP. Those are different enough once you start looking at them in a bit more depth, that you'll find they deserve to be recognized as patterns of their very own. Summary We've learned that this MVP Pattern has a good long history, particularly with .NET developers, and as a result has several variations of its implementation. There is a lot of discussion that you can go find online about nuances and ways that people like to craft their Presenters or craft their Views to make them just so. And there's plenty of debate about how best to do that. Ultimately what we've been able to do here is create some very clean user interface code by separating out the concerns that we might normally find in our code-behind pages, and we need to recall that all of the MVP collaborators that we saw were in the UI layer. Remember that, yes I can pull a very rich entity up and bind it directly into my View, but we get a lot of advantage by not doing it that way, by putting in another layer of that Model that gets built by those Assemblers that we saw. We saw that we had our Domain classes, that is the primary location for all of our business logic, and that was in a completely separate assembly doing work under the covers, under the UI. We weren't really worried about how that work got done. And that's Model View Presenter. I hope you go try it pretty soon and if you've not incorporated this into your toolbox, this is going to be a really good one, and really can improve your day-to-day life working with Web Forms and Windows Forms if that happens to be what you are currently working in. This has been David Starr. Thank you very much for joining me and I hope to see you in class sometime soon. Model View ViewModel (MVVM) Pattern Introduction Hello, this is Brian Lagunas, and in this module I'm going to discuss the Model-View-ViewModel, otherwise known as the MVVM Design Pattern. The Model-View-ViewModel Design Pattern facilitates modern development techniques such as separation of concerns, unit testing, and test-driven development. I have had great success with the Model-View-ViewModel Design Pattern. Notably I was part of a team that about a year and a half ago created an application that tracks the progress of construction at the erection site. The project was completed on time, and over the span of that year and a half has had only two reported bugs, and that was partly due to the fact that we used the Model-View-ViewModel Design Pattern to construct the application. As with most Design Patterns, the Model-View-ViewModel Design Pattern is just a set of guidelines that when you follow them it makes it easier to write applications. Use them where they make sense and modify them to fit the needs of your application at a given point in time. We're going to start off by talking about where the Model-View-ViewModel Design Pattern came from, who created it. Then we'll discuss what is the Model-View-ViewModel Pattern, the different components, what those components are, and how they interact with each other. And then we'll also see how to implement this pattern in your own applications. History In 2004, a gentleman named Martin Fowler published an article that describes a Design Pattern called the Presentation Model. In this article, he explains that the Presentation Model Design Pattern is similar to the MVP or the Model View Presenter Pattern, in that it separates a View from its behavior and state. Specifically, the Presentation Model pulls the state and behavior out of the View and into a Model class. It coordinates with the domain layer and provides an interface to the View. The Presentation Model frequently updates its View so that the two stay in sync with each other. That synchronization logic exists as code in the Presentation Model classes. One thing to note about the Presentation Model Pattern, it is not specific to any UI framework. In 2005, a gentleman named John Gossman, who at the time was one of the WPF and Silverlight architects at Microsoft, unveiled the Model-View-ViewModel Pattern in his blog. In the blog, he described the Model-View-ViewModel as a variation of the Model View Controller, but it's tailored for the modern UI development platforms where the View is the responsibility of a designer rather than a developer. In 2008, John changed his mind. He realized that the Model-View-ViewModel pattern is identical to the Fowler's Presentation Model and that both patterns feature an abstraction of a View which contains a View state and behavior. Fowler introduced the Presentation Model Pattern as a means of creating a UI platform independent abstraction of a View whereas Gossman introduced the Model-View-ViewModel Pattern as a standardized way to leverage core features of WPF and Silverlight, meaning that the Model-View-ViewModel Design Pattern is tailor-made and specific to the WPF and Silverlight platforms. Intent So what exactly does the Model-View-ViewModel Design Pattern really do for us? Well for one, it helps the developer separate the concerns of the View, the View state and behavior, and the underlying data. It also allows for unit testing of the application, as well as UI testing. Now most would agree that maintenance is the number 1 cost in the software development life-cycle, you know, add a new feature here, add a new feature there, make a change, modify this, modify that. Well we want to be able to do that throughout the entire life-cycle of the application, but we don't want to break anything, and we want to make it easy to actually implement these features or make those changes. It also helps developers and designers work together with less technical difficulties. In the past, there's always been friction between the designers and developers, you known, who's touching my UI and who's touching my code. Well now you could split the two teams more easily, you don't get a lot of the butting heads that you used to get, you know, designers can go and create this awesome beautiful user interface without ever having to know what the developer is doing, the designer just needs to know the DataPoints that they're going to be exposing to the user, and the programmer doesn't have to know what the designer is doing. He doesn't care. He is just coding to the functionality of the application's requirements. The single most important aspect the Model-View-ViewModel Pattern relies on is the data binding infrastructure in WPF and Silverlight. By binding elements of a View to a ViewModel, you get very loose coupling between the two and you entirely remove the need for writing code in a View's code-behind or in a viewModel that would directly update a view. The data binding system also supports input validation, which provides a standardized way of transmitting validation errors to the View. Structure The Model-View-ViewModel Design Pattern is made up of three components. It has a View, a ViewModel, and a Model. I will be discussing each of these components in more detail later on, but for now I want to concentrate on the structure of the Pattern. Let's begin with the View. Now the View may or may not have a reference to the ViewModel, it just really depends on how you implement this pattern in your applications. When I say that the View does not have a reference to the ViewModel, I mean that there will not be a hard-coded instance created, either in the View XAML or in the code-behind. There will be an instance, if you will, of the ViewModel in its DataContext, but that could be set by other mechanisms, such as a factory pattern of some type. But in any case, the view will never know about the Model. It should never have a reference to the Model. The only component in the MVVM Pattern that has a reference to the Model will be the ViewModel. The ViewModel may or may not have a reference to the View. Once again, it just really depends on how you decide to implement this pattern in your application. If you decide to have the ViewModel create the View, which is the ViewModel first approach, then the ViewModel will have a reference to the View. If you decide to go the ViewFirst approach, then the View would have a reference to the ViewModel. But once again, if you're using a factory pattern, it's completely possible that neither one of them have any reference to each other. The Model is completely oblivious to the fact that the ViewModel and the View even exist. This is a very loosely coupled design which pays dividends in many ways. Demo: Creating the Application Let's create a simple MVVM application. The purpose of this application is just to get you comfortable with the pattern and help you fully understand how it works. We'll start off by creating a new Silverlight application, and we'll call this simple MVVM. We will not need to create a website to host this particular demo application, so I'll uncheck that box. Now what I'm going to do is I'm going to create three folders, one for each of the components of the MVVM design pattern. So one is going to be for my Models, the other will be for my ViewModels, the next will be for my Views. Now I'm going to go ahead and move this main page into my view because I'm going to use this as my main View, so I'm going to go ahead and stick that in the Views folder, and I'm going to create a couple of classes. I'm going to need a Model object and in this example I'm going to use a simple Person object. And I'm also going to need a ViewModel, so I'm going to create another class and I'll just call this MainViewModel. I'm going to go ahead and drag these into the corresponding folders. So this is what our project structure should look like up to this point. The Model The model is the data, and you can look at the Model from two different perspectives. There's the object-oriented approach where your Model may be represented by domain-specific objects or you can use the data-centric approach where your Model may be an xml file or a data access layer or anything else that's responsible for communicating with a data store. Either way, the model's purpose is to represent the DataPoints, and it has no knowledge of where it will be presented or how it will be presented. Its single responsibility is to represent the DataPoints. On the slide in front of you we have a Person object with two properties. You'll notice that this Person object implements two interfaces, the INotifiedPropertyChanged interface, which is responsible for notifying the UI or Presentation Layer of any changes made to a property's value. The IDataErrorInfo interface is used to notify the UI if a validation rule has failed against one of those properties. Demo: Creating the Model I'm going to start off by giving our PersonModel object some properties that we're going to be binding our UI to. So a Person normally has a first name and a last name, and I know that at some point I'm going to be updating our person, so let's go ahead and give it a DateTime of maybe UpdatedDate, okay. In order to let my UI know that any of these property values changed, I'm going to have to implement an interface, the INotifyPropertyChanged interface, to be exact. So let's go ahead and implement this. And the implementation is actually pretty simple. We're just going to have a public method that takes a string parameter, if I can spell, and we're just going to say PropertyChanged, there. So now that we've implemented the interface, we have to modify our properties so when they do change we can let them know. (typing) And the last one is the UpdatedDate. There, now all of our properties are firing the PropertyChanged event when the value changes. This allows the View to display any changes that have been made to the underlying Model object's properties. Well, now I've got to worry about something else. I've got to worry about validation. How do I send validation errors up to my View? This is accomplished by implementing the IDataErrorInfo interface. (typing) So for the Error property we're just going to return null on this. This is the object level error, so we would set this for the object level validation. For demonstration purposes, we're going to keep the validation on our Person object, pretty simple. So I'm just going to validate that the first name has been entered. So I'm going to do a simple check. I'm going to say, if ((string.IsNullOrEmpty(_FirstName))) then we're going to set the error message to say First Name is required. Now anytime this validation error fails, my UI will be notified through the IDataErrorInfo interface and send a notification to the user. The user will get a visual cue that something is wrong with this particular field. The ViewModel You may be wondering what exactly goes into a ViewModel if my data and its DataPoints are in the Model? Well, the ViewModel contains properties, commands, and other abstractions to facilitate communication between the View and the Model. What does this mean? Well, it means that the ViewModel will have properties that expose instances of your Model objects. It will also have commands or events that interact with the View to respond to any type of user interaction. At a minimum, you want your ViewModel to implement the INotifyPropertyChanged interface. This is because your View will be bound to your ViewModel and the INotifyPropertyChanged interface is the mechanism which pushes data up to the View. As you can see, we have a ViewModel called Main ViewModel. It exposes a property of type Person, and this is the Person domain object that was in our View slide. We are exposing an instance of that Person object to our View, and anytime the Person object instance changes, the View will be notified of that change and update accordingly. There has been some debate recently about what your ViewModel should inherit from. A lot of people have their ViewModels inherit from dependency object or a UI element. Although the ViewModel manages the state and behavior of the View, it should not have a dependency on a UI base object. Basically, you do not want any control-related objects in your ViewModel. Demo: Creating the ViewModel Now let's work on our ViewModel. Go ahead and open it up and right off the bat I know that at a minimum my ViewModel has to implement the INotifyPropertyChanged interface. Add the using statement there, and go ahead and implement this. And we're going to implement it the same way we did it in our Model class, just create a public method here. (Typing) Making sure that the handler is not null. If it's not null, we're going to go ahead and fire that bad boy off. Now we have our INotifyPropertChanged interface implemented, and we have to have this at a minimum because, a little review here, this is the mechanism that pushes all the changes in our base data up to the View. The next thing I want to do is I want to expose a property that is an instance of my Model object. So let's go ahead and create, we'll just call this ModelPerson, and I know that whenever that value changes I need to update the View. And to do that, I just call the OnPropertyChanged method. Okay, now we need to populate this Person object with an instance of something. So let's go ahead and first create a constructor for our MainViewModel. And we can go ahead and load an instance of our Person and our constructor so right when we new up a new instance of our ViewModel, we'll just go ahead and create and assign an instance to our ModelPerson property. And let's go ahead and just say ModelPerson = new Person. We'll give it a FirstName of "Brian", LastName you guessed it, of "Lagunas". Alright, great, so now we have a method that will actually load a person up when this ViewModel instance is created. The View The View is simply the visual display. It consists of all the elements displayed by the user interface such as buttons and windows and graphics and all the other controls that we know and love. The View is responsible for displaying data and collecting data from users. It is not responsible for retrieving data, business logic, business rules or validation. In WPF and Silverlight, the View contains binding extensions that identify the DataPoints that will be represented to the user. The bindings point to the names of the DataPoint properties, but they don't have awareness of where those properties are or where they come from. The bindings are activated when the Views DataContext is set to a class that contains the source for the bindings. It is that DataBinding infrastructure that's built into WPF and Silverlight that allows designers to create rich and very interactive user interfaces without ever having to know the details or specifics of where the DataPoints come from. Demo: Creating the View Now that we have our ViewModel finished up, let's go ahead and get started on our View. I don't want to waste everyone's time and site here and type XAML up in front of everyone, so I went ahead and created a basic View to display our DataPoints. This is where I put on my designer hat. I now work for ABC Design Company and I have no idea what the programmers are doing over in programming land. All I know is I am responsible for building a rich UI that the users are going to interact with. What I do know are the DataPoints that I'm expecting. I know that this textbox here is designated for a FirstName property, so I'm going to set my Text to Bind to the ModelPerson.FirstName. I'm going to do that for the last name as well. (typing) And for the Updated values. (typing) I'm also aware that the FirstName has validation rules applied to it, so to enable those I'm going to set the validateOnDataErros to true. Now that my responsibility of creating a View and setting up the initial DataPoints is done, I'm going to hand this View back to the developer and now he's going to create and hook up a ViewModel to this View. So the first thing we have to do is we have to add a Namespace. This Namespace is the location of where our ViewModel exists. Now for demonstration purposes, we're going to create the ViewModel as a resource and then use a static resource DataBinding syntax to set the data context of the View. Let's go ahead and go UserControl.Resources, and here's our ViewModel. I have to give it a key, this is how we're going to reference it. We'll call it MainViewModel. Now I have to set the DataContext to that resource. Let's go ahead and build it. And everything worked. Now you'll notice that in the designer I actually see the data that I was going to load at run time. If you remember, early in the module I discussed a concept called blendability, the ability to see design-time data. So by using the XAML approach for creating my ViewModel, I have actually enabled design-time data. What's happening is my View is creating an instance of that ViewModel at design time and it's newing up that object for me so I can see the underlying data as it exists now. Now before I run this, there's one thing that I have to do that I forgot. In Silverlight, you actually have to specify the mode in which your data binding will behave. TwoWay, meaning that any changes that I make from the UI perspective will be pushed down to the underlying data Model, as well as being pushed up. So, I'm going to go ahead and change my mode, actually set my mode to TwoWay on the two textboxes that I will be manipulating. So let's go ahead and run this. And as you can see, the results are as expected. We have the FirstName and LastName of our Person object that exists in our ViewModel, and we also have validation on the FirstName, saying if the FirstName is empty, then it's not a valid person. So we'll go ahead and remove that and let's see what this says, First Name is required, so our validation has performed as expected as well. So we'll just put that back in there and our validation succeeds. Now the next thing we need to do is have something happen when we actually click a button. When I hit Save, I want the last updated date to change, meaning that we updated the person's Name or Last Name, one or the other, something changed on this person. In order to do that we have to use Commands. Binding the View and ViewModel I mentioned earlier that to create the connection between the View and the ViewModel, all you have to do is set the DataContext of the View to an instance of a ViewModel object. Well, establishing that connection can be accomplished in a variety of ways. You could do it declaratively in XAML. This is also known as the ViewFirst approach, meaning that the View is responsible for instantiating the ViewModel. Using this method, you create an instance of your ViewModel as a resource and use the static resource binding syntax to set the DataContext of your View. Now there are a couple of drawbacks to using this approach. One is that you cannot control the instantiation of your ViewModel, and two, you cannot pass parameters to an overloaded constructor. Because of these limitations, I find it difficult to use this approach when building anything except a Hello World demo application. You could do it imperatively in Code. In this method, the ViewModel is created and assigned to the DataContext of the View in the View's code-behind, normally in the constructor of the View after the initialized method or in the View's loaded event. Using this approach, you can now control the instantiation of your ViewModel and you can also pass parameters to an overloaded constructor. Now some of the MVVM purists out there may argue with you that you now have code in your code-behind and it shouldn't be there. My response to that is, if you're comfortable with code in your View, well then that's perfectly fine. Remember, my view is that Patterns are just a starting point and they are not gospel on how you have to follow everything to the T or your application is not going to work. You could use a ViewModel Locator Pattern. This is actually pretty popular in a lot of the MVVM frameworks that are out there. Basically this is the Service Locator Pattern renamed for MVVM purposes. The basic idea of the ViewModel Locator method is that you have a class that contains references to all the ViewModels in your application and it encapsulates the logic to locate and create them and you can intermix that with IoC and things like that. You can use Data Templates, Inversion of Control, I just mentioned, or you can go crazy with it and do a Factory Pattern with Inversion of Control. You can have the factory responsible for creating an instance of your ViewModel, an instance of your View, and then setting the DataContext in there, and you can use Inversion of Control to create those instances for you. I guess what I'm trying to get at is there are many, many ways to create the binding between the View and the ViewModel. All I can do is suggest that you use your favorite search engine, try to find the approach that fits your programming style and your application's needs. Communication Between the View and ViewModel As mentioned before, communication between the View and the ViewModel can be accomplished in a couple of different ways. The two most common approaches are by using Events and Commands. Commands are similar to Events, except you can associate any number of UI controls or input gestures to a command and bind that command to a handler that is executed when controls are activated or gestures are performed. Commands also keep track of whether or not they are available. If a Command is disabled, all UI elements associated with that Command are disabled as well. The code that executes when the Command is invoked will be located in the Command's Execute Event Handler. The code that determines if the Command can or cannot be invoked will be located in the Command's CanExecute Event Handler. Demo: Communicating with Commands I'm going to put my designer hat on one more time and say that I have another requirement I just got in, so I take my View and I have just learned that this button is going to execute a Command, and that Command is going to exist on my ViewModel and it's going to be called SavePersonCommand. So right now if I were to run this and I do not add that command to my ViewModel, we would expect a BindingExpression error and that is exactly what we get here, BindingExpression path error, SaveCommand property not found. Well, of course, because we haven't added it yet, but that lets me know that that button is looking at the ViewModel for a command called SavePersonCommand. So let's go ahead and open up our ViewModel, we'll close our View. And instead of creating another class, I'm just going to go ahead and stick it at the bottom in this ViewModel and I'm going to create a command and I'm just going to name this SavePersonCommand. And this is going to be of type ICommand, it's going to inherit from ICommand. It has to implement the ICommand interface in order for the button to execute it. Now we're going to need an Action. This Action is going to be what executes when the button is clicked. We'll just call that executeMethod. The CanExecute tells me if I'm even allowed to execute this Command, yes or no, true or false. For demo purposes, we're just going to say anyone can update this Command. If this was false, the button would be grayed out, you wouldn't be able to push the button. Now, I'm going to take my executeMethod and invoke it. I've created a simple Command, but now what I have to do is I have to create a property on my ViewModel that exposes that Command. So we'll just say public ICommand and we'll call this SavePersonCommand. Of course I want to put my OnPropertyChanged on here and this is called SavePersonCommand. Well, we're not quite done yet. Now we have to create an instance of the SavePersonCommand. So let's go ahead and create a method called InitializeCommand and we'll just put it down here. And all this Command does, it says SavePersonCommand = new SavePersonCommand, and we're just going to call that UpdatePerson. The UpdatePerson method is going to be the Action or Method that is invoked when the Command is executed. So let's go private void UpdatePerson(). And all we're going to do is set the ModelPerson.UpdatedDate to this very instant. Now this line is complaining because I have not yet created a constructor that takes a parameter, so let's go ahead and do that now. I'm going to go ahead and declare my constructor and I'll just do it right under here. I'm going to say the _executeMethod = UpdatePerson; and of course, this has to be an Action. Alright, so now we're all squared away. We have created an instance of a SavePersonCommand, we have an Action that will execute when that Command is fired from the UI, and all it's going to do is update the ModelPerson's UpdatedDate and then we should see that value reflect back into the UI. So now if I run this, what should happen is when I click this Save button, this last UpdatedDate should modify to the current date and time, and it does so as expected. And if I wait a few more seconds and click again, the time changes. So every time I click this button that SavePersonCommand executes, which then executes our UpdatePersonMethod. So now that we have our demo application completed, I want to point something out. We have all that functionality without a single line of code in our code-behind. All our logic is separated out into this ViewModel class, which exposes our Model class's properties and exposes Commands to help interact with the View. Collaboration Now this may be a little bit of a review, but now that we have an understanding of each of the different components of the Model-View-ViewModel triad, let's discuss a little bit of how these different components collaborate with one another. The ViewModel is responsible for the state and behavior of a View and it acts as a façade to the underlying model. Think of the ViewModel as the middle man between the View and the Model. It is responsible for sending Model information to the View and View information back to the Model. The ViewModel is nothing more than an abstraction of the View's code-behind except that the ViewModel has no hard dependency on any View. This makes it possible to reuse a ViewModel across multiple Views and even multiple platforms. The View binds to properties on a ViewModel, which in turn exposes data contained in Model objects and other state that are specific to the View. The bindings between the View and ViewModel are simple to construct because all you have to do is set the DataContext of a View to an instance of a ViewModel object. I want to reiterate that your ViewModel must implement the INotifyPropertyChanged interface because if property values change in the ViewModel, those new values will automatically be propagated to the View via DataBinding, and that will only happen if your ViewModel implements the INotifyPropertyChanged interface. When the user clicks a button in the View, a Command on the ViewModel executes to perform the requested Action. It is the ViewModel, never the View, that performs all modifications made to the Model. Consequences So what are some of the consequences we see when we use the Model-View-ViewModel Design Pattern? Well, for one, we reduce code-behind. By abstracting the View out into a ViewModel we eliminate most, if not all of the View's code-behind. The Model doesn't need to change to support a View. We can create a new ViewModel or modify an existing one to present DataPoints to the user differently depending on application and requirements. Designers get to design, Coders get to code. This supports simultaneous development. While designers are creating Views in rich user interfaces, the programmers are writing the core code and business logic. This also reduces development time because the work is being done simultaneously. Of course, using the Model-View-ViewModel Pattern, you have to create more files. This bothers some people more than others. To me, I think it's a great way to help keep my project organized and structured well. Simple tasks can be complicated to perform, such as setting focus to an element in the View. There's a lack of standardization. But I really don't see this as a con, but I listed it as one due to the feedback I have received from the WPF and Silverlight community. My view is that the MVVM Pattern is just that, it's a Pattern. It's just a set of guidelines to help facilitate abstraction in my applications. You could almost consider this a positive since the Pattern is flexible enough to meet anyone's needs and can be implemented in so many different ways. And, once again, I've mentioned this a few times, but it is specific to the WPF and Silverlight platforms. I guess if you weren't using this Pattern in a WPF or a Silverlight platform, you would be calling it the Presentation Model. Known Uses If you're interested in who is actually using this Pattern, just to name a few, Microsoft uses it internally for some of its applications and it was used in building Expression Blend. The UFC, otherwise known as the Ultimate Fighting Championship Gym, uses it for a membership access support system they have. The US Army uses it for a resource allocation system. There's a couple of free applications available for download. You can actually get the source to Family.Show and the PRISM Reference Implementation, as well as AQUA. AQUA is a CodePlex project with SourceCode, it's basically a healthcare CRM reference application. There are also many MVVM frameworks out there. Some of the popular ones are the MVVM Light Toolkit, you've got Caliburn, Cinch, Onyx, and the MVVM Foundation. Of course, you can hit up your favorite search engine and find more out there, there's plenty of them. Related Patterns Here are some of the related patterns to the Model-View-ViewModel Design Pattern. These Patterns, like the MVVM Pattern, are considered a View Separation Design Pattern. We have the Model View Presenter, the Model View Controller, both of which we will have modules in our on-demand library so you can learn more about those. And then I've already mentioned and described a little bit about the Presentation Model. For more information on that you can go to Martin Fowler's website or just hit up a search engine of your choice. Summary To summarize, in this module we looked at the Model-View-ViewModel Design Pattern and how we can use it to leverage core features of the WPF and Silverlight platforms to help separate the concerns of a View from its state and behavior. We saw that by separating the state and behavior from a View, we were able to make our code more testable and more maintainable. We also discussed a couple of different ways of how to create the binding between the View and the ViewModel. We also learned how to implement this Pattern by writing a simple demo application. This is Brian Lagunas, and I hope that I've given you enough information for you to be able to use the Model-View-ViewModel Design Pattern in your app. Null Object Pattern Introduction Hello this is David Starr, and in this module we're going to be looking at Null Object Design Pattern. I personally have found this pattern to be very helpful in making my code just cleaner and easier to read, and I can tell you that we use this pattern extensively in the website and we've found that it just really helps our code be more maintainable. Motivating Example Now the Null Object Pattern directly relates to how we program in defense of null references in our software. And there's a wonderful quote from Sir Charles Hoare, the inventor of Quicksort, he was a Turing Award Winner and is currently a Microsoft Principal Researcher. Well in 2009 at QCON he gave a talk in which he detailed the inclusion of null references into a programming language as his billion-dollar mistake, meaning that he included null references in languages that he was developing in 1965, and as a result all of the code and defects that have resulted from that have easily added up to a billion dollars worth of time and coding effort. In fact, most of us are so engrained to deal with null references, that we just do it as a matter-of-fact part of how we develop code. Let's take a look at what I mean by that and how it looks in code to code with null references in mind. Demo: Example 1 Now here's a brand-new command line executable program generated from just saying New Application in Visual Studio. This is exactly what you get when you create a new console application from scratch. Now interestingly, we already need to be thinking about null references. We take on the entry point method an array of args that may have been passed on the command line. As you may know, if I try and reference one of the arguments, even though it's not been passed, I'm going to get a null reference exception, because the argument's array has not been initialized. This is classic null pointer problem. In fact, it's so pervasive that I use this product ReSharper when I code, and it has a built-in ability to check parameter for null. So the first thing we do as part of our application in many cases is check to see if the incoming arguments are null. And if they are, we're going to throw an ArgumentNullException. This type of code can end up littering our Source Code, such that it's almost hard to tell what's actually supposed to be occurring within the function. We're spending so many lines of argument checking up near the top to make sure that we're not getting null references. Demo: Example 2 Here's a bit more complex application, and what it does is news up an automobile repository. We can think about this as our Data Source of automobiles. And then gets from it a list of all automobiles named Ford from within the repository. Notice in this coding style I'm not paying attention to whether or not my Automobiles collection or my Automobiles list is null, and that's because we sort of have a convention within .NET where we agree that rather than passing back a null if I find nothing, in this case, I'm probably going to pass back, instead, a collection or enumerable or some sort of set that doesn't have any members in it. Therefore, when I call foreach and I actually walk across all the members of the set and invoke operations on them, there's actually nothing in there and so I don't have a problem calling foreach on the set. If the reference of Automobiles, if the Automobile's set was null, then I would get a null reference exception here. If I call this on the command line, let's pop over to the command line and we'll run our application, I'm not going to get anything back from the call where I look for Ford Automobiles, but at the same time, my foreach is able to execute cleanly because I'm receiving an array or set of some sort that doesn't have any members in it, yet the set itself has been initialized. We can look at what type this is. This is an IEnumerable of IAutomobile, and this IEnumberable of IAutomobiles has been initialized properly, it just doesn't have any members. So the whole idea around the Null Object exception is why can't we treat individual objects the same way we treat this empty collection or this empty IEnumerable. If I were, instead, to put in code like this, wherein we ask for a very specific automobile to come back. This happens to be the ID of the Mini Cooper within the autoRepository. If we ask for this particular vehicle or this particular IAutomobile to come back, then we do need to check it for null before we try and invoke any operations on this object. Let's take a look at what happens when we compile and run the application in this state. The Mini Cooper was in there, so we got a result back, and we were able to invoke Stop and Start on it. Now if we change our number here or our identity, and do a Recompile, and pull out our null check, run our application, we get a null reference exception. So this is the kind of code that we would like to avoid having to write, all these little null checks that we might have in our code base. Intent As we've already discussed a little bit, the intent of the Null Object Pattern is to rid our programs and our code and all of those entry points into our methods of these null checks where possible. Now I'll admit, it's not always possible, and we do still have null checks in our production code, because we can't always use this Null Object Pattern. We have to identify exactly where we're able to do it. Now the idea is that we're going to provide an object, an instantiated, yet nulled object in place of a null reference. So when I asked for the Mini Cooper, instead of getting back an IAutomobile that equated to null, I would get back an object that would represent the state of a null automobile, and it has no implementation. Therefore, we can go ahead and safely invoke operations on that object. So, we provide an object that has no functionality, and this allows us to actually invoke those operations without worrying that we're going to cause a null reference exception. Applicability Now as I mentioned, we're unable to use this pattern all the time to replace every null check in our software, but when is it most applicable. Well, it's most applicable when we want to shield our client from needing to handle a null case, so that we can provide a null implementation and not have our client worry how that's actually implemented. This is especially valuable when the object that we're returning to the client requires some sort of collaboration with another object. A really good example here is in the use of the Strategy Pattern. You can look that up also in the Patterns Library here at Pluralsight. The Strategy Pattern uses an object passed into another object that it will then execute the object that was passed in. Sometimes we don't want anything to happen so we might provide a Null Strategy Object. That is, a Strategy Object that doesn't have any implementation, so that we could go ahead and call Execute but that nothing would actually occur as a result of making that call. Same thing when we look at a Command Object. Also, the Command Pattern is available in the Pluralsight Library and you can take a look at that. So when we have an object that requires a collaborator, meaning that another object is going to invoke an operation on it and we know that, then we can provide a basically, do-nothing implementation of the object that we're providing to that collaborator. We've also found it very useful to provide null implementations or do-nothing implementations of entities that would be returned from repositories, as we'll show in a little bit. Also Known As The Null Object Pattern goes by a few other names as well, some less known, but it may be referenced as a Stub, as the Active Nothing Pattern or as an Active Null Pattern. And that one sort of makes sense because this is an active object, it's not really null, but we want to treat it as though it were. The Null Object is also considered a special case of an implementation for the Strategy, the Command or the State Pattern, and there are others where the Null Object Pattern comes into play, but the idea in all cases, is that we can provide a do-nothing implementation, known as a Null Object, and invoke operations that effectively do nothing. Structure Now here's a very simple class model of how the Null Object relates to the client that might be using it. So we have a Client Object here that through some mechanism gets a reference to an Object. This object is defined through some sort of abstract Base, maybe it's an interface, it could be an abstract Base class, but there is a Method typically or Property, something like that, on the base object that will be invoked. If this is a real object, then the result of executing this operation will do some real work within our system. However, if this happens to be a Null Object received by the Client, then invoking the do-something operation simply has no effect. Interestingly, it's sometimes necessary to have multiple Null Objects to represent different types of Null States. In other words, when I invoke a do-nothing operation in the context of this Client, it may have a different connotation, it may have a different intent, than invoking do-nothing from a different Client. And because of that, in some cases we'll find programs that have different Null Object implementations of these same Base object or interface, intended for use in different scenarios. Demo: Implementation Example Here we have an example of a program that is using the Null Object Pattern. The AutoRepository is being asked to find a vehicle with the keywords of mini cooper and it returns an object that derives from AutomobileBase. This is an abstract Base class that we'll take a look at in just a moment. The fact that we're using the Null Object Pattern means that I can invoke Start and Stop operations regardless of whether I got a hit, or rather a result, on the Find operation of the repository. So in this case we're looking for a mini cooper. Let's do a build and we'll hop over to our command line, invoke our application, and in this case we did get a mini cooper back. We can see that we called Start and it started. We have 1.6L of raw power ready to go. And then we called Stop, the mini cooper was then stopped. Now if we change this to look for another automobile, let's say a BMW and do a recompile, rebuild, and run our application again, we see that we did not find a BMW in this case, and as a result calling the Start and Stop operations had no effect because we had a reference to the Null Object implementation of our AutomobileBase class. Let's take a look at how that's actually achieved. We'll take a look at our Automobiles folder here where we have a class for AutomobileBase.cs. This is our abstract Base class, which looks a lot like we would expect an interface to look. We're not providing any concrete implementations in here, that just happens to be the way this particular Base class is implemented. So the idea here is that I'm going to have a class like this one, like the Mini Cooper and the BMW class that will implement or derive themselves from the AutomobileBase class. Where this gets a little bit special is down here inside this region where we've included a singleton reference to a NullAutomobile class. So here's our nullAutomobile type and it happens that this is declared as an internal class to my abstract Base class. Now this is not necessarily required for implementing this Null Object Pattern, but it's very common to include a singleton reference to a Null Object on the abstract Base class. This is the reason this is an abstract Base class instead of an interface. And the reason we include this here is because we can always now reference AutomobileBase.NULL through this member, which is the NullAutomobile singleton. And we'll see how this looks in use by the repository in a moment, but when we implement our NullAutomobile, note that it derives simply from AutomobileBase, like any other object, any concrete object will, our MiniCooper and our BMW334XI will do the same. It provides its own implementation of everything that it needs to provide, so in this example it's going to provide an empty Guid for ID, it provides an empty string for Name, and you can see that the Start and Stop methods quite literally do nothing. Now you can see from this implementation that this pattern isn't going to be applicable to all objects, but where it is applicable it works quite well. Over in our AutoRepository, we can see that we have a very contrived example here of what a Find operation on a repository might do. In this case it's going to look to see if we passed in the word mini, if we did, return a new MiniCooper, otherwise, return a NULL. This is merely simulating real application logic that would obviously be more complex, but what we note here is that the repository is able to reference AutomobileBase.NULL and simply return that singleton, and now we have only one instance of a null AutomobileBase running around inside of our application. And this just is a very common way to implement this pattern, although as I say, you don't have to include your Null Object implementation on your Base class, it just turns out to be quite handy to do so, so that we can then write code that always knows where to check for equality. It checks for equality here on the AutomobileBase, and that's because sometimes, even though we're able to safely invoke Stop and Start, we may not be able to safely do that. We may, indeed, need to check to see if our automobile is equal to our AutomobileBase.NULL type. If that's the case, we may want to take some other action as opposed to invoking the do-nothing operations. Here's a quick model of the actual implementation that we had. In our example, we have our AutomobileBase Class here and it contains a Nested Type, an inner Class of NullAutomobile. This NullAutomobile Class is exposed via the Null Property of the AutomobileBase Class, and then we also had our Concrete Classes, our miniCooper and our BMW335XI that implement their own IDs, Names, and Start and Stop operations. Consequences Now what are some of the consequences of using the Null Object Pattern? Hopefully you agree that the code we just saw ends up being a bit cleaner, more concise, and obviously has fewer null checks necessary in order to invoke operations against objects that may, in fact, be null. One interesting side note of this is that since we're not doing these null checks where we say if Object equals null, then take some corrective action like throwing an exception, our cyclomatic complexity measured against our methods actually goes down, so our complexity and maintainability are improved using this pattern. Our callers don't need to care about whether they have a Null Object or a real one, obviously, and one thing to be aware of, this is sort of a negative thing, is that we must be aware that those Null Object implementations exist, right? So if we have multiple people on a team and we're sharing a code base, if I'm unaware that those Null Object implementations exist, I may still do null checks in my code because I simply don't know that the team is using this particular Design Pattern. Notes and Related Patterns Here are some final notes on implementing the Null Object Pattern. We saw that in some cases, many cases, the Null Object is implemented as a singleton on the Base class for which it represents null. And one very good reason for doing this is that our behavior or state conditions don't vary over various instances of NullObject. If we have multiple NullObject instances running around inside of our software, they may in fact be different, so the singleton gives us a way to prevent that from occurring. Now the multiple instances would be identical in their implementation, perhaps, but we wouldn't be able to do equality checks on them unless we did something like implement an IComparable within the NullObject itself. So this is just an easy way to provide that capability. This also means that our do-nothing code or our NullObject code is centralized in one place. We can always depend on where that logic is going to be represented, it's going to be in that singleton. And interestingly, we alluded to this that the definition of do-nothing can be different in different circumstances. So sometimes it can be difficult to implement if all of our callers don't agree on what that "do nothing behavior" should be. So in those cases, we'll often not see our NullObject represented as a singleton because there will be multiple instances of NullObjects. And finally we saw that sometimes the calling code does, in fact, need to know it has a NullObject. In that case, it's awfully handy to have that singleton hanging off of our abstract Base class that gives us an opportunity to check for equality on that comparison. Other patterns that relate to the NullObject Pattern include the Singleton, as we discussed a bit earlier, the Strategy and Command Patterns, and you should be able to learn more about these in the Pluralsight Patterns Library as well. Summary In summary, we saw that null references really are quite a problem in our modern software and that NullObject can often stand in for RealObjects, mitigating all of that checking that we might do because of NullObject references. We also discussed a few other patterns that can benefit from the use of NullObject implementations like Strategy, Command, and State. I hope this helps clean up a little bit of the code that you have to work with on a daily basis, and again, we have found this pattern to be instrumental in helping us write cleaner, more maintainable, and more easily understood code. Thank you very much. This is David Starr and I hope to see you in class sometime soon. Observer Pattern Introduction Hello. This is John Brown, and in this module from our Design Patterns Library we will be looking at the Observer Pattern. This pattern is widely used in software development and may be used in some places that you may not be aware of. To get an understanding of when to use the Observer Pattern, we'll take a look at an example where we can apply the Observer Pattern to make the code more in alignment with the solid principles. I will then introduce you to the Observer Pattern and we'll talk about what makes up the Observer Pattern. We'll follow on by discussing three variations of the pattern starting with the traditional version that was documented by the Gang of Four in their Design Patterns book. We'll also look at Events and Delegates, the bread and butter of the Observer Pattern in the .NET framework. And we'll take a look at a new implementation of the Observer Pattern that was added to the .NET framework in version 4. Finally, we'll talk about some real world examples and some of the pitfalls to avoid when interacting with them. So when do we want to use an Observer Pattern? As the name implies, the Observer Pattern is useful when one object is dependent on the changes in another object. Instead of periodically checking to see if the object has changed, we would only like to be notified when it changes. We also look to the Observer Pattern when we do not know how many other classes or instances are monitoring the changes to the object. And probably most importantly, when the concerns of one class or instance are unrelated and/or need to be hidden from the other classes or instances monitoring the object, we can implement the Observer Pattern to handle the communications independently. Motivating Example If we take a look at this sample application, we see here that we have a sample stock ticker that's monitoring various stocks and performing actions based on those stocks or conditions within those stocks. So if we take a look, we see here that at the beginning we are reading in stock data that's coming from the SampleData, and we're looking at each stock as it comes in, just very much like a stock ticker. We're also looking at it to see and report on Google's price as it comes in. Anytime the Google price changes we're going to reflect that, and we also have an evaluation of the Microsoft price to see if it reaches a target price, which is indicated here. If we go look at the SampleData, we can see here we have stocks and their prices. We have Microsoft at 10.00, $10.25, Google at 555.55, and then Microsoft drops back down to 9.50, 9.03. so this is simulating the stock ticker. If we go back to the program, what we can see here is that several different things are going on. When we're looking at simply the monitoring of the stock ticker, this by itself doesn't need to know anything about what is being monitored for each stock. It doesn't need to know about the Google price, it doesn't need to know about the Microsoft price to do its job, it simply needs to read the stock and report on it. In this case, also, we have the Google price, which has nothing to do with the Microsoft price. These are independent activities that are occurring all within the same program. If, for some reason, we would like to add a new monitoring, we would actually have to come in and modify this particular application and take a look at what it's doing. So maybe we need to look at Exxon Mobile and report on that price. So what we have here is the requirement that anytime that we want to take a look at something different, we actually have to modify the main application. What the Observer Pattern will allow us to do is to take a look and see if we can separate out each of the monitoring aspects or the Observers and the Actions that they're taking from the data that is being reported by the stock ticker. If we take a look at running the application, we can see that it's going to report back that the Microsoft price has reached its targets of 10.25 and 10.10, and then we would see all the Google price changes as it goes through. Introduction to the Observer So how can the Observer Pattern help us? Well, we have to look at the intent of the Observer Pattern. One of the things we're going to do is try to adopt the concept or the principle of Separation of Concerns. We really want to separate the subject or the stock ticker from the Observers or the Microsoft and Google Observers that we saw. We also want to make sure that it's easy to add multiple Observers to react to changes in a single subject. Well how do we do that? Well, the structure of the Observer Pattern is to provide a way so that we can separate out the subject, which would be the stock ticker in this case, and the Observers, which is the Microsoft and the Google Observers, and to do that what we need to do is have the subject provide a way to register and unregister Observers. In addition, we need to allow the subject to notify the observers when a change occurs. And then conversely, we need to have the observers provide a way to allow the subject to notify them of the updates. So essentially what will occur is the subject or the stock ticker, in this case, will push notifications to update to the observer whenever a change in the subject occurs. The observer, on the other hand, will both read and set states on the subject. However, because there are multiple observers, if observer 1 reads and sets the state, then observer 2 will receive a push notification of the change. Traditional The traditional approach as laid out by the Gang of Four is to create an abstract subject and an abstract observer. The abstract subject provides the mechanism to allow the Registration and the Unregistration of observers. It also provides a notification mechanism. The abstract observer, on the other hand, provides the blank implementation of the Update method, but does not provide any of the concrete implementations. If we look at the concrete subject, in this case it's the stock ticker, we see that we have attributes of the stock ticker of stock and the operations of the constructor. We then have two classes here, the GoogleObserver, which provides concrete constructors, a reference to the DataSource, or in this case the stock ticker subject and the method for updating. The MicrosoftObserver has the same operations. Demo: Traditional If we look at the traditional implementation, you'll see it looks a little different now. Our main program has none of the actual logic in it anymore. What we have here is we have the constructor of a simple StockTicker, which is our subject, and we've created two observers, the GoogleObserver and the MicrosoftObserver, that are taking in the subject of their observations. And we simulate the StockTicker by loading up data and setting the change in the stock on the subject. If we go and look at the AbstractObserver, we see the AbstractObserver just has an abstract method for the update. We also see that the abstract subject has the logic in it to register new observers, remove them, and then cycle through each of the observers during a notification, to let them know that a change has occurred. The concrete implementation of the GoogleObserver takes in the StockTicker and sets it to the DataSource, and also registers this observer with the subject. We then see during the update that we override the update and we see that it takes in the Symbol and the Price from the DataSource, which is the StockTicker, and then processes that. It performs the same action that we saw before. All of these activities that occur within this class are all related to updating and providing information for the Google stock. It has no reference to the Microsoft stock, nor does it have a reference really to the StockTicker, other than the fact that it is the source of the data. We look at the Microsoft version and it has the same aspects, except that it is specific to the Microsoft stock. The StockTicker application itself is simply repository for a representation of the latest and most current stock that comes across the StockTicker. In this case, we see that you can return the stock. You can also set the stock, but when you set it, it triggers a notification to all of the observers that the stock has changed. If we go and run this application, we can see that it returns the same result as the original implementation except now we have a separation between our different concerns. We've separated the subject from the observers. Consequences So what are the consequences of using this approach? Well, if we need to track multiple subjects for each observer, we're going to have to actually take a look at passing the subject to the observer so it knows which one of the subjects was doing an update. We also need to take a look at, what about triggering the update when multiple properties are involved? If I had separated the stock price from the stock symbol, and had updated them individually, I would have had to track the fact that I might be updating one value and not the other, or I might be causing double updates when both properties were updated at the same time. We also have an issue when we decide to dispose a subject or an observer. Because they have references to each other, those references can be held and can prevent the garbage collection of those objects. When we're dealing with mapping of the subjects to their observers, we also incur a memory overhead, that depending on the number of observers for a subject, can get quite large. So, unexpected updates can occur when we have multiple observers, and a single change to the subject by a single observer that may be small to that one observer, may cause a ripple effect through the system where all of the observers are now being updated, and the overhead of those updates can be quite large, especially when there's a large number of observers. If it's only 2 or 3 observers, we probably will never notice, but if we have thousands of observers, a single change from one observer to the subject may cause a lot of activity unexpectedly. And finally, in this approach, in the traditional approach, we're really looking at each of the properties of the object as one large object, one item that we are tracking whether or not a change has occurred. But what if we wanted to look at each property individually and track each of the different properties separately. For example, maybe we would like to know when the Symbol of the stock changes, separately from when the Price of the stock changes. This approach would require that we would need possibly multiple implementations of the Observer Pattern and the Pattern exactly support this. In this case, the StockTicker inherits from one AbstractSubject and the observers that inherit from one AbstractObserver, and there really is no mechanism to support tracking multiple aspects of each of the subjects in the observers. In the .NET framework, this has been addressed through events and delegates. Events and Delegates The same pattern can be implemented using the .NET framework without abstract classes. A built-in feature was created specifically to implement the pattern. Events and Delegates provide the language feature to support the Observer Pattern. The Event is created on the subject and allows for the Registration of observers through a Delegate Callback mechanism. The observers provide Delegate method implementations that will be called by the subject when the Event is raised. We see that here in the StockChangeEvent on the StockTicker class, where we have an EventHandler that's passing StockChangeEventArugments. On the MicrosoftMonitor and the GoogleMonitor we see that there is a MethodHandler that's picking up the StockChangeEvent through the Callback mechanism. We even can have specialized EventArguments such as the StockChangeEventArgs that can pass the additional Stock information to the Method Callbacks. This is done to handle the multiple properties and multiple subjects problem where we're not sure what has changed on the subjects and this provides a way to communicate those changes to the monitoring classes or the observers so that each of the observers can make the appropriate modifications based on the data without having to re-query the entire StockTicker or multiple subjects for that information. Demo: Events and Delegates If we take a look at the event-based implementation of this, we see here that we still have the same property holding the Stock. We also have something new here, which is the Event. This is our mechanism to register the observer. We also have the equivalent of the Notify, which is the OnStockChange method that is called by the Stock setter. So whenever we set the Stock, the OnStockChange method is called, passing the new StockChangeEventArguments and the current value of the stock. This then checks to see if there are any observers associated with the StockChangeEvent, and it will call each of the observers, passing in the subject, which is this, and the event arguments, which will hold the data of what has changed. If we look at the observers, we see here that we have the equivalent of the Register Event being called here in the constructor. In this case it's using the symbology of the += to add the new EventHandler or the Callback, the delegate Callback, to the StockChangeEvent. It's passing in the method to be called, which is this one down here, which will be picking up the sender or the subject in this case, and the arguments of the change, which is what has been modified on the subject. Then it calls the appropriate evaluations like we had in the original implementation. What's important to note here is that we've solved two of the issues that we had talked about earlier. One was the fact that now I have a stock and it is throwing an EventBaseChange, but I can also add multiple EventHandlers. I can add a new one, which is maybe SymbolChange or ExchangeChange, and I can have another event, or another property rather, which is the Exchange, string Exchange, and I can then wire up its own event and provide its own implementation of an ExchangeChangeEvent. We can catch that on each of the observers. Let's take a look at how we would run this. If we take a look at the execution, we see the observer and we see the results are the same. If we look at the program we see that it's very similar to what we had before. We create a new StockTicker, which is our subject. We associate observers with that StockTicker by passing in the StockTicker as part of the constructor, and we load up sample data to process through the StockTicker. IObserver The third implementation of the Observer Pattern is new to the .NET framework. It's called the IObserver. The IObserver was added to the Base class library and it was previously a part of the reactive extensions to the .NET framework. It was done to support some of the new features such as the task parallel library. Now if we look at this, it has a very similar look to the traditional approach. Instead of having an abstract Base class for the subject, we have an IObservable and instead of having an abstract Observer class, we have an IObserver. In the concrete implementation we have a few things that are different. We have the standard subscription to register the observers with the subject, and we also have the notification, so that we notify the observers when something has changed, but on the concrete observers we see that we have three methods instead of one. We have the standard update method, but here it's called OnNext, so we're getting the next value from the subject. We also have the OnError method that is called when there is an error in processing the changes to the subject. And we also have the OnCompleted method, which indicates that there will no longer be any changes to the subject. Now why are these different? Well, it turns out that we're solving a little different problem. The Observer Pattern turns out to be the dual of the IEnumerable Pattern. So what does that mean? Well, if we look at the IEnumerable Pattern, we see that the IEnumerable allows us to pull items from a collection and to process them in an environment. So our application or our program will typically query from the IEnumerable collection and get an enumerator and pull items that we would wish to process. Whenever something changes to the environment, so our subject per se, we wish to push those changes to observers who will react to those changes. We can see the duality here. They look very similar in the sense that IEnumerable we get an enumerator, and we return an IEnumerator. It has a couple of methods on it called MoveNext and Current. The equivalent over here is the IObservable, in which case we can subscribe to the IObservable and we're returned an IDisposable object. The Observer has the methods we talked about earlier and so they have a very similar look and feel in how we use them. So what does our code look like? Demo: IObserver If we take a look at the program, the program looks pretty much the same. We're creating the StockTicker again. We create Monitor classes or observers. In this case we are not passing in the StockTicker. All of that is taken care of when we subscribe in the StockTicker, the Monitor. Notice though, we're using, using statements. The using statement are interesting. One of the problems that we had talked about earlier with the Event and Delegate Model was that often we'll forget to release an observer from a subject properly. So the observer goes out of scope, we think we have destroyed it, and we think garbage collection is going to pick it up. However, because there's a reference from the subject to the observer, the observer is held for a long time. We end up having what is called dangling events. By implementing this Disposable Pattern here, where the Observer, instead of providing a Subscribe and Unsubscribe method, is actually providing an IDisposable object when you Subscribe, allows us to keep track of that Disposable object and release it when we're no longer using it. So what does the actual observer look like? Well, the Observer looks very simple. In fact, all we have is three methods. These are the methods that will be called when we are getting an update from the subject. In this case, we're also passing the actual subject that's changing. We're also going to get any Error messages. We'll get, in this case, an Exception that has occurred because of the update to the subject. And when we're done updating the subject, we'll get an OnCompleted Event. If we look at the StockTicker itself, this one's a little bit more complicated, but we can also have wrapped this up into a Base class that we could modify particular to our needs. We had the standard property that we were holding our stock information in, and we're also holding the Notify method, and whenever we update the stock we trigger the Notify method, but in this case the Notify method will also take a look and provide Error indications. So, for example, we're going to cycle over each of the observers that we've registered through the subscription method. We're going to check to see if there's an error either in Price or in Symbol, and we'll throw an Exception with some details about why there's an error. Or we'll return the value of the updated stock as a call to the OnNext for each of the Observers. The Subscription looks a little different because instead of making a simple Subscription, we take in the IObserver, IObserver, which is the observer. We add it to our collection of Observers here and instead of returning a Void, we actually return a new object, which is the Unsubscriber of the observer from the observers collection. Now this clearly can be put together in a Base class library. We have a local variable holding the reference to the observers and the observer. And we have a constructor of the Unsubscriber. And then we use the standard Dispose method to actually check to see if the observer is in the collection and remove it if necessary. So what does this program look like? Well, when we run it, it will actually return the exact same results. Real World Examples So where are we going to see the Observer Pattern in use? Well, we're going to see it all throughout the .NET framework. If we take a look at any kind of implementation of, say, GUI Controls, we see that they use the Event and Delegate model throughout the application to wire up the GUI Controls to the EventHandlers on the Forms. Data Binding, as well, uses the EventHandlers and Event Delegate Callbacks to update the values of any of the Controls when a change to the DataSource occurs. You're also going to see it when we look for things like the network availability Events and the File Watcher Events. These are system level objects that we can monitor so that when a change on the file systems or in the network, we can react to that change appropriately. Now when we deal with things that are outside of our application or coming from the system such as the Network Events and the File Watcher, we need to start thinking about things like the Unexpected Thread. The calls from the Network Events and File watchers will not come in on the Main Thread that created our GUI Controls, but rather on a new Thread that is coming in from the operating systems. So because the Thread is new, we have to concern ourselves with updating GUI Controls with a Thread that did not create them, that's a violation of the .NET framework. We also have to be aware of the fact that if we're not going to update GUI Controls directly, we might have Multiple Threads. We will have Concurrency and threading issues. So even though we are creating a single-threaded application, because we are listening to Events that occur externally and we are observing subjects that occur externally, the updates that come will be coming on Threads that we did not create. So the data that they update needs to be locked and handled appropriately or possibly called through a standard Thread invocation to thunk it over to the appropriate Thread. We also see the Observer Pattern in the Model View Controller Pattern that is popular, our model is our Subject. In each of the individual Views, of course, are our observers. We also need to be aware of Memory Leaks. If we do not clean up our Observers and our Subjects properly, we will find that the memory quickly grows out of control. Summary So in Summary, we see that we have taken a look at a sample application called the Stock Ticker where we are looking at stocks that have come across the Stock Ticker and we want to observe those stock changes and react to them in a way that's appropriate, but yet independent of each of the other observations. We do that through Separation of Concerns where we separate the Stock Ticker from the Observers and we separate each of the Observers from each other. We looked at three different ways to do that. We looked at the Traditional way from the Gang of Four and their implementation using abstract classes. We also took a look at the way that it does it in the .NET framework with Events and Delegates, which we'll see throughout the .NET framework and the implementation issues regarding that. And we've taken a look at the new IObserver or IObservable, which is part of the new version 4 of the .NET framework. We also took a brief look at Samples such as the File Watcher and the Network Change, which will trigger updates in the observers, but not on the original threads. And we need to handle the threading issues and other pitfalls that come with them. Thank you and I hope you've enjoyed this module on the Observable Design Pattern in the Design Patterns Library from Pluralsight. The Prototype Pattern Introduction Hi, this is John Sonmez from Pluralsight, and in this module we're going to be talking about the Prototype Pattern. So the Prototype Pattern is kind of a unique pattern. It is kind of hard to find information about the Prototype Pattern, so I'm going to try in this module to really get you a good understanding of what the Prototype Pattern is and when you would use this pattern. It's really quite a simple pattern and I think this is why a lot of people are so confused compared to a lot of the other patterns that are out there. This pattern really doesn't take very much to implement and it seems rather simple, so more of this pattern is about when to use it and why to use it rather than how to use it. So let's go over what we're going to cover in this module. The first thing that we're going to do is we're going to go over the Prototype Pattern. We're basically going to look at from a high level, what is the Prototype Pattern, kind of try to understand what exactly we're trying to do with the Prototype Pattern before we really look at the technical details. We're not going to look at any UML diagrams or anything like that here, we're just going to kind of explain this in layman terms so we can get a good understanding of what we're trying to do. Once we have that done, we're going to go ahead and go to some problems. And the first problem we're going to look at is when we have construction costs for a new object that is expensive. And in this case, we're going to see how we can use the Prototype Pattern to basically reduce that construction cost, and how that solves that particular problem. The second kind of problem that we're going to look at is when State is important, and so we need to get a new object, but we really care about the state of an existing object, and we need to copy that state. And we're going to see how we can use the Prototype Pattern in that case to prevent us having to basically construct an object and manually copy each of the properties of that object. Then we're going to take a look at a third problem, which is hiding a constructor, and this is one of those problems that we might see if we were designing an API or we had some kind of purpose for trying to make sure that someone using our class couldn't get access to our constructor for some reason or other, maybe we're going to change that constructor later. And we're going to see how we can use the Prototype Pattern to basically help us to hide the constructor, but still allow someone to make an instance of our class. Then we're going to go ahead and we're going to go through the design of the Prototype. We're going to look at the UML diagram here. We're basically going to go through the roles, and this is pretty simple, so we're just going to kind of cover from the technical viewpoint of what exactly is the Prototype Pattern. And then finally we're going to look at a few examples. We're going to look at some language examples in JavaScript and C# and Java and just see how different languages are using Prototype Pattern and how Prototype Pattern is kind of baked in to a lot of languages that you might not even realize. Understanding Prototype So let's talk about the general idea of the Prototype Pattern, what exacly is this pattern? Well, the kind of formal definition of the Prototype Pattern that you might see in the Design Patterns Book is to specify the kinds of objects to create using a prototypical instance and create new objects by copying this prototype. So, a lot of words here, but we can break this down and really see how simple the Prototype Pattern. So, we specify the kinds of objects to create using a prototypical instance. So this basically just means that instead of using new, instead of creating a new object, we're going to use some prototype, some existing object, and that's how we're going to specify the objects to create or the kinds of objects. And then we're going to create new objects by copying from this prototype, and that's pretty self explanatory. We're just basically going to have some object, we're going to use that as kind of the master or the prototype, and then other objects that we create are going to be copies of that object, just like cloning, and in fact, in a lot of languages you're going to see the Clone method used in order to implement the Prototype Pattern. So really, when you think about Prototype, you can really think of cloning or making a copy of something instead of newing it up. So let's go through a short kind of dialogue that helps to explain in a real-world example of what the Prototype Pattern is going to do for us. So, I see you have a water bill there. Yes I do. I need my own copy of that water bill. Okay, I'll call the utility service and have them send you a new printed one. Hmm, there must be a better way. No, I don't have the software they use to generate it, so you must get it from them. This does not seem like a really good idea here. You can imagine in a real-life scenario how silly this would seem. If you were wanting to get another copy of a water bill, you wouldn't ask the utility company to send you one because you don't have the software they used to create it. And you can really think of this in terms of programming if we think about creating an object, it's kind of silly that we would have to go through all the steps that have happened so far in the software to create an object. Shouldn't we just be able to see an object that already exists, that already is set the way that we want it, and get a copy of it. So let's take a look at another dialogue that kind of illustrates this point in a real world example. I see you have the water bill there. Yes I do. Can you make a copy of that bill for me? Sure, I'll put it on the copy machine. Cool, now we both have copies. Yes, but you have to pay the bill. So in this dialogue, it makes a lot more sense. This is something that you might actually say in real life. You might really make a copy of a bill. You wouldn't go to the utility company and ask them to create a new one from their system because that doesn't make sense. If you already have a copy of the bill, you can just make another copy, just use the copy machine. And this is kind of the idea of Prototype. And we're going to see in some code examples where this is going to help us, where this is going to make sense to use a Prototype Pattern instead of trying to create that object the way that the first one was created, because if we already have an object, it's sometimes simpler and makes more sense to make a copy of that object than it does to go through the whole construction process again. Problem 1 So now let's take a look at a simple example of a time where we might want to use the Prototype Pattern. So I've created a new solution here, and in the solution it's just basically a console application. And I've created this WebPageScraper class. And if we look at the implementation of this class you can see that it has a couple of data members here and it's got a constructor that takes a URL, and then it's using a webClient to basically download a page that passed in, and Scrape that page. In this Scrape method, we're not really implementing, we're just providing some fake data, but in a real application we could imagine that the Scrape function might go through and actually scrape out that title and the headerTagCounts, and the first headerTagCount. In this case we're just setting them, but in a real example you might have some data that's being Scraped from the page, so we can just imagine that that's happening in this case. Then we also have this method to print the page data. So, let's go ahead and run this and see what we get here. I'm going to point it at So, and one thing that you'll notice is, this is taking a little bit of time to run, it's not instantly returning back. And this is one of the reasons why we're going to actually use the Prototype Design Pattern in this case when we try to make another copy of this. So it's finally come back here and you can see it's taken quite some time and it has basically produced this output here. Now if we want to create another copy of this and we want the same data, maybe we're going to do something with this data. We could basically create a new copy, call it scraper2, and we could do this WebPageScraper. Perhaps this is somewhere else in our application and we can point it at, and then we could do scraper2.PrintPageData, so go ahead and run this. It's going to take some time for this to work, but it comes back a little bit faster here just because the networking stack has already been initialized, but we are going out and we're making that web request twice. We don't really need to do that since we're getting the same data. So one thing that we can do here is we can use the Prototype Pattern in order to make it so that we get a copy of this WebPageScraper, but we don't have to construct it a second time, because really what's happening is in our constructor that's where we are making this call to the WebClient and basically downloading this page. So if we go ahead and use something that's already built into the .NET framework, we just have to implement this ICloneable. So we need to implement one member on here, which is Clone, and the way that we implement Clone is we can just return MemberwiseClone. And what this is going to do is this is going to copy all the data that exists in our object, and it's basically going to create a new object and set that data. Now we have primitive types here. We don't have any nested types. If we had another type in here that was a complex type, like maybe another, like a webpage class that was referred to in here, this MemberwiseClone would not be good enough, because we wouldn't be doing a full copy. What we would be doing is what's called a shallow copy. That's what a MemberwiseClone does is it only copies this data basically bit for bit. And so if we had a reference to another object, it would copy that reference to the object instead of the object itself, which we may or may not want. In this case we don't have to worry. So this is really all we have to do to implement the Prototype Pattern. With this ICloneable and implementing this Clone, we are basically implementing that Pattern. So now in our class, instead of calling this constructor again we can basically do scraper.Clone, and that will give us a second version of the scraper. Now this Clone method is returning an object, so we're going to have to cast this as a WebPageScraper; and when we do this now we should have a working copy of the first scraper, so we should have the same data in there. So I'll go ahead and run this, and you can see it's going to take a little bit of time for the first object to be created, because when it's created it has to go out and get that webpage. But the second object comes back almost immediately, and that's because it's actually just a copy of the first one. So this is one example of a good place to use the Prototype Pattern is whenever you have some object where constructing that object is resource intensive, it's going to take some time or some work and you need a copy of that object. It doesn't make sense to make a new copy and go through that construction again when you just need a copy of it and you can just make a copy instead of reconstructing it. So there's a lot of instances in real applications where you would see this. One place that's pretty common is loading something up from a database. Another here that you can see, this WebPageScraper is kind of going out to the network and it's doing some parsing, so this is definitely one of those places where Prototype is going to get you some benefit. Problem 2 So let's take a look at another example where you might want to use the Prototype Pattern. I've created a class here called LogicPuzzle, and this is a very strange class. In fact, I'm not even sure exactly what this class does. This class basically represents some kind of a logic puzzle. Maybe you've see one of those wooden toys where you have to manipulate that puzzle in some way in order to open some door to unlock something. Well this class is going to represent something like that. We've got a bunch of methods on here. SwitchBlueSwitch, and it checks some condition and toggles the Toggle, increments the move.Count. SwitchRedSwitch checks some other conditions, does one thing in one case, does something in the other case, ToggleBigToggle, ToggleSmallToggle, and all of these methods are really manipulating all of this state here. They're kind of dependent on what the current state is. So this is pretty confusing to figure out exactly what's going on. And then I have a method here to Print the State. So if we look at our program here, I'm creating a new instance of this puzzle and I'm doing a few things here. I'll go ahead and run this. And you can see here what the State is. Now this is a good example of a time where if you wanted to preserve the State, if you wanted to create a new object with this state, well the only way to do that is to basically toggle these Toggles and Switches. We don't really have a method. We haven't exposed any of this for someone to set these directly. Just like a real puzzle, you wouldn't be able to cheat on that. So you can imagine a program that's maybe trying to solve this puzzle. And in that case it might need to have a snapshot of what the current state is, so it might need to basically make a copy of this puzzle so they can try something, manipulate it, and then they can go back to what it was. So in this case, we're going to need to make a copy. And if we tried to just create a new LogicPuzzle, we'd have to kind of go through whatever the state was already to try to get back to that state, and that would not be a lot of fun trying to figure that out, especially if we didn't do this all in succession. In our program, like we did here, maybe the user was controlling the state. Maybe the user was putting in some input and toggling these switches, and so we'd have to try to remember or store every single move that was done. But, if we go ahead and use the prototype Pattern here, we can just make this implement ICloneable. We will go ahead and implement that Cloneable method here, and then we'll do a MemberwiseClone and we'll just return that back. And now if we want to create a second copy of this puzzle, we can just simply do puzzle2, and we'll set this equal to puzzle.Clone() as LogicPuzzle; So now we have a second copy of this and if I do puzzle2.PrintState, we should see when we run this that both have the exact same state. So you can see here, we've got our first instance, and our second instance has the same state, it matches perfectly. So this is a good example. There is going to be some times where you're going to have code that it's going to have a complex state. And anytime that you have a complex state that is very hard to manipulate where you can't directly control that state, there is methods that are really working on that state. Having the ability to clone that object to be able to use the Prototype Pattern is really going to benefit you rather than trying to manually recreate that state, which is error prone and it might even take a long time to recreate. Problem 3 Let's look at one more final problem that we can solve with the prototype Pattern. So I've created a new class here, which I've called ComplicatedUnstableObject. And this class kind of represents an object or a class that you might create that is going to be unstable because you might be changing it a lot, especially the constructors, and fairly complicated, maybe it's difficult to construct this object and there's a reason why you have a large number of constructors and it's part of some framework that you're building. This is going to happen a lot of times when you're trying to make a simple API for users to use your framework or to use some library that you're creating, but internally there's a lot of complexity. So in this case you can see I've basically just set up this class to have a few constructors here that take a lot of parameters, that aren't very well named and could be very complicated to set up and know when to call what constructor. And we don't have any implementation here, but you can imagine that there might be some complex implementation of what these constructors actually do. Now one thing I've done here also is I've marked these constructors as internal, and the reason why I've done this is because if I'm designing an API, I don't want the users of my API to be able to construct this object using these constructors, but I need these constructors because in my framework that's how I'm building this object. So this class is public, so someone can use this class and see this class, but they just can't construct it using these constructors. So this is another place where we could simply use a prototype here by implementing this ICloneable, and using Clone here I can just return MemberwiseClone, and then we're going to return a clone of this object. So you can imagine the user of this class. So if we go in here and we create a complicatedObject, as a user of this class if we had this class packaged in another assembly, we wouldn't be able to do a new here. Because we're in the same assembly, we can go ahead and do a new, so we can create this ComplicatedUnstableObject, but you can imagine that your users or the callers of your class won't be able to do this. So in this case you might just hand them an object that you've already constructed that's the prototype, maybe they have a version of it. And if they need to get another copy of it they can basically just call the Clone method on that object. So in this case, instead of exposing all of this complexity of these constructors your way that you exposed to them for creating an instance of this class, is through this clone. So, you basically provide maybe a reference implementation, you create one version of this where it's already constructed, and then when you hand that to them they can just use Clone to clone this. So, this example is not as common as some of the other problems that you might have, but if you are designing an API or you're trying to simplify things so that it's easy to construct your object, but you need some more complex ways to construct that object, but you don't want to expose them, this is definitely one way that you can do that. The Prototype Design So now let's take a look at the actual technical design of the Prototype Pattern. So this is a UML diagram that you would see perhaps in a textbook or a book about Design Patterns, and this is how the Prototype Pattern is shown and implemented. Now in some of the examples that we've already seen, we've kind of already seen how to implement the Prototype Pattern, but we haven't really given this formal definition of the implementation details. So if you look at this diagram, it's actually quite simple. Prototype is really one of the more simple patterns and that is really why I think it confuses people is because it's so simple that you've already grasped it before you know and so you're looking for more there, but there isn't any more there. So really, all that we have here is we have Prototype, and Prototype is going to define a method, it's usually going to be an interface or an abstract class that defines a method for copying an object. And then we've got some Concrete Prototypes, we can have as many as we want, and the the only requirement here is that they basically implement this Prototype interface, and so that is giving them the ability to copy themselves. They must in some way have a Clone method or a method like Clone that's going to create a copy of that object, and they can do a deep copy or a shallow copy. A deep copy, if you remember, is when you copy everything including the references, so the entire tree. And a shallow copy is when you are just copying one level deep and any references would get that reference copied, so it wouldn't actually create a new copy of any things that object references. And really, that's all there is to this pattern. You just have to have some kind of interface, and then you have to have some objects or some classes that are implementing that interface that allow them to copy itself, and then you've got a client over here and the client is going to use that Prototype interface, it's basically going to use those Concrete Prototypes to copy themselves through the use of the method on that Prototype interface. So let's talk about the roles for the Prototype, and again, it's very simple here, but I think it's worth talking about the names of the actual roles in this Design Pattern so that when someone is talking about this you can immediately recognize who the roles or actors are in this Design Pattern and you can identify that with someone else's code or talk about it very easily. So the first one is Prototype, and we had already talked about this a little bit. It's basically just an interface or an abstract class and the only thing that it really has to do is just define a method for copying an object for doing a clone, and that's really all there is to this. In fact, we're going to see in a little bit when we talk about some of the examples, that this is baked in to a lot of languages nowadays that you can just find this interface already in the language or in the class libraries for that language, and so when you're implementing this pattern you're probably not even going to implement this part because you're going to use this in the language already. The next role is the Concrete Prototype. And really there's just these two roles here. The Concrete Prototype is just a class and it's any class, it really doesn't have to be very specific. You can implement Prototype with basically any class that you have, you just have to implement the interface of Prototype, which is to say that it just has to be able to copy itself. Like we've talked about a little bit before, you can do a deep or shallow copy and that's going to really depend on what you're using the copy for. A lot of times you're going to want to keep this in mind though, because you're going to want to know whether or not you need to do a deep copy. And it's a little bit more work to do a deep copy, so if you can get away with a shallow copy it's definitely going to save you some time and a little bit of headache. Language Examples So let's talk about some examples of Prototype in languages. We've already seen some real-world examples and we've seen some code examples, but I wanted to kind of touch a little bit on examples that already exist and are already out there, that you might not even know you're using and that are built into languages. So the first big example of Prototypes is the entire language of JavaScript. And this might surprise you, but JavaScript is a prototypical language, and what that means is that basically there is no way to create an object that is not a prototype in JavaScript. So in JavaScript whenever you create an object, you're really creating a copy of a base prototype object, and there is an excellent Pluralsight course that covers this and I put the link here. And this course is called Structuring JavaScript and you can find a section on Prototypes in JavaScript in that course. I definitely encourage you to check it out, but the basic idea here is that the whole JavaScript language is based on this concept of prototypes and really it doesn't have classes, and a lot of people get confused when they start learning JavaScript because they want to create classes and they want to do inheritance, and you really have to think a little bit differently with JavaScript in regards to OO programming because you're going to be working off of copies of objects. And this actually allows you to do a lot of really neat tricks with JavaScript. If you think about the libraries that have come out kind of recently in web development like jQuery and backbone.js, some of these things really are taking advantage of the prototypical nature of JavaScript and how you can basically add methods and do a lot of things that having language that is based on prototypes allow you to do. So two more examples inside a language of prototype is in C# and Java, they both have prototypes already, it's already built-in to the language, this Design Pattern. So in C# we've kind of already seen this already, but you have this ICloneable interface, and so if you implement this interface you're basically saying that you are implementing the Prototype Pattern, that this object can be cloned, it can be copied. And C# has built-in support for MemberwiseClone. This is the method that you can use to copy an object, so that's a good example of having prototype already built in to the language. And memberwiseClone, of course, is going to just do a shallow copy. Same thing in Java, we've got a cloneable interface that you can just implement to indicate that you support Clone. In fact, the base object in Java has a Clone method on it. It is preferred that you actually implement Cloneable to indicate to users of your class that you do support cloning because as we talked about a little bit before with shallow copies and deep copies, if you just call Clone you might be doing a shallow copy when someone might be expecting a deep copy, so you really shouldn't be supporting Cloneable unless you're actually going to provide an implementation for it, but Java has this built in, so this Design Pattern using this cloneable interface, this represents prototype, and it has a method Clone that you can call that is basically going to do a shallow copy of a Java object. And I also think this is one of those reasons why a Prototype Pattern can kind of be confusing is because you're kind of already using it a lot if you're using Clone in either one of these languages, and you don't even realize it. So if you're looking for more, really Prototype is pretty simple and it's really straight forward, it's just going to be something that you're going to use when you need to copy an object. Summary So let's go over what we covered in this module. The first thing that we did was we talked about the Prototype Pattern, just kind of overviewed that in kind of layman terms of what is Prototype. And we went through kind of a dialogue of what if you needed a copy of a water bill. Would you go to the utility company and say, hey send me a brand new copy or would you just make a copy of the copy you already have? And so that's kind of the example of why we would use a Prototype Pattern, it's basically just making a copy of something. Then we went through some problems here. The first problem we looked at was when construction is expensive. We saw an example in code of an object that was expensive to create, so we used Prototype to make it so that we didn't have to go through that construction process, we could just make a copy of one that was already created. Then the second problem that we saw was when State was important to us, so we didn't want to have to construct an object and then try and match the state of an existing object when the state was really important to us of that current object. So what we did is we used Prototype to just copy that object and copy its state so that we didn't have to go through that process and we didn't have any possibility of making a mistake in copying the parts of the state that we need. Then the third problem we looked at was when we need to hide the constructor. And we saw that in this example all we had to do was use the Prototype Pattern and we could make the constructor private, various ways we could hide that constructor so that we could change that constructor later if we needed to and we didn't have to expose that to the user of our class. Instead we just gave them away to make a copy of our object if they needed a new version of our object. Then we went ahead and we talked about the formal definition of prototype. We saw the UML diagram, and we saw really how simple it is and we talked about the two simple roles that exist in Prototype, which is the Prototype, which is just an interface or an abstract class and the Concrete Prototype, which is just an implementation that implements that interface. Then finally we took a look at some examples in code. We learned that JavaScript itself is a prototypical language and that all objects in JavaScript are basically prototypes, they have a prototype property that you can see what the prototype is of that object. And then we talked a little bit about C# and Java and how they both have support for the Prototype Design Pattern already built in to their base class libraries in the language itself. Proxy Pattern Introduction Hi, this is Steve Smith, and in this Pluralsight on-demand module we're going to take a look at the Proxy Design Pattern. Intent The basic intent of the Proxy Pattern is to provide a surrogate or placeholder for another object in order to control access to it. Because of this, the Proxy Pattern is also known as the Surrogate Pattern. Motivating Example There are several examples when the Proxy Pattern would be appropriate. For instance, if you need a placeholder for an actual object that is expensive to create, the Proxy Pattern can serve you well. One example of this is if you have an image that you need to display inside of a client application and generating these images is expensive or time consuming. You can use a proxy in order to display some kind of a loading message while the actual image is being fetched or rendered. Another example is when you need to work with a remote service using web services or WCF. In this case, it's very common to have a proxy object that you work with, with your client, and that proxy object has the same interface as the remote object you're actually going to invoke, but it has the added benefit of keeping your code decoupled from the networking details of working with the remote object. Applicability There are several different scenarios where you might find the Proxy Pattern useful. A remote proxy acts as a local representative of a remote object, abstracting away the details of communicating with the actual object that lives in another memory space. A virtual proxy is used to create expensive objects on demand. A common example is the Image Proxy that I mentioned earlier, which would show a placeholder while the image is being loaded or rendered. A third type of proxy is called a Protection Proxy, and this one can be used to control access to an object, based on certain authorization and authentication rules. In this module, we're going to take a look at both the Remote Proxy and the Virtual Proxy versions of this pattern. Structure The Proxy Design Pattern consists primarily of two objects, the real subject, and the proxy. Both of these objects inherit from a common base class called Subject, which defines the interface that they both share, in this case shown as a simple method called Request. The real subject is responsible for the actual implementation of the request as a client would expect to have it done. The Proxy class includes a reference to a RealSubject and delegates calls to its Request method to the RealSubject's Request method. However, the Proxy class performs some kind of access control such as handling any network access required for the RealSubject or dealing with some kind of performance optimization such as lazy loading, which we'll see in a moment. An alternate and simplified implementation of the Proxy Pattern involves only two classes where the realSubject has the Request that's going to be performed and the Proxy simply is a subclass of the RealSubject. The only difference here is that there's not a common parent interface that both the Subject and the Proxy inherit from, but rather Proxy is merely a child class of the actual Subject, and thus when it performs its Request method, it calls the base.Request in order to delegate the actual behavior to its base class. How It Is Used Let's look at an example of how the Proxy Pattern is used. Clients work with the Proxy object as if it were the actual object. However, the Proxy is there to control access to the actual object, delegating calls to it only if and when it feels that it is needed. This allows the Proxy object to implement performance improvements and things such as the load time of an application or to simplify access to remote objects, eliminating the need for the client code to have any knowledge of the networking details required for this access. Proxy objects can also be used to defer expensive calls until they are requested by implementing Lazy Loading of objects from persistence. Lazy Loading What is Lazy Loading? Lazy Loading is an optimization that we can make in our code so that when it loads itself from persistence it only retrieves the state that is required, minimizing how many round trips are necessary to the database. It's often the case that objects stored in the database may span many tables and many rows. For example, if we take a common scenario of an E-commerce or catalog system in which you have an order object that has a collection of OrderDetail items and also a reference to a customer record, We can assume that each OrderDetail item also is going to refer to some product and each Customer record is going to refer to a collection of orders and other objects as well. Now if we are to create an Order object, such that all of its fields are fully instantiated, meaning that each object it refers to is, itself, fully populated with its state from the database, then that may result in loading thousands of records from the database. In fact, simply loading up one customer and their orders could result in trying to fetch most of the database once we've followed every possible path to every possible object reference, however, most of the time we don't need this much data. In fact, if we only needed to display an Order Number or perhaps a Total Price, there would no value at all in populating the Customer or OrderDetail records on our Order object. Thus, Lazy Loading refers to the practice of fetching object state from persistence only as it is requested by the object's clients. Remember that Lazy Loading, like any performance optimization, should not be done prematurely. Many ORM tools support Lazy Loading and can be configured in such a way that you can specify which mappings should be done in a lazy fashion, and which should be done in an eager fashion, thus allowing you to optimize the performance of your ORM tool to match the needs of your application. Consequences Let's examine some of the consequences of using the Proxy Pattern in our application. First, Client code typically will not need to be changed in order to work with a Proxy, however, it's important to note that the Proxy must be kept synchronized with the Real Object's interface. Thus, it's often a good idea to use some kind of code generation to create the Proxy automatically for you, so that whenever the underlying object's interface changes, the proxy can be regenerated automatically. This is typical in ORM solutions, as well as in remote proxies created by tool sets such as WCF. Another important note is that the Proxy can sometimes be used to optimize behavior in an existing system, without touching existing class behavior. We'll see an example of this by using a cast repository in just a few moments. This follows the Open/Closed Principle, which states that modules should be open to extension but closed to modification. You can learn more about this principle in the Principles of Object Oriented Design Course available at Pluralsight on-demand. You should be careful that your Client code does not make incorrect assumptions about the behavior of the object once the proxy has been introduced. Oftentimes, the Client's interface to the real object will use many small calls and a chatty interface, when fewer larger calls and a chunky interface would be more efficient when the object has been replaced with a remote proxy. Oftentimes in this scenario the network latency involved in each request is significant, so reducing the total number of requests can provide a significant performance increase. Another example is a Client that uses an object that has a lazy loaded proxy involved, and this may result in numerous database calls to load up the state of this object when an eager-loaded approach that simply requested all of the necessary state in one database call would have been more efficient. Demo: Virtual Proxy Now let's look at an implementation example of the Proxy Pattern using a Real Object and a Virtual Proxy Object that will increase the performance of the application by implementing lazy loading. First let's consider our Order object, which has a constructor shown here. As you can see, one of the things that the constructor does is call GetEntity, as well as calling GetCustomer and GetItems. Let's look at the GetCustomer method. This will return a new Customer passing in the OrderEntity's Customerid. Now if we look at the Customer's constructor, we'll see that it's going to new up a CustomerRepository and call GetById given the Customerid that was passed into it. Now let's see if we can improve the performance of this application in the scenario where we need an order, but we don't need to know anything about the Customer. First we're going to replace the Order's constructor with our OrderProxy constructor that simply takes in an ID and does no further work. Next, we're going to override the Customer field on the RealObject so that it returns our GetCustomer method, and our GetCustomer method is going to override the simple one of the RealObject with one that has a little bit of logic that controls access to the real customer data. In this case, we're going to check and see if we've already loaded the customer from the persistence layer and if we have, then we're just going to return our local instance of customer. Otherwise, we will set our local instance of the customer object using the base.GetCustomer call, which makes reference to the base object's actual implementation, and we'll new up a customer and have it be set in its constructor as before. This implementation ensures that the Customer is not loaded until such time as it is actually required. However, when it is required, it is only loaded once, and then stored in a local variable inside of our Order Proxy. Now let's look at a demo showing how we can use a Virtual Proxy to implement lazy loading on our Order object. In this case, we're going to use MSTest as the driver for our application. Each one of our tests is simply going to act as if it were a console application exercising a different version of the Order class. In this first method, we're going to say that Order should populate itself fully on creation. And if we run this test you see that it can pass because we have no assertions, so as long as there's no exception it should work correctly. Now if we look at the output for this, we can see that there are a number of lines being written out. These ones all correspond to data access, fetching different records from the database for Order, Customer, and Order Details. And then this is some information that I want to display to the end user. In this case I'm showing the date and also the name of the customer. If we look at this ConsoleReporting.PrintOrderDetails here, you'll see that it simply has three Console.WriteLine statements, one of which references order.OrderDate, and another that references Customer.Name. Looking back at the results of our test, you'll notice that all of the data access occurs before any of the reporting information is displayed. This is because our Order object is currently eager loading all of its state from the DataSource before it can be used at all by the Client calling code. In this case, our Client code consists of this ConsoleReporting method that takes in the myOrder instance. Now let's take a look at how we could implement an OrderProxy to change this behavior so that we only load the state that we need as it's being requested. First let's have a look at Order itself. Order has a constructor that takes in its ID and then within this constructor it's going to call GetEntity, as well as GetCustomer and GetItems. If we look at GetEntity, we'll see that it uses an OrderRepository to fetch the actual order from the database. And if we look at that GetById method you'll see that this is where we're going to display Fetching Order and in this case we're not actually talking to a DataSource, but we would in a real scenario. Now if we look at GetCustomer, we can see that it's simply newing up a Customer object and our list of Order items is going through our collection that was returned in our OrderEntity and newing up an individual OrderDetails object with each one. It's also important to note, for the implementation of Proxy to work, that most of these methods have been defined as virtual because we're going to override them in our Proxy. Now if we look for a moment at the OrderDetails object, you'll see that in its constructor it's also calling out to a repository here in order to get itself populated from its DataSource. The same is true of Customer, which follows the exact same pattern. Now taking a look at our Proxy, the first thing to notice is that our OrderProxy inherits from Order and it redefines the constructor that takes in simply an id to do nothing with data access. Then, whenever something tries to refer to some of the state of the order, such as the OrderDate, it's going to check and see whether or not the entity has already been loaded from persistence. It's going to do that inside of the GetEntity call and it's going to use this Boolean _entityLoaded variable. If we look at GetEntity, it simply checks to see if it has not been loaded yet, that it calls the base implementation GetEntity, which will actually call the repository and fetch the object. Finally, it sets the entity loaded to true and then it simply returns the entity's OrderDate field from the OrderDate property here on the Proxy. Customer and Items are implemented similarly, except instead of having to depend on the existence of an OrderEntity, each one of these depends on the existence of its actual class, Customer or a collection of Order items. Because of that, we have a local field called Customer and another local field which is our _orderDetails collection. Looking at GetCustomer, we again check a flag to see whether or not we've already loaded it, and if we haven't then we're going to get our entity if we haven't done so because we need some of the Entity's values in order to load these two fields, Customer and Items. Then we'll simply call base.GetCustomer and set our flag to true. GetItems is implemented the same way. Now if we look back to our test, we can see that we have an OrderProxy that we're going to call and then, otherwise, it's going to be the exact same code as before. When we run this, we'll see that the output will be different. Now the report starts before any of the data access occurs. Then when the call comes in saying that we need the date, this results in the entity having to be fetched, so we call Fetch Order 1, just in time before we need to display the date. And then next when we need to display the Customer Name, again, we're going to do a just-in-time call to the database and then display that Customer Name. It's important when we do this that we don't implement something that calls the database every time a request is made, and that's why we have those flags set up in our proxy to ensure that we only make these calls once and not every time these are accessed. We can prove that this is working the way we expect by accessing the Customer Name again and accessing each of the items again. When we do this, when we rerun our test, we can view the results and see that after fetching the Customer once, we were able to display it multiple times and also we're able to fetch each of the OrderItems only once and each of them is displayed. So as you can see, everything is working as we expected and our object is now more efficient because it's not having to call out to the database like it did on its very first implementation and fetch its entire state, even though we're only using a fraction of those fields. Now let's look at another implementation of using Lazy Loading, using the Lazy operator in .NET. We have one more test down here called LazyOrderShould, and this implements another implementation of Order called LazyOrder. Let's go ahead and look at LazyOrder. The main difference here is that LazyOrder has set up its fields so that they are Lazy and Lazy>. What this means is that we can set up a Lambda that will populate these fields the first time they are requested. So in our constructor, we can go ahead and use the behavior of the base class here, base class GetCustomer and the base class's GetItems as our Lambda to populate these. So when you look at this, you can see that the Lazy's constructor expects a Func. This is a function that will return a Customer object, and it's a function , so for a LazyCustomer it expects to return a Customer, and likewise for the list of OrderDetails it expects a function that returns a list of OrderDetails. Now, otherwise, we don't have to do any of the work that we implemented on our own in order to make the Lazy instantiation work. All we have to do is run the test, having done the use of the Lazy, and you can see that it passes. Now one other thing I wanted to show is that if we look at this GetCustomer method on our base class, you can see that all it's doing is returning a new Customer and passing in the Customerid. So if we take this exact return, new CustomerOrderEntity.Customerid and we use a Lambda expression for our function, we will get the same behavior. So let's look at our test results and verify that we did, in fact, get a Lazy behavior. Here you see that we fetched the Order, we display the information on the Order, and then we don't fetch the Customer until the Customer is requested. So that is what we would expect. Now let's see, assuming we use the Lambda expression we should get the same results. We run the test one more time and view those results, you can see that they are the same. Now in my LazyOrder implementation, I did not implement Order itself using Lazy although I could have. If we wanted to do that, we would just have an OrderEntity here that was implemented in the Lazy fashion. And then once the OrderDate was requested that would trigger it to go and fetch the Lazy value using the Lambda expression. The only other thing to note is that since the Lazy object is being used as our field for these properties that we're overriding, we have to use the .Value of the Lazy in order to get the underlying value of that type. So this .Value is of type Customer, this .Value is List. So Lazy is an easy way for you to achieve Lazy Loading behavior in your applications without having to implement it completely from scratch. Demo: Remote Proxy Now let's look at an implementation example of the Remote Proxy Pattern using WCF. In this case we have a repository that has been constructed to call out across the network to fetch the data that it needs for its application. You can see that it's calling OrderService.OrderServiceClient in order to make this Fetch of the data and it's returning back a DTO or a Data Transfer Object. Now in this case, our Proxy is the OrderService Client, which is actually generated using WCF when you add a Service Reference to your project. Shown here are the generated files from the Service Reference and the actual Proxy class is inside of Reference.cs. The code that is actually being run when this executes across the network is in another project entirely and in this case it's called OrderService, which has the GetDataUsingDataContract method defined. You can see that in neither the Remote Object nor the client is any of the networking infrastructure exposed because this is all done inside of the Proxy that was generated for us when we added our Service Reference. Let's look at how we can use a Remote Proxy in our Order baseDemo that we saw before. In this case we're going to load the details of our order from a WCF service that's running, in this case, on the same machine, but it could be running across the network. To do this, I've altered my order by creating a new implementation called RemoteOrder. And if we look at RemoteOrder we'll see that it simply inherits from Order and overrides GetEntity so that it uses a RemoteOrderRepository. Now this RemoteOrderRepository has been changed so that it uses WCF to fetch the order. And it does so by calling out to a Service Reference that I've created called OrderService.OrderServiceClient. This is found here in my Service References and if we want to see the actual code that was generated, we can say Show All Files and drill down to the Reference.svcmap, Reference.cs, and if we open this up we'll see some of the code that was generated. As these are generated files, which they warn you about right here at the top, this isn't something that you want to change directly because the next time you update you're Service Reference this code will be overwritten. Now the actual Service that's being called is in this other project here, which is a simple WcfServiceLibrary that I added to my Solution. It has an interface that defines the contract that takes the GetDataUsingDataContracts method name, tells it that it expects an orderId, and it returns an OrderDTO or Data Transfer Object. Now my OrderDTO is part of my DataContract that I've defined here and I gave it fields that correspond to the things that my OrderEntity expects. I didn't use the OrderEntity directly because I didn't want to necessarily have a dependency between my WCF Service and this Proxy Project that will be referencing it. It's easy to get into a circular dependency issue if you have your ProxyDemo calling in to a Service Reference and your service calling back to your ProxyDemo with an Assembly Reference. Looking at the OrderService itself, we could imagine that this would be fetching the data from some remote data store, but in this case we're going to just hard-code it so that it returns a new instance of our DTO and passes in some sample data. This is slightly different than the data that I had in my OrderRepository because it's passing back five different items and it has a Customerid of 123 instead of the Customer 1 and OrderItems 1, 2, 3 that it had previously. Well in order for my test to work, I have to have my service running. So if I run this test right now, it'll just time out and fail because the Service doesn't exist. But if I go ahead and run my project by hitting F5, this'll go ahead and run my WCF Service for me and then when I run my test it will actually talk to that Service, so there we go. So now we have this actually talking over the wire to a separate process. And if we look at the output, we can see that I'm still Eager Loading because I'm not using the Lazy Loading Proxy anymore, but we can see that we're fetching using WCF to fetch the order. And the data that we're getting is Customer 123 and OrderItems 1-5 as defined in our RemoteOrderService. The key takeaway here is that my RemoteRepository here was able to reference an object, this OrderServiceClient as if it were an actual local object and I could call out to its methods and get full IntelliSense without having to know about the fact that this actual object exists on a remote server or in a different address space than where I'm running currently. The other nice feature of WCF and other similar frameworks is that they generate this Proxy code automatically based on the contract that you specify for your method. So looking at the Proxy Design Pattern, the IOrderService interface is implemented by both the real object, which is in this case, OrderService, as well as the Remote object, in this case this Reference.cs Order Proxy. Here's the public IOrderService that's being used by the Proxy. Demo: CachedRepository For this last Implementation example, I would like to show you a pattern that I use in my real applications that takes advantage of the Proxy Pattern to dramatically increase the performance of the Repository Pattern. If you're using the Repository Pattern, you probably have code that looks something like this where you have a Repository of some type, and it returns back values typically fetched from the database. In this case, I'm simply returning a new OrderEntity with some hard-coded fields, but you can imagine that more typically this would be talking to my data structures through the use of whatever object-relational mapper I'm using at the time. Now the Proxy Pattern in this case is going to be used to implement caching at the repository level. By implementing a CachedOrderRepository that inherits from OrderRepository, I can ensure that my code is taking advantage of the Single Responsibility Principle. This means that my OrderRepository has no knowledge of caching in it and I have embedded all of the caching logic inside of this separate CachedOrderRepository class. This is also an example of the Open/Closed Principle because I was able to add caching logic to my repository without actually changing the OrderRepository itself. One last consequence of this pattern is that if you are using some kind of an IoC container or Inversion of Control container such as Microsoft Unity or StructureMap, you can now control whether or not your repositories are using caching or not by simply changing which implementation of the repository type you used inside your container's catalog. What this means is that you can turn caching on or off throughout your application on a per repository basis by simply going into one file in your app and changing whether it's a CachedOrderRepository or simply an OrderRepository that's being given back to the application whenever it asks for this OrderRepository type. This makes it very easy for you to tune your application by turning on or off caching at various levels in order to see what performance impact it has on the application. Now we're going to take a look at the CachedRepository Pattern, which takes advantage of the Proxy Pattern. In this example, I have another test that says that the CachedOrderRepository should LoadOrder only from the source one time. In order to show this, we're going to load up several entities from new CachedOrderRepositories, or we could use the same one, it doesn't matter, and in each case we're going to do a GetById on the same item from the database. If we run this test and look at the output, we can see that we only said we were Fetching Order 1 one time. So let's look at how this CacheOrderRepository works. CacheOrderRepository in this case inherits from OrderRepository and wraps it with some additional behavior. In this case, we're going to set up our cacheKey based on the type of thing that we're fetching, and it's ID. We're going to use the MemoryCache.Default, which is a new type in .NET 4. If you're using an earlier version of .NET, you can simply use HttpRuntime.Cache and that will work as well, as long as you have a reference to system.web. If our entity is null, that means that it was not found in the cache. We're going to go ahead and delegate to our base class the OrderRepository's implementation of GetById and then we're going to create our new Item and Policy and we're going to add it to the Cache before we finally return our entity. When we call into base.GetById, that is where we are going to call Fetching Order, and so you'll see that that only occurs the one time in this case. Now the nice thing about the CachedOrderRepository is that it's sort of following the Decorator Pattern as well as the Proxy Pattern, in that not only is it controlling access to the underlying data, but it's also adding some behavior in terms of how the caching logic works. One nice thing about this is that you can actually use it on top of another implementation of OrderRepository such as our RemoteOrderRepository that we already created. If we have a RemoteOrderRepository, that's going to call out using WCF, but our cache logic should still ensure that it only happens one time. So with just that one simple change, if we rerun our test we'll see that it fails because now it's talking to WCF. If we run our WCF project so that it's active, run this again with our test, it's going to take a second the first time that it loads, and we can see it's, you know, using WCF, but only one time. And now subsequent results if we run the test are much faster, but again, each one only fetches it one time. So the CachedOrderRepository or, in general, having a CachedRepository inherit from a ConcreteOrderRepository that actually does the data access, is a pattern that I've found to be extremely useful for improving the performance of applications and also keeping my design very clean, because all of the caching logic can live inside of the CachedRepository, while all of the logic of accessing the data can live inside the base implementation. It's also possible to take most of this logic that's in here, and put it inside of a base class or helper method so that you don't have this repetition of all this caching logic, but that's beyond the scope of this presentation on the Proxy Pattern. Related Patterns Let's look at a couple of patterns that are closely related to the Proxy Pattern. The first one is the Adapter Pattern. The Adapter Pattern changes an object's interface to suit the Client's needs, while the Proxy Pattern tends to retain the same interface, but controls access to the underlying object's behavior in order to improve performance or, otherwise, alter how that object is accessed by the application. The Decorator Pattern is extremely similar in implementation to the Proxy, however, its intent is different. The Decorator adds additional responsibility to an object, while the Proxy merely controls access to the Object. You can learn more about both of these patterns in the Pattern Library available at Pluralsight on-demand. As always, there are a number of excellent books where you can learn more about Design Patterns in general or the Proxy Pattern in particular. I recommend you start with the Design Patterns Reference Book by the so-called Gang of Four, which is the first title listed here. I have also found Design patterns in C# to be helpful, and Head First Design Patterns is an excellent book for learning Design Patterns, which has a unique way of presenting the information. You can also learn more about the Proxy Pattern online at Summary In summary, the Proxy Pattern is useful when you need to control access to an object. This can be done by using a Virtual Proxy that can be used to eliminate or defer expensive operations and thus improve application performance. Or, you can use a Remote Proxy that can encapsulate access to an object that's located in a remote address space. Remote Proxies are often generated automatically using tools like WCF and Visual Studio and allow you to implement your code so that it has no knowledge of the networking infrastructure required to actually communicate with the remote service. These are just two of the most common examples of the Proxy Pattern and you may find others where it makes sense for you to control the access to an expensive object by putting a Proxy object in its place. This has been the Proxy Design Pattern for Pluralsight on-demand. My name is Steve Smith, and I want to thank you for listening and I hope to see you again at additional Pluralsight on-demand courses real soon. Repository Introduction Hi, this is Scott Allen of Pluralsight, and in this module we're going to look at the Repository Pattern. This is a common design pattern inside of applications that need to perform data access. Why do we use the Repository Pattern? Because most applications do need to access data from some Data Source or perhaps multiple Data Sources, and it doesn't matter if those Data Sources are relational databases like SQL Server or web service endpoint or a collection of text files on the file system, what we don't want to do is duplicate data access code throughout our Business Logic or our Domain Model. Typically data access code is very repetitive and it's concerned with low-level infrastructure details like opening SQL connections and managing SQL parameters and transactions. We don't want that sort of code duplicated throughout our Business Logic. What we'd like to do is extract that so that the Business Logic is just focused on implementing the special algorithms that make the business work. We'd like to extract the data access code so that we have a separation of concerns and we have a separate layer of code that's concerned with accessing this Data Source. This also increases the testability of an application, because as we're about to discover using the Repository Pattern, we can simulate data access when we're inside of unit tests and actually have a component that works with in-memory data instead of a web service or against a database schema. This allows our unit test to be very repeatable, very low friction, and not much effort to set up, and it also lets those unit tests run very fast so that we have a quick feedback cycle. Intent A Repository is going to be a class that you build for your application and it's going to exist somewhere between the Business Logic and the Data Source of your application. You might have multiple repositories inside of an application. You might have a repository for each type of entity that you need to store. So in this example we'll have an Employee Repository and a Product Repository and a Customer Repository. And this layer of software, then, completely encapsulates all the minutia of data access, so that the Business Logic never has to worry about opening a connection or reading a file. Instead, the goal of the Repository is to make all the business data appear as if it were just living inside the repository inside an in-memory collection, so it's as easy for the Business Logic to access some employee data that lives in a database as it would be for the Business Logic to just access employee data that lives inside of an in-memory array somewhere. So it's quite common for these repositories to just expose information through a collection-like interface where you can add, remove, count and so forth. It's also quite common for these repositories to expose methods that will allow the Business Logic to query that repository and it's up to the repository to take the parameters of that query and send it to the Data Source. For instance, the Employee Repository might have a FindEmployeeById method that takes parameter to the Business Logic and say Find the employee with an ID of 1. Or it might be more complicated, you might be saying Find all the customers who live in London or Find all the products whose price is greater than x and whose inventory is less than y. It's up to each repository to take those simple methods that they're exposing to the Business Logic and map them into something that the Data Source will understand either through an API like the Entity Framework or NHibernate provides or by taking the parameters and passing them to the right web service method. IEmployeeRepository Let's switch into Visual Studio and take a look at what a Repository implementation might look like. First we'll probably want to start with an interface definition for our Repository because our Business Logic can then program against this interface and that leaves us free to implement different versions of that interface in concrete classes. We might have one version that actually talks to the database and we'll use that in production and at Runtime, and we might have a different version of IEmployeeRepository that we just use during unit tests so we can have fast, efficient unit tests. So what methods and properties should we put on this interface? Well, remember the goal of a repository is to make the data appear as if it's just living inside an in-memory collection. So you might drive the design of this repository using unit tests or the requirements of your Business Logic, but the ultimate goal is to provide very simple mechanisms that will allow someone to add new objects to the repository or query for existing objects. So in this comment in code, I'm pretending this is some business logic and I'm just trying to get a feel for what types of things we might want to do. Like, given an IEmployeeRepository object, we might want to go up and tell the repository to add some new object to the persistence mechanism. And we probably also want the ability to remove some given employee object that we might have hanging around. So Add and Remove are two methods that are typically on every repository that you're going to build. We also need some mechanism on our repository to retrieve information and there's generally two approaches to this. One might be a dedicated method that will both encapsulate the data access and also the query parameters. So you can imagine something like repository.GetAllManagers. Not only does this method know how to query the Data Source, but it also knows how to put together the proper parameters and the specifications needed to get the employees that are just managers. That's one approach. Another approach is to provide a very generic querying mechanism, and this can be done quite eloquently these days using Link. So we might say repository.Find, and then pass in a Link expression that says, given an employee, we want e.IsManager to be equal to true, so we just want those objects. The choice between these two styles will really be driven by both the needs of your Business Logic and also the type of Data Source that you're accessing. For instance, if you are using WCF Web Services behind the scenes to store and retrieve this information, then you might want to use this form of GetAllManagers that will map directly to some WCF Web Service call. Or if you're doing database access through Stored Procedures, you can imagine methods on your repository that map to specific stored procedures that someone has built in the database. On the other hand, if you're using a very flexible data access layer, something like can be provided by the Entity Framework or NHibernate, then you might want to choose this Link approach, because it turns out to be very easy to take these Link expressions, like e +> e.IsManager and just hand them off to a Link provider, a Link provider implemented by the Entity Framework or NHibernate and they have the ability to pick apart these expressions and build an SQL command at Runtime that can execute and find just the objects that you need. In this demonstration, we're ultimately going to be working with the Entity Framework, so we're going to prefer this style mechanism for performing queries through the repository. So now that we've written some code or some pseudo-code or some unit tests that have flushed out what the API for a repository should look like, let's go ahead and construct our IEmployeeRepository interface. We'll say that any object implementing this interface should have the ability to add a new employee to the repository, to remove an existing employee, and given some predicate expression, the ability to find some subset of employees. Now let's take a step back and talk about this API for just a minute. First of all, many people might say, well what about an update mechanism that is given employee, I now want to make sure that it gets persisted when I invoke this update method, so it gets saved in the database somewhere. The Update method is a reasonable thing to have on a repository interface, but it's not all that common to tell you the truth. Repositories that are using WCF Services or file system based services or SharePoint List, you might need an explicit Update command on that repository to make sure data gets saved, but if you're working against a mechanism that uses a Design Pattern called the Unit of Work Design Pattern, which is going to be another module in this library, what you'll find is that the explicit Save operation, the Update operation or the operation that saves and reconciles all the changes made in your repository to the actual Data Source, that's actually going to be handled somewhere else. And we have this discussion when we talk about the Unit of Work Design Pattern. So we're going to leave the Update Operation off of our repository, that's going to be magically handled by some other mechanism and we'll see a bit of that in this demonstration too. Let's also take a look at this Find API. Now remember that the goal of a repository is to make the data appear as if it's just an in-memory collection, so when we go to find some subset of Employees, it seems reasonable that we just return a list of Employee or we could return an array of Employee, but sometimes it's even better to go with a less restrictive type. For instance, IList or even better is we could return IEnumerable and it turns out this will give us some additional benefits that we'll see later, namely the ability to have a Lazy evaluation of the Find operation. And if you are working against a Link Data Source, something like the Entity Framework or NHibernate, you might find it useful to actually return IQueryable. Not only does this give you the opportunity for Lazy evaluation of the Find operation, but it also gives you the ability to compose in additional expressions into the results of this Find operation, so the ability to Add, for instance, an OrderBy and a Take and a Skip, and those types of operations. If you're not familiar with the differences between IQueryable and IEnumerable, then I suggest you look in the Pluralsight on-demand library at the link in C# module that's part of Link Fundamentals. IQueryable will essentially let us compose together queries that the Link Provider like the Entity Framework will see holistically, so they'll have the ability to see the entire expression and formulate a very optimized SQL Command. Generic IRepository As we take a look at this Repository API, we'll notice that methods like Add, Remove, and Find, these types of operations could apply not only to employees, but also to accounts and customers and movies and any type of persistent data that we want to get to will probably need the ability to add, Delete, and Find that information. And so it's quite common not to start with a base interface like IEmployeeRepository, but to start with a very generic repository like IRepository. And now what we can do is we can, instead of using a specific type like Employee, we can use that generic type parameter to say that, okay we want to Add a new entity of some type. And we're also going to Remove some entity and we also want to Find and Return IQueryable, so IQueryable of that entity type. And now what we have is a generic repository that we can use for any type. Now it might be that if we need some of these special methods like GetAllManagers, that we could still define an IEmployeeRepository interface that's going to derive from IRepository and provide that additional method. So inside of this interface definition we could define GetAllManagers and force objects to implement that. But for this demo we're just going to work with the generic repository and we'll see how we can use this to isolate our code from data access internals or specific APIs like the one that the Entity Framework provides, and we'll also see how we can use an interface like this in our unit test and keep our unit test isolated from the database schema. Repository at Work Let's look at using IRepository inside of an application. So here's an ASP.NET MVC web application that's going to work with employee information that's stored in SQL Server. Every employee has some properties like ID, Name, HireDate, and a collection of TimeCards. We're going to implement a controller that is going to allow us to List, Edit, Create, and Delete employee information. For instance, I can click on the single employee that we have right now in the database and edit the Name and the HireDate and click Save. Those controllers using an IRepository where T is an employee type, and when we need to get a form that will edit the employee, what the controller can do is walk up to the repository and say, find me the employee that meets this specification where the employee's ID is equal to the incoming ID parameter. And then we'll use an additional Link operator to say that we should just get a single result from that query. And that employee will serve as the model in this MVC Design Pattern, and we'll pass that model off to the View to render. Now when someone edits the employee information and does some work in here and clicks Save, they'll be posting back to a different controller action here, that again, is going to go out to the repository, retrieve that employee so that it can be updated with model binding in the MVC framework. So we've retrieved the employee, we've applied some changes to the properties. As I mentioned earlier, we don't have an explicit Update or Save method on this repository. Instead we're using this design pattern notice the unitOfWork, to go out and Commit all of our work. So conceptually at this point, you can think of the unitOfWork as a component that goes out and looks at all the repositories that we have available and tells each of them that now is the time to commit the work inside of a single transaction. But the important part to point out here as far as the Repository Design Pattern goes, is that you can see working with the repository from the controller is a very simple operation. We can go out and find things, we can go out and create things by adding new employees to the repository, and it's not any different really than working with a list of employees or an in-memory collection of employee objects. We don't have any data access code, any low-level stuff about connections and parameters or any of that inside of this layer that is using that repository. It's all hidden behind the interface. Implementing a Repository Now that we've fleshed out the API for IRepository and we've seen how we can consume that API in a real application, the next question would be, how do we implement a concrete version of IRepository? The answer depends greatly upon the type of Data Source that you're trying to reach. So a concrete implementation that works against SharePoint is going to be much different than an implementation that works against the Entity Framework or an implementation that works against WCF Data Services. In this demonstration, I want to show you how easy it is to build a concrete implementation for that interface that talks to SQL Server via the Entity Framework. To get started with the Entity Framework, first we're going to need an entity data model. We have several videos available in the Pluralsight on-demand library that describe how to build an entity data model, and it's essentially the metadata that you need to provide the Entity Framework that tells it how to map a CLR type to tables and columns in a database. For instance, I'm describing here to the Entity Framework that when you see an object of type Employee, that that maps to the Employee Table and here's how the individual properties map to specific columns that are inside of that table. Behind the scenes I just have a Poco employee object that is a plain old CLR object that the Entity Framework can work with. It doesn't need to derive from any specific base class. it doesn't need any specific attributes on it, it's just a plain class. We do have some virtual properties here that enable some features in the Entity Framework and we'll talk about this IEntity interface in just a moment. Once you have an EDM in place, what you can do is you can construct an instance of an ObjectContext. This is the gateway to the database that the Entity Framework provides us. It's what we want to hide our business layer from, but all that thing needs is a connectionString that describes what database to connect to and where to get the metadata, and then we can use that object to start getting to information in the database. A concrete implementation of IRepository might look like this class. This is SqlRepository. What it's going to do is when you construct one of these, you need to pass in an object context from the entity framework and from there everything is pretty straight forward because it turns out the Repository Pattern and the Entity Framework work pretty well together. First of all, given this generic type parameter T, I can create an ObjectSet through the Entity Framework API that's essentially an abstraction around a collection of entities that would live inside of a table that the Entity Framework knows how to talk to. And once I have that ObjectSet, I can implement IRepository members like Find and Add and Remove simply by taking parameters that are passed into those methods and forwarding them to calls on the ObjectSet. When you call Find and pass me in a predicate expression, I'm just going to forward that to the Where operator on the ObjectSet. When you add a new entity, I'll forward that to AddObject. When you want to remove something from this repository, I'll tell the ObjectSet to delete that object. ObjectSet implements IQueryable that allows us to chain together some additional operations once we return this queryable set, and that should give us very efficient queries at Runtime. Now I did add a couple additional operations actually into this repository into my implementation of IRepository. For instance, one thing that you might find that is useful is that if you provide a method on your repository to FindById, given any entity of type T, I just want to be able to invoke FindById on my repository and pass in an integer parameter. Now this does require, if I'm going to implement this generically like I do in SqlRepository, where it just says OjbectSet.Single, that's the Link operator that says I should expect a single result. When you look for that object with an ID equal to the id parameters, in order for this to work then we have to ensure that every generic type parameter we get is for a type that has an ID parameter. And the way to do that is to use generic constraints. So here we can say, you can instantiate this repository with a T, but that T has to be a reference type and it has to implement IEntity. So first of all, it has to be a reference type because it turns out that the entity framework has this requirement on its generic type parameter for CreateObjectSet, T has to be a reference type. IEntity, what we can do with this is we can say anything that implements IEntity has an Id parameter, therefore, as long as we're working with a T that is an IEntity, then we can implement this logic in our generic repository, and we can also provide that method on IRepository. You can see we have the same generic constraints there. So with very little code, we now have repositories for any of the things that we have in our entity data model, but we want to get to in the database. Tests and Separation Now that we've seen how easy it is to implement this Repository Design Pattern, let's take a step back and look at the advantages that we've gained inside of our application. As I mentioned earlier, the primary advantage to this Repository Design Pattern is that you provide a simple API for your Business Logic or in this case the logic that's inside of an Action method on a controller. The code that needs to interface with the repository now doesn't need to know any low-level details about how the repository actually connects to a Data Source or how it sends commands and retrieves objects from that Data Source. Instead, the code just walks up to the repository and, in this case, we're saying Find all the Employee objects, and then because of the way we've designed our repository we can keep firing Link operators at it, so we can tell it to order that collection of employees now by the HireDate. And this is the primary advantage of this design pattern. We've separated the concerns, the data access concerns are hidden behind the repository. The Business Logic just focuses on using that repository to get at the information it needs. In addition, because our Repository is defined by an interface, IRepository, we have the ability to switch different implementations of IRepository at Runtime and at test time. For instance, we could build a FakeRepository that implements IRepository that instead of working against a database, just works against an in-memory collection like a HashSet or a List or an array. And in this case, when someone wants to find a particular employee in that in-memory collection, again, all we need to do is take that predicate expression and forward it to the Where operator on that in-memory collection. And when we want to do something like add a new object to that collection or into this repository, we just need to add it to that in-memory collection. The one trick here is that because we are returning IQueryable, which allows us to build very efficient composed queries using Link, we need to make that in-memory collection look as if it supports IQueryable. by default, it's only going to support IEnumerable. All these in-memory collections like List, and HashSets and arrays, they support IEnumerable out of the box, but not IQueryable. The only thing you need to do to make an in-memory collection appear as an IQueryable, is to use the Link operator AsQueryable. And we'll do that here inside of our FakeRepository to make this appear just like the real repository that's going to work against the Entity Framework. At this point, we could construct FakeRepositories and populate them with fake data and pass those FakeRepositories into our controllers to have very efficient execution during our unit test. We don't have any friction about setting up a database or getting the correct schema installed, having all the test data populated. All we need to do is build a couple simple in-memory collections and execute our tests against the controllers using those in-memory collections. We could also use a Mocking framework like Moq. In this particular unit test, we're going to build a MockRepository. We're going to have it set up with expectations to return some fake data using the Mocking Framework API, so here we're saying set up this Mock repository object when someone calls FindAll. Return this in-memory employeeData that we've put together. Now what we can do is state-based testing. That is, we'll construct the controller using this MockRepository, invoke the Index, and then make sure that it builds the proper model for us, that the model it returns has the same number of objects as that in-memory collection that we built. Then we can also do very simple interaction-based testing, which is let's invoke the Index action on the controller and use the Mocking Framework's API to just Verify that somewhere inside of that Index method something invoked FindAll on our repository. These will be very simple, very fast unit tests, all thanks to the Repository Design Pattern. Applicability In the demo that we just looked at, we used the Repository Design Pattern to allow our Business Logic and Controller Logic to connect ultimately to a SQL Server database. And the Repository behind the scenes used the Entity Framework to interact with the database. The Repository Design Pattern works very well against relational databases, but it's also applicable to a number of other scenarios. For instance, you can imagine if your data is stored somewhere in the cloud or behind a web service, you could build a repository that allows your Business Logic to talk to the Repository and hide you from the details of connecting to that web service. Likewise, you could connect to text files or XML files that are on the file system. You could connect to lists that are stored inside of SharePoint. The Repository Design Pattern will do a great job of abstracting away all these different types of Data Sources. so you could say that the Repository Design Pattern really is applicable anytime that you need data persistence. You're going to make that data appear as if it's just hanging around in-memory inside that Repository and hide all the details of data access behind the repository's interface. Consequences There are a couple consequences to using the Repository Design Pattern. First, you should have an increased level of abstraction inside your application. This is good because it should mean that you'll have less duplicated code. It also means that you should have code that's more maintainable, more flexible, and more testable, however, you do have some additional interfaces, some additional classes, some people who are not familiar with the design pattern might need to look at this and figure out exactly what's going on before they can catch on. When you have data access logic buried right inside of your business code, sometimes it's very easy to look at that and understand what's going on, but it just doesn't scale up well, and in complex applications, you really need this increased level of abstraction just to manage the complexity. Another consequence of the Repository Design Pattern is that you are one step further away from the data. Since the Repository is shielding you from the underlying infrastructure, sometimes it can also be more difficult to get hints into that infrastructure that can help it optimize some of the operations that it needs to perform against the Data Source. There are various ways to work around this, and optimizations are always about trade-offs, but for one example, you could provide some explicit named methods on a repository like the GetAllManagers method that we looked at the beginning of this module that contain all that optimization code inside of it and it still gets to hide all of that from the Business Logic layer. Related Patterns Let me give you a quick description of some of the Related Patterns that you might see in an application that's using Repositories. Number one is the Unit of Work Design Pattern. It's the Unit of Work's responsibility to track changes in the objects that are being retrieved from all these different repositories so that when it comes time to save the work, it can coordinate saving all the data from all the different objects in a single atomic transaction. The Specification Design Pattern is something you might apply when you need to build up complex criteria to pass in to one of the Query methods on a Repository. There is also the Identity Map Pattern that is very common in data access scenarios, particularly when you're using a technology like the Entity Framework or NHibernate. The Identity Map enforces object identity in much the same way that a database enforces row identity based on a primary key value. And finally, there's the Decorator Design Pattern. Decorator allows you to dynamically layer in additional behavior on top of a Repository while still maintaining the API or the interface of that Repository. For instance, you might have written a Product Repository that encapsulates data access code for product information, but on top of that you could layer a Caching Repository that caches data coming out of that Product Repository. Neither the Business Logic layer nor the data access layer know about that Caching Repository, it's just sitting in between and it still implements the same interface as the Product Repository. Summary In this module, we looked at the Repository Design Pattern and we saw how we can use it to keep our Business Logic and Domain Model free of data access code and away from infrastructure code and actual components that talk to the database. Using the Repository Pattern, we were able to write more maintainable code and easily unit test our code. And we took a look at a specific example that implemented a generic repository in C# code, the IRepository interface. Using the magic of Generics, we were able to provide a single concrete implementation of this interface that covers most of our needs in an application. Singleton Introduction Hi this is Steve Smith, and in this Pluralsight module we're going to have a look at the Singleton Design Pattern. This is part of the Design Patterns Library, and Singleton is one of the simplest design patterns, but it's also an easy one to get wrong if you're not careful. Motivating Example The idea of the Singleton is that you have a class in your program that should only ever have exactly one instance. Some examples of this would include on your computer you maybe only want to have one file system that represents all of the hard drives and subsystems of that. Or on a network that might have many printers, you'd want to have only a single printer spooler so that you wouldn't have multiple printer spoolers allocating jobs to different printers. Likewise, with the operating system there should be only one windowmanager. Commonly, singletons should only be created when they are first needed. That is to say that they should implement something called lazy construction because you don't want to have them created when they're not needed within your application. Intent The intent of the Singleton Pattern is to ensure that a class has only one instance. The class itself is responsible for keeping track of this sole instance, as well as for making sure that other operators within the application cannot create their own instances of the class. The best way to think about this is as the movie the Highlander points out, there can be only one of this particular class's instance. Applicability You should use the Singleton Pattern when you're certain that there must be one and only one instance of a class within your program. This class must be accessible to clients and the class generally should not require parameters as part of its construction. If it does, that's a sign that you probably need to have multiple different versions of this class, and therefore, the Singleton Pattern doesn't apply because you would need to be able to construct multiple instances. Sometimes if the creation of an instance is expensive, a Singleton can improve performance, even if it wouldn't otherwise be required. Structure In terms of its structure, the Singleton is extremely simple. Here we have a UML diagram showing a class called Singleton. I don't have any attributes called out because they're not important to the pattern, but in its Operations you can see that I have a method called Instance, and that method is the only way that we can get an instance of the Singleton. This is because the constructor is private, indicated by the minus sign in front of it. And so this constructor, the Singleton here, is inaccessible to any class except for the Singleton itself. As it turns out, the Instance method shown here is responsible for construction of the object and will ensure that there is only one of them at any given time. It's also worth noting, that while I have Instance shown here as a method, it's also commonly implemented as a property in C#. Structure (not thread safe) The classic implementation of the Singleton Design Pattern is shown here in C#. You can see that we have a static Singleton _instance, and this will be the only instance of this class that we will have in our program. We've got the private constructor shown here, which ensures that this class cannot be constructed by any class other than the Singleton itself. We also have a public static Instance, which in this case is a property, as indicated by the Getter that it has here. And what this does is it simply checks to see if Instance is null, then assign it to be a new Singleton, and in any event, simply return that Instance. So when this is first called, Instance will be null and it will instantiate a new Singleton, otherwise, it will always return the same Instance. Note, however, that this is not thread-safe, and so you should not use this in any application that might have the Singleton accessed from multiple threads. We'll look at how we can clean this up in just a moment. How It Is Used Unlike some Design Patterns that are a bit more complex, the Singleton Pattern is very simple in terms of how it's used. Once you have constructed the Singleton using its instance method or property, you can call methods on Instance directly as is shown here, or you can assign variables to Instance if you want, as is shown here where I am assigning the Instance to my object and then calling methods on it as if it were any other Instance. Finally, we can pass these Singletons around as a parameter, which you can see here where I'm passing into some other method my Singleton Instance, and my method simply expects some object of Type Singleton. Structure (thread safe) As we've already noted, the default implementation of the Singleton Pattern is not thread-safe, and therefore, should only be used in applications that will not access the instance from multiple threads. If you're building a web application or any other application that is meant to be used in a multi-threaded environment, you should avoid the classic Singleton Pattern that was shown previously. Instead, there are a number of different approaches that you can take to create a Singleton in effect, but without using that exact same pattern. Some of these involve locks, which can affect the performance of your application, but this particular implementation here does not use locks and, therefore, is thread-safe, as well as being extremely fast. We start off by giving it a private constructor as is typical for the Singleton Pattern, as well as a property to get the Instance of our class, the LazySingleton. The implementation of this relies on the way Type initializers work in .NET. The C# compiler will guarantee that a type initializer is instantiated lazily, only if it is not marked with a special flag called BeforeFieldInit. The way that we can ensure that our class here nested is not marked with that flag, is by ensuring that it has a static constructor, shown here. While this static constructor appears to be not being used for anything, it is actually important because of the way the C# compiler behaves. Within the Nested class, we have our field, which is the LazySingleton instance, and we're setting that to be a new LazySingleton statically when it's first referenced. That reference will only occur within our method getter here so that when we recall this, it will refer to Nested.instance. The first time this occurs, this particular bit of code here will be initialized and we will get our new Singleton. Subsequent requests will simply get back the existing instance of our variable, and thus the Singleton Pattern is followed with there being one and only one LazySingleton in our application. Collaboration Since the Singleton involves only a single class and its construction, collaboration with this pattern is very straightforward. Classes that need to interact directly with a Singleton, must refer to its Instance, Property or Method. Alternately, classes can depend on an interface or a parameter of the Singleton's type. Consequences There are a number of consequences involved with using the Singleton Pattern as shown here. The default implementation of the Singleton Pattern is not thread-safe and thus should not be used in multi-threaded environments, including web applications such as ASP.NET. Singletons can introduce tight coupling among collaborating classes. This means that it will be more difficult for these classes to be separated from one another in order to test them or in order to refactor your application, resulting in a more brittle design. Singletons are notoriously difficult to test and are commonly regarded as an anti-pattern by those who consider testable code to be an asset. Using an IoC Container, it is straightforward to avoid this coupling and the testability issues that it introduces. Single Responsibility In addition to adding tight coupling to our application and making our application more difficult to test, the Singleton Pattern also violates the Single Responsibility Principle. Management of Object lifetime is a separate responsibility from the actual responsibilities that a class performs. If we add the responsibility of ensuring there is only one of our Instance to a class, this represents a violation of the Single Responsibility Principle. Using an Inversion of Control Container or an IoC Container, a separate class can be responsible for managing object lifetimes. That class would then have only a single responsibility and thus would not violate the Single Responsibility Principle. You can learn more about the Single Responsibility Principle in the Principles of Object Oriented Design course available from Pluralsight on-demand. Implementation Example Now I'm going to demonstrate an implementation example of the Singleton Pattern. In this example, we're going to look at logging to a common file and we'll do this using separate Instance classes. We'll apply a Singleton in order to improve performance. We'll introduce locking and double-check locking, which are both patterns that are often applied to ensure that the Singleton is thread-safe. And then we'll show the lazy instantiation via statics, which is the pattern that you saw a couple of slides ago. In this example, we're going to have two different execution modes. The first will be a single-threaded mode, in which the classic implementation of the Singleton would be perfectly acceptable, and then a multi-threaded mode, which will be using the Task Parallel Library from .NET 4 to ensure that our application is being used by multiple threads at the same time, thus requiring a thread-safe solution. In this example, we're going to look at a number of different implementations of the Singleton Design Pattern as they apply to Logging to a common file. In this case, we're going to use a file that's located here in my dev/scratch/logs location. If you want to run this code yourself, it's available with the course and you should change this path to a path that exists on your machine. The actual details of what we're going to run are located in this separate class here, _numbersToTextFile. and we're going to call this WriteNumbersToFile method. In addition, we have a stopwatch that's going to be used to show us how much time is required for this operation to take place. Let's have a look at numbersToTextFile. Here we have our WriteNumbersToFile method and you can see that we're going to write out to the console that we're beginning to log. We're going to create a generator that generates numbers and then for each integer in our generator we're going to print out a dot as we go, so we can see how quickly we're running. And then we're going to create our _fileLogger, and in this case we're going to be using an InstanceFileLogger, which is to say that it's not a Singleton, and then we're going to simply write out to the file that we are getting the next number and then we are going to log that number. When we determine that we're using an InstanceFileLogger, we're going to close the file each time. This is just to ensure that the application behaves the way we want it to in that Instance. If we were writing this without any kind of variation in terms of how we're going to do things, we wouldn't have this, we would just simply say, myLogger.CloseFile here, but because of the fact that I have written this so that it can be used with a number of different implementations of our FileLogger, I had to go ahead and give it this if statement in order to do this, only in the case where we're not using a Singleton. Finally, we break once we reach a certain limit in terms of how many numbers we're going to use, which by default will be 100, and then if we haven't already we're going to make sure that we close that file. If we run this, you can see that it's logging to the file and to do 100 of them, it's going to take about 5 seconds with a little bit of overhead. The reason for that is because we're using a delay so that when we do write to the file using BaseFileLogger, all it does is introduce an artificial delay of 50 milliseconds each time it tries to get the FileStream, which we are going to say is representative of some kind of a resource that's expensive to create. So when we construct our BaseFileLogger, you can see that within the constructor it calls GetFileStream, and that then is going to call this Thread.Sleep with some delay. When we write the line to the file, we simply call _logFile.WriteLine. LogFile, in this case, is a TextWriter and that TextWriter is retrieved from File.AppendText with the path that we've specified. Demo: Adding the Singleton Okay, so now let's look at how we can improve our application to eliminate the delay caused by this Thread.Sleep, and access a resource that's expensive using a Singleton purely for performance reasons. And so the first thing we can do is we can go in and create our FileLoggerSingleton and this is a non-thread-safe implementation using the classic pattern of the Singleton. You can see we've got a private constructor, we have a private static Instance of our class, and we have a Getter called _instance that says that if the Instance is null we're going to set the Instance to a new Instance of FileLoggerSingleton, and then return it. Now in order to change our class so that it uses the FileLoggerSingleton, I'm going to go in and set up a factory that uses the FileLoggerSingleton, which is here. And you can see that this factory simply has a Create method and returns back that FileLoggerSingleton.Instance. Now to configure my application to use this particular factory, I have to go and change one area in my Unity configuration. So we haven't looked at this yet, but in my program I'm actually calling something called RegisterTypes right at the beginning, and in RegisterTypes I'm going to new up a UnityDependencyResolver, and then ensure that its dependencies are registered. There's some other stuff going on in here for when we start to use parallel applications, but we're not going to get to there for a few minutes. So inside of this UnityDependencyResolver class, I am registering my types and I have this Factory implementation, this interface, IFileLoggerFactory, and it's currently registered to use an InstanceFileLoggerFactory. If we look at that, we'll see that it's returning back a new FileLogger and that FileLogger is simply the same as my BaseFileLogger, okay? If I want to change to now use my Singleton FileLoggerFactory to ensure that I get back a Singleton, I can do that here and then I can run my application again and you can see that it's much faster now. So what changed? Once we started to use the Singleton version, the only time that we had to call the expensive method of GetFileStream was the first time the constructor was called. Looking at that code, when we use a Singleton that's only going to be called on the very first reference to this particular class. And so by changing from an instance of this class on every request to now use a single instance over and over again, we were able to dramatically improve our applications performance. If we want to look at that actual logfile, it's here, and you can see that we're getting each number 1, 2, 3, 4, 5, 6, 7, and it's working correctly. Now in order to test this application, we're going to have to go into our UnityDependencyResolver and continue to change which particular Factory we use so that we can see how it works with each different one. And then we'll have to make a note of the times involved, etc. So if we stop our application and then go ahead and change this to _useParallel, what's going to happen is that it's going to call the NumbersToTextFileAsync instead, and this particular class here uses the parallel.For method in order to do this writing to a file. Otherwise, it's doing pretty much the same thing as before where it's going to write a dot, it's going to use the Factory to create the instance, and it'll dump out the various numbers. If we try and use NumbersToTextFileAsync using our standard Singleton, let's see what happens. So if we look at UnityDependencyResolver, we're still using our standard Singleton, and we run it, and we get an Exception. Apparently, we were trying to reference the file even though it was being used by another process. So, even though we have a Singleton it's supposed to guarantee that we're only ever going to write to this file from one Instance in our program, as soon as we start using multiple threads the Singleton Pattern breaks down. Let's stop this code and let's just jump ahead and change our Resolver to use the LazySingleton. And so if we create the LazySingletonFileLoggerFactory and run this code, you can see that it continues to work as before. So even though we're now executing in parallel, we are still able to get the correct output. And you can see that we are executing in parallel by looking at the numbers that are being output. Each thread is writing out the file using a separate set of numbers that Parallel 4 has assigned it. Each number is only going to be operated on once, but the order in which they are output to the file is no longer deterministic because of how the parallelism works. Now it turns out that testing an application by changing these fields here and continuing to run it over and over again is not very efficient. So what's better is if we just stop using our program to test our implementation and start using some tests. So if we do that and we come look at our tests, we can say that, given a single thread our FileLoggerShould, and this is a common way to write your tests so that they can be read as sentences, we can say that our FileLoggerShould LogNumbersWithInstanceFileLogger, it should log numbers with the SingletonFileLogger, with the LockedSingletonFileLogger, and with the DoubleCheckedLockedSingletonFileLogger. And we'll look at each of those in just a moment. So first off, let's run these tests and confirm that they work. Alright, so you can see that all five tests in the GivenSingleThreadFileLoggerShould have run, and each was successful. You can also turn on the times to see how long they took, and so you can see that the InstanceFileLogger took the longest period of time, the DoubleCheckedLocking took the next longest, then the LazySingleton, the LockedSingleton, and Singleton all took virtually no time at all. Let's look at how the locking works, even though we've come up with a better solution. So we have the LockedSingleton, and if we look at that here in our FileLoggers here, FilLoggersThreadSafeSingleton. And this lock on this object here whose sole purpose is to provide this lock, so we have a lock object here, is going to occur every time someone tries to get an Instance. And so in a multi-threaded environment, this is going to be an area of contention. It's going to serialize all access to our Instance, but it's going to cause things to wait for this lock to become available. Also, it's possible that this will still fail, and so another pattern that actually has been described as a separate pattern from the Singleton is called the DoubleCheckLocking Pattern. And the DoubleCheckLocking Pattern actually goes and checks to see if the Instance is null. Then it institutes the lock and then verifies once more whether the instance is null, since it's possible that another thread has managed to get in there and create it in that one moment between this operation and the separate operation. And only then does it then create the instance. There are some problems with this particular pattern, the main one being that it's easy to get wrong, and secondly, that although C# and Java share many similarities, this particular pattern does not work in Java. If you're only a .NET programmer, that's not very important to you, but if you happen to cross paths with, you know, both the Java side of the fence as well as .NET, you should know that the DoubleCheckLockingSingleton Pattern is not ideal in the Java environment. Because it uses locks, it's also going to be a little bit slower than some other implementations. If we look again at our LazySingleton and we see how it's implemented, it uses a Nested private class and relies on the fact that type initializers in C# are only called Lazily when they're first requested, so this internal static reference here to the FileLoggerLazySingleton, will only be initialized when this particular Nested Instance is first requested using the Instance property of our FileLoggerLazySingleton. Let's go back to our tests and see how they work in a multi-threaded environment. GivenMultipleThreads our FileLoggerShould and we can see that it should LogNumbersWithInstance, it should log them with the Singleton, etc., etc. Some of these are going to be difficult to test all at once, so we're going to run them one at a time. And so let's run this unit test and you can see that this particular one fails and it fails just like our example did where we're now getting an IOException with multiple threads trying to reference the same file. If we come in now and look at the SingletonFileLogger with multiple threads and we run this code, it too fails. And again, we saw it fail using our program as well. Next, let's look at the LockedSingleton. We'll go ahead and run this. LockedSingleton works, and if we check the timing on that it takes about .21 seconds. Then we try the DoubleCheckLocking, which we expect should also work, and it does, taking about 0.25 seconds, about the same time. And finally with the LazySingleton we can run this unit test as well, and we see that it runs perfectly fine in about the same amount of time. Now I've mentioned that an IoC Container is the ideal place for us to determine whether or not a class should be referenced as a Singleton or not. In this case, I've been using Unity. Unity is something you can get from Microsoft. You can add it to an existing application if you've got the latest code for Visual Studio by saying that you want to Add, let me see under references, you want to Add a Library Package Reference, and that will let you add Unity or any number of IoC Containers such as StructureMap or Ninject. So in my UnityDependencyResolver I create a Container called Unity, new it up, and then I need to call this RegisterType in order to assign these various types to it. You can learn more about IoC Containers in another course on Pluralsight on-demand, but one of the features that most IoC Containers will allow you to do is to set the lifetime of the object that you're registering using Unity, we can set up the Lifetime such that it will behave just like a Singleton. Let's look at that in some unit tests. The first thing we want to do is verify that we can return the same instance from Unity when Unity is configured to do so. So, I have a Container and I'm going to register my Type of FileLogger and I'm going to specify that it should have a ContainerControlledLifetimeManager. This is a rather verbose way of telling Unity that you want this particular type here to be a Singleton. Now how can we test whether it's a Singleton? Well, if we find that each time we ask for a reference from the Container to this particular interface, that we get this same instance, then that follows that it's following the definition of a Singleton and so we can assert that these two instances are the same, and if this passes, then we know that this is actually behaving like a Singleton. If we run these tests, we can see that, in fact, they work as expected. Here, we can assert that these two instances are not the same and what will happen is if we simply register this Type without any additional parameters here, the default behavior is to give us a new instance with every request. And so what happens here is that first Instance is going to run and become one Instance of FileLogger, and the second Instance will try and be another Instance of FileLogger. Now because we have decided for whatever reason that our BaseFileLogger is going to hard-code the file path that we're using, and further because the constructor is calling the GetFileStream method, neither one of these by the way is a best practice, we're going to have some problems when we try to implement this. So I'm going to turn off the Ignore here and we'll run this test, but we know it's going to blow up because when it tries to new up the second instance that's trying to open up the same file, we get an exception that tells us that the process cannot access the file c:\developmen\scratch\log\logfile.txt because it's being used by another process. This tells us very clearly that we're actually creating another Instance and although our test does not come back and tell us that they are not the same, which is what we would like, the fact that it gives us the Exception does tell us that they are not the same Instance. If we wanted to run our test such that we could still pass the test, we need to be able to expect the Exceptions occurring. So there's an attribute for that called ExpectedException, and then you have to give it the type of the Exception. And in this case, the underlying Exception, it turns out, is this IOException here. But the Exception that our test is going to see is Microsoft.Practices.Unity.ResolutionFailedException, So we'll take that Exception and we'll use that as our Type, and then if we run our test again we get success. So we are now expecting for the Exception to occur and if something were to change, for instance, with how Unity behaves, our test would stop working the same way. Now that we have this ExpectedException, we can run our test successfully, but we still can't run our first test suite because unfortunately, since we're dealing with Singletons and since we're dealing with real files being opened, we haven't set up a way for us to close those files easily. We could do that, and that would make it so our system would be a little bit more testable, but as it stands now, whichever one of these tests runs first is going to open up access to our LogFile and prevent the other tests from running. So if I run this test all by itself, we can see that it runs. Likewise, if I run the second test all by itself, it too runs successfully. But if I run them both together, they have issues. And the reason for this is that first one still has a reference now to that file, which causes the second one to fail. These kinds of side effects are one of the things that makes Singletons and Statics very difficult to test. And that is one of the reasons why you should try and avoid using them in your applications whenever possible. Related Patterns The Singleton Pattern is part of the creational family of Design Patterns and as such, it is related to other creational patterns such as the Abstract Factory, the Factory Method, and the Builder Pattern. It's also worth considering the fact that a static class in C# is very similar to a Singleton, but has additional downsides that even the Singleton does not have, such as the inability to use inheritance, as well as no easy way for you to bypass the Singleton for implementing testability. Static Classes generally should only be used if they have no state, and thus are simply a utility that operates on the parameters being passed into them. Static Classes tend to introduce a lot of tight coupling within your application, making it more difficult to test or to refactor. References There are a lot of great books on Design Patterns. The first one that I recommend is the classic Gang of Four text called simply Design Patterns. The next four books here all discuss Design Patterns in one way or another. These three, Design Patterns Explained, Design Patterns in C#, and Head First Design Patterns are all great books that cover with practical examples how Design Patterns can be used. The Head First Design Patterns book is a very different approach to the topic and I recommend it because of the fact that it makes it much easier to pick up Design Patterns if you're not familiar with them. C# In Depth has some great coverage of the Singleton Pattern in particular, and this particular article here was used as the reference for some of the patterns shown in this particular Pluralsight video. We already talked about some of the Related Patterns such as the Builder, Abstract Factory, and Factory Method. Look for these on Pluralsight on-demand in the Patterns Library. Summary In summary, the Singleton Pattern is one of the simplest Design Patterns. It's used to ensure that only exactly one instance of a class exists within a program. Although it's simple, it is very easy to get wrong and it can result in a more brittle and less testable design of your application. We talked about the Single Responsibility Principle, which you can learn more about in the Principles of Object Oriented Design course on Pluralsight on-demand, and it describes how an object should have only one responsibility. It turns out that Object lifetime management, in terms of how many Instances an object should allow to exist within your application is a separate responsibility form whatever your class is actually doing. This can usually be better handled by an IoC Container that has responsibility for this. We saw in our example that Unity is a particular IoC Container that Microsoft ships that can be used for this purpose, although there are a number or other IoC Containers that will serve equally well. This has been the Singleton Design Pattern. My name is Steve Smith. Thank you for watching Pluralsight on-demand, and I hope to see you back again soon. Service Locator Pattern Introduction Hi, this is John Brown, and this is another module in the Design Patterns Library. In this module we'll review the Service Locator Pattern and when and how to implement the Service Locator Pattern to simplify the code, provide separate responsibilities, and increase maintainability. The Service Locator Pattern is a creational pattern that was identified, not as part of the Gang of Four's creational patterns, but rather identified more as a pattern that was in use by Enterprise applications to help clients find services on remote servers. We see it referenced in the Core J2EE work on the Business Tier. With the advent of Inversion of Control Containers, we see the Service Locator referenced more and more. Containers such as Spring.NET, StructureMap, Ninject, and Castle Windsor, provide object construction that helps to decouple the calling class from the dependent object. The implementation of an IoC Container is typically done using either a Factory Pattern, Dependency Injection or a Service Locator. Motivating Example A good example of when to use a Service Locator is when we implement Logging. It is used throughout the application and is independent of any particular business function. Initially, it's quite easy to implement, but often it needs to be modified as the environment or deployment changes. Our apps start out with custom Logging built by us, usually embedded directly in the application. As the application evolves, we will break out the Logging as a separate function, but in general it is written or tied specifically to the application. To change the Logging Provider, the application must be modified and adapted to the new Logging Provider. By adding a Service Locator between the application and the Logging Provider, we will be able to abstract the Logging Provider from the application and the application from the Logging Provider. This will allow us to change the Provider more easily. This can be simply a different version of the same Provider or a completely different Logging Provider. Demo: Simple Version So I have here a Service Locator demonstration where I have a very simple application that's completely contrived. In this application we're simulating menu actions by the user. The user might click Button One here and we're going to indicate that Button One was clicked. In a real application this would go off and do some work or load a form or something. We also have Button Two, but as an application developer I might want to record what actions the user has taken during the lifetime of the application. So, let's take a look at what the code would look like if we were to write this as just a simple app that we've thrown together ourselves. We have the MainWindow code here, and in this we see that the EventHandlers are doing a simple Button One Clicked and we're showing that in the textBlock, and then we're going to Log the UserActions. If we look at the LogUserActions method, we see that it takes in a string, creates a new StreamWriter to an "actions.log", and writes the line and flushes the contents. This is how most Logging begins in an application, a few lines of code that the dev throws in there, and later on they expand on this. So we can go see what the logFile has. We can go to the ServiceLocatorDemo and expand the files, pull open the file, and we can see that Button 1 Clicked and Button 2 Clicked was recorded. It's a very basic Logging application. If we want to change this, we're going to have to come back to this code and we're going to have to modify it. We can't actively swap it out depending on what we're doing. Clearly this is written as part of the MainWindow. This function is more than likely going to be needed elsewhere, so it would behoove us to improve this process for future use. Intent So what is the intent of the Service Locator Pattern? The pattern is designed to help abstract the application from the services, the consumer from the producer, allow each to be independent of the other. The Service Locator will play the Middleman and allow the consumer application to find and connect with the service. The goal is to allow a change in the service without recompiling the application. We wish to simply identify the service through a configuration so that we can adjust the service or change the service depending on deployment situations. We may use a service for logging that uses a Windows event log when deployed on Windows servers and a file-based log on Unix servers. The ultimate goal is to have Non-Programmers modify the configuration and adjust the services without the assistance of the developers. If we look at some Real World Examples of these situations, we can see similarities with a traditional telephone operator or 411 service. As a consumer of the telephone system, I may not know the telephone number of a business, so I use a trusted middleman to look up the telephone number by name, return the telephone number to me, and optionally make the connection directly to the business. Whenever the business changes its telephone number, it registers the change with the telephone company and is made available to the operator or 411 service. On the internet, the equivalent service is the Domain Name Service. Prior to the DNS, each computer had its own lookup called the Host file, where the name of the machine was mapped to its IP address. Whenever the IP address of a machine changed, all other machines had to be manually modified. By adding the DNS as a Service Locator, each machine only needs to register the IP address change with the DNS, and each consumer of that service will look up the IP address from the DNS using the machine's name. Structure So here is the structure. What we see from this is that the Service Locator is a single class that provides two sets of methods, methods to register or add a new service and methods to find or get a service from the Locator. The Client application, or MainWindow in this case, has a reference to the ServiceLocator and to the interface that the service implements. In order to use a service, we must have a contract that either implicitly or explicitly provides the interface to the service. We see here that the LoggingClass, which has been developed internally and implements the ILog interface, notice that it does not have any reference to the ServiceLocator or the MainWindow. It is independent and can be developed independently. Demo: Improved Version Okay, let's look at an improved version of this application, one where we have added a basic ServiceLocator. Let me start by taking a look at the ServiceLocator. We see here a basic example of the ServiceLocator class. In this case, we see that the ServiceLocator has a Hashtable called services that provides the mapping between the keys or the types of services that we're looking up and the actual classes or instances of classes that provide the implementation. It is divided into two sections. We have the AddService methods and we have the GetService methods. If we look at the first AddService method, we see that it is AddService a generic implementation AddService, where we pass in also a type instance (T t). We use the name of the type information to register with the Hashtable as a key, and we pass in as a value an instance of the service that we are registering. We can also register that service as a type of T given a special name and the same instance of the object. In addition, when we return or get services out of the ServiceLocator, we can use the method that passes in the service of a type T, which will use the name to look up the service in the Hashtable, cast it to the appropriate type, and return the service. Or we can look it up by generic name of the serviceName. It will then look it up in the Hashtable and cast it to the appropriate type. Now that we have a basic ServiceLocator implementation, how do we wire that up? Well, we originally had in the MainWindow, we used to have the Logging method at the bottom here. We have pulled that out into a separate class called the LoggingClass where we have each of the Log methods, a basic Logging method that captures an initial string that's passed in, and a formatted Logging method that uses string.format to prepare the message before it's logged. The original Logging method is the same, where it's simply creating a StreamWriter for the "actions.log", writing the text, and flushing it out. This class is dedicated to Logging and has no other dependencies. Now to wire it up we look to the Application_Startup. In the Application_Startup event, we see that we have the ServiceLocator, we call the AddService method and pass a new instance of the LoggingClass. It will from this infer the proper type and call the AddService method of the ServiceLocator. To get the service, we will look at the MainWindow class and we see here we've added a class level instance variable that is getting the service directly from the ServiceLocator by passing in the type of class that we're retrieving or the LoggingClass. If we run the application, we can see that the Logging is occurring the same way and that the logFile is created properly. What we notice here, though, is that the code that was previously embedded within the MainWindow is now dedicated to an external LoggingClass. This is improved, but it is not where we want to be in the end. Other Providers So we've seen how to implement a ServiceLocator to separate our internal Logging Provider from the consuming application, but the real goal would be to use an externally developed provider. Why would that be important? We can leverage the work done by other groups who have dedicated their work to Logging. Let them specialize on all of the various logging styles and techniques and allow us to concentrate on our application. The provider may even be specific to the environment. Do you really want to test your Logging Provider over 200 different platforms? Some examples of Logging Providers are Log4net. Taken from the original Log4j, it is a very simple provider that can log to several different formats and appenders, but it has not been modified since 2006. NLOG is a newer Logging Provider that is in active development and is written for the .NET framework specifically. We also can use Logging from the Microsoft Enterprise Application Block if you are using the other application blocks and wish to tie them together. The important thing to note is, with a ServiceLocator we already have defined the contract and the application as the ILog interface. The external Logging Provider will not know anything about the interface, so we may need to utilize another pattern called the Adapter to bind the Logging Adapter to the Logging interface and register it with the ServiceLocator. Demo: Advanced Version If we look at this more advanced implementation of the ServiceLocator, we can see that we've added another feature called the ILog interface. This interface will abstract the LoggingClass from the calling application. We see that the LoggingClass now implements the ILog interface and provides two methods, which are the same two methods that it provided before. We've also modified the MainWindow to ask for the ILog interface instead of the LoggingClass Service. We also gave it a common name called the "logger". We can see that the wiring of this in the startup of the application is a little different. We've now used the ServiceLocator to Add a Service, passing in the type of ILog instead of LoggingClass. We're giving it a friendly name and we're calling in the instance of the LoggingClass. If we run this, we'll see that the application behaves just like it did before, a couple of Button Clicks, we're going to see the same Logging file, actions.log. So what we want to do now, by adding yet again another layer of abstraction, we can now consider adding in a different LoggingClass. I've implemented here a LogAdapter for log4net. In this case, it implements the same ILog interface. We're using the log4net style of creating a Logger using their static LogManager, and we implement the same two methods that we implemented before. Now normally this would be done in usually an external DLL so that you wouldn't have to recompile this application, but in this case I've included it for simplicity. Now how do we take this and actually, through configuration, swap it out? Well, what we've done is I've taken and added to the ServiceLocator a new method called the RegisterServiceFromAppSettings. This allows us to abstract the construction of the Service. In this case, it uses the AppSettings to look up the serviceName and return the name of the logger. I will then instantiate that logger using reflection, and add it to the ServiceLocator. If we look at the App.config, right now we can see that it's using the logger that's part of the LoggingClass, but what we can do is we can swap that out and we can use the LogAdapter, I'll comment that out, and here's the configuration for log4net. Now it's going to put the FileAppender in the same "actions.log", it's going to change the display layout and give us some more information, and we realize that if you read the log4net documentation you'll find that there's lots of different appenders that we could add without actually changing any of the class. We need to make one more modification. Instead of directly adding the class to the ServiceLocator, we're going to use this configuration option to register the Service using the AppSettings and the name of "logger". So let's do that and we'll walk through this really quickly. Okay, so what we have here is as we're stepping through we're going to pick up the serviceName, okay, and we'll step into this. So we've got the instance of the loggerEntry, which is the LogAdapter. We're going to create an instance of that and we're going to register the Service. So now as we go through and we instantiate the MainWindow, we're going to pick that same "logger" back up, except we're going to pull it back as type of ILog and we see that it's returned the LogAdapter. So when we go to log, we'll be picking it up in the new LogAdapter, which will it out to the same file, but using log4net as the logger. If we go take a look at the results, we can see that the first logger dumped it in as Button 1, Button 2 Clicked, but in the second logger, which used the same file, it appended directly to it and used the log4net's more rich environment and more rich details to show that not only it did capture Button 1 Clicked, but it captured the date and the time, where it was coming from, and some various other threading information. So under this implementation we can now easily switch back and forth and actually swap between our loggers by just changing configurations. So let me close all these documents and let's open the config and we're simply going to comment out this class, expand this one. I'm going to comment out the log4net section just so there's no conflicts, and we're going to run the application. We're going to go back, do a bunch of Button Clicks, examine the log file and notice that it's been completely changed purely by configuration without any changes to the code. Benefits By using the Service Locator, we can see the benefits and supporting the SOLID Design principles. Single Responsibility, each component can concentrate on the specific service. In this situation, the MainWindow concentrated on the application, and the logging classes were able to concentrate just on logging. Open/Closed principle, modifications to the consumer were not necessary when the producer changed. We were able to swap out each of the classes. We could also have modified the LoggingClass without changing anything about the caller, as long as the interface was consistent. Liskov Substitution, we were able to reduce the service directly to their interfaces and that was the only exposure each of the logging services had to the client. Interface Segregation, each interface can be specific to the type of service. Notice in the Service Locator, that I registered each service as an ILog. As we add more and more services, I wasn't using the same interface to register all of my services, I was using an interface specific to the service that was required. The Service Locator did not care, nor was it required to have a common interface to be registered with the Service Locator, it just simply needed a way to identify each of the services, either by the interface or by a specific name. Dependency Inversion, the consumer is only dependent on the service interface and the service locator, never the specific service. We have inverted the dependencies and made the service dependent only on the service interface and made the application only dependent on the service interface. Consequences Consequences, what are the consequences of using the Service Locator Pattern? Well, it is Global. Any client can access the Service Locator and gain access to the service resource. Availability, we do not know if a service is properly loaded and is ready to be used. We are simply using the Service Locator to locate the service and wire up the client or the consumer to the service or the producer. As such, failure is always a possibility. The caller must know how to handle the failure. The service will not be guaranteed to be there. And Lifecycle, the Service Locator does not handle the lifecycle of the objects inherently. The Service Locator will not provide the lifecycle management of multiple objects or a single object. It is simply providing the lookup. If you're looking for something more advanced, you might need to look to additional technologies. Related Patterns Related Patterns. There are some related patterns, such as the Obverser Design Pattern, which allows a Service Locator to become more robust. The Observer Design Pattern would allow us to locate new services when they become available by monitoring things such as the file system and locating any additional DLLs that could be provided as part of the service. We could allow a dynamic generation or a dynamic discovery of DLLs and services, registering them with the Service Locator and providing them to the applications when necessary. Proxy Design Pattern, we will often use a service locator to match a proxy to a specific implementation. The clients often will have a proxy. instead of an interface, they will actually have a class that is providing the robust proxy, and the specific implementation of the service will not be known, except going through a service locator. We saw already that we need to use the Adapter Design Pattern to adapt a service that doesn't quite match an interface. We will provide an adapter to allow that service to bind to an existing application. Dependency Injection, instead of looking up a service from a middleman, we use an assembler to provide the service to the consumer when the consumer is first created. In this fashion, the consumer will not even need to know about the service locator or any middleman to gain access to the services that it requires. Summary In summary, we've shown how to use a service locator between the application and the logging services to provide a clean separation that allows for the logging service to change without modifying the application. We've also shown how to use an adapter pattern to allow external libraries to present themselves as consumable services. We've gone from this, an application with the logging built in, to an application like this where we have multiple options on how to provide Logging Providers, Logging Adapters, and decouple the application from the services that it requires. A service Locator is not the only pattern or method that can be used to match up producers and consumers of services. IoC Containers combine many design patterns, especially dependency injection and service locators to achieve robust object creation. This helps to match up both the consumers and the producers during object creation. In addition, recently new to the .NET framework is the Managed Extensibility Framework that allows you to create and bind services as part of the class declaration using attributes. I hope you've enjoyed the Service Locator Pattern, and I encourage you to examine the other creational patterns in the Design Patterns Library. Good luck on your journey to being a true software craftsman. State Pattern Introduction Hi, this is John Brown, and this is another module in the Design Patterns Library. In this module, we'll review the State Pattern, and when and how to implement the State Pattern to simplify the code, provide separate responsibilities, and increase maintainability. Behavioral design patterns help us write code that can adapt to the situation. The patterns listed here were first documented by the Gang of Four in the early 1990s. Some patterns help in communicating between two objects, such as the Chain of Responsibility, the Command, and the Mediator Patterns. Other patterns change how the actions or the methods of an object behave based on configuration, such as the Strategy Pattern. The State Pattern, however, allows the object to change the method's behavior, not through configuration, but based on the state of the object. Let's take a look at a simple example of where the complexities of managing the different branches of logic within methods, can quickly become overly complicated. Motivating Example Let's take a look at an example of Work Item Tracking. Work Item Tracking is simply the bug tracking systems that we have all used such as Bugzilla, Clear Quest, and Team Foundation Server. They all have in common that the work items or bugs go through a transition process. In each step of the transition they change states, and along with the change of state, the behavior of the work item also changes. Some methods become unavailable, while others have different behaviors based on the state. The states and behaviors can even change based on the template that is applied to the system. In the TFS example, the CMMI template is a four-state system with Proposed, Active, Resolved, and Closed, while the Agile template only has three states. So what is an indicator that a State Pattern should be used to simplify the code? Well, a simple version of the work item tracking system we might see code such as this, where inside each method or action on a work item there is a case statement. The case statement changes behavior of the method based on the state of the object. In this case, when the Delete method is called and the object is in a Proposed state, we can still Delete the item or Remove it from the work items. However, once an item has become Active and someone is working on it, we can no longer remove the work item, so we simply provide a message back to the user. The same thing with an item that already has been worked on and is now being tested, it's in a Resolved state and you Cannot Delete it. However, in this simple work item tracking system, once an item is Closed and it's been properly validated, we'll then again allow the user to delete it. In this way, based on the state, two possible outcomes can occur. Either we provide a message indicating that we cannot do the work or we do the work. Demo: Simple Version Let's take a look at an implementation of this simple example. I have here our command line interface of a work item tracking system that is using the basic CMMI approach that TFS uses with four states to the work items. There's Proposed, Active, Resolved, and Closed. On a work item, you typically can create a work item, edit the title and the description. We can open the work item, which essentially moves it from Proposed to Active, we resolve it, moving it from Active to Resolved, we verify it, moving it from Resolved to Closed, and we also can print details about it. It's a very simple example, but for this I think it'll work. So, let's take a look. So we can do a quick create 1 test1 test2, so we've created a new work item. It's in a Proposed state and has test1 and test2 as a title. If we want to, we can verify the work item, and we get back an indication that the work item is in a proposed state and cannot be directly closed. So let's open a work item or let's open Work Item, print out the state, and now let's try to delete it. So, we can't delete it, but if we move that work item to resolve and then we verify that work item, we can now delete it and we find out that the object no longer exists in the database. So let's take a look at how that is actually implemented. Demo: Simple Version Code Review This implementation is broken up into two basic classes. There's the main program here, and this is a very simple example, so it's going to create a connection to the Data Source. In this case, we're using an XML data file and we're using the XML UnitOfWork. This is also one of the design patterns in the Design Patterns Library. This will parse the command line and pull out some variables for us to work with. It will determine which action we are taking and call the appropriate method on the work item. So, for example, Create is going to create a new work item, it will Edit the information and Print it out again. Or, we're going to open it and it'll call the Open on the work item. That's what the basic program does. If we take a look at the WorkItem, in the WorkItem class we can see the basic properties of the WorkItem. We have the ID, the state, title, description, these are all just simple properties. Then we have the actions that we can perform on this WorkItem. If we open up one of the actions, for example the Open, we see in each of these there is a switch statement that changes the behavior of this action or this method whenever the state changes. In this case, when we open an item that's in the Proposed state, we'll just change it to the Active state. If an item is already Active, we'll indicate that with a message. We'll also indicate messages for the Resolved and Closed states. Each of the methods does the same switch statement, checking the state of the WorkItem before it performs the action. This quickly becomes a problem in maintaining each of these WorkItems. This particular WorkItem is going to get very, very large in terms of the code, and we're not going to notice as we work with this, all of the problems that the WorkItem may have. Issues with the Simple Approach As we can see, there are some issues with the Simple or Naïve approach. No extensibility, all of the states are hard-coded in the program. To add a new state, we must go to each method and add a new case to all of the switches. Mixed Concerns, all of the actions for a particular state are spread throughout the code. A change in one action for one state may have an effect on the other states, which means we need to test it, but these are difficult to unit test. Each method has a large number of permutations for the inputs and the corresponding outputs. This leads to a lack of testing and possibly complicated unit tests. All of these issues lead to a maintenance problem. Intent So what is the intent of the State Pattern? Well the intent is to change the behavior of the object with each change in the state. As I change the state of the object, I expect all of the actions that go with that state to also change. I want to, though, encapsulate that logic of each state into a single object, something that is in one area that I can test by itself. If the state is a Proposed State and there are several different actions, I want to be able to test those actions independent of the other states in the application. I want to allow for the possibility of dynamic state discovery. In the current application in the simple or naïve approach, we had all of the states in the code, but the State Pattern can allow for the dynamic discovery of new states and the program should be able to integrate them into the process. And, of course, with all of this we want to make unit testing easier. If we make unit testing easier, we have a good understanding of the code, we have a good belief that the way we have implemented the code is correct. Structure So here is the Structure of the State Pattern. In the State Pattern, we create a hidden set of objects that represent the actions of the object for each state. In this pattern we divide the code into three pieces. The original object, which is the WorkItem, the interface of actions, which is ICommands, and a specific implementation for each state, Proposed, Active, Resolved, and Closed. In this example, I have set each of the states to be a child of the BaseState. This provides some common usage of methods. We see here that the WorkItem and each of the state objects will implement the same interface. The actions are simplified and reduced to the common actions for each of the states. In this case, we no longer have a special action to transition between, say, Proposed and Active, we simply call the SetState method and change the state. The WorkItem class will internally instantiate a state object, one of the states Proposed, Active, Resolved or Closed whenever the state changes and shuttle over any method indications directly to the state object. In this fashion, it will act as a proxy for the actual implementations. So the first step in implementing the State Pattern is to define the contract that all of the objects and all the state objects will implement. In this example, I'm implementing four methods. Delete, Edit, and Print are all common from the original class. The last method, the SetState, provides the method to change the state. Demo: Advanced Version Code Review Let's take a look at the implementation of the State Pattern. In the Main Program, the structure is pretty much the same. The program starts by creating a Data Connection, parsing the command lines, and then executing the commands on the WorkItems. What is different here is that the actions on each of the WorkItems have been reduced to the ICommand interface. So instead of all the individual actions, we now have the SetState command. The WorkItem has been modified as well. On the WorkItem I've implemented the ICommands interface and I've added two new instance variables, one for the State and one for the stateCommands. The WorkItem now implements each method of the ICommand interface, and each command in the ICommand interface is implemented by shuttling the method call to the stateCommand Objects methods. So if we take a look at SetState here, we have the stateCommands and the SetState method passing in the string parameter. Same thing for the Print, the Edit, and the Delete is a little bit more complicated, but it's essentially the same thing. So all of this is pretty simple, but when the state changes, the stateCommand object that provides the actual work also needs to change. This is done by implementing the state property. So in the state property, we see here that the value of the state being set is stored in the instance variable, and when the state changes, the state properly will also instantiate a new stateCommand object based on the state value and passes in a reference to the WorkItem. As noted in the code, this does not strictly separate the state from the WorkItems, but you can see here how that functionality can quickly be added so that the WorkItem itself may not know anything about the states in the future. What you do notice is that apart from the state change, there is no longer any case statements in each method of the WorkItem. So as we toggle here, if we look here, the WorkItem here is simply concerned with the data items and swapping out the stateCommand object when the state changes. So at the top here we have the instance methods for creation, finding of a WorkItem, we have the data values that are stored in the public properties, and then we have each of the instance methods that are related to the ICommands interface, but we no longer have all the case statements that were making the whole WorkItem convoluted. States The states themselves have been broken up into a separate class for each state. If we look at the active state, we see how the Active class is inherited from the BaseState and implements the ICommands interface. The inheritance from a BaseState is not required, but it shows that we can still leverage commonality in the states as long as they all implement the ICommand's interface so they can have a relationship back with the WorkItem. Notice that in the construction of the Active class, the reference to the WorkItem is captured as the owner. This allows the states themselves to pass information back to the WorkItem or use the WorkItem in one of the method calls. We see this in the execution of the Print method. In the Print method, the WorkItem is passed directly to the Base classes method for implementing of Print. If we take a look at the Base class, we can see that for all of the states it takes in the WorkItem and simply prints the properties out. A difficult method to implement is the Delete method. In this case, the Delete method of a particular state needs to determine if the WorkItem can be deleted, and send that information back to the WorkItem. The reason is, this WorkItem is part of a collection, it doesn't really know how it's being stored. So in this case, I would go back to the original program. We can see that the WorkItem is being stored in this XML UnitOfWork, which is essentially just a data file, an XML data file, so it's a collection that's being stored. What we'll do is we'll look at the WorkItem and we'll see how that actually is implement that. So we have the UnitOfWork here, and on the UnitOfWork we see that it has a collection of Entities, which is the IRepository Pattern, so it's going to add the Entities when it creates them. Well conversely, when we delete it we're also going to need to remove the items. So in this case, the Delete for each of the states determines whether or not that state can be deleted, that item can be deleted when it's in that state, and returns a flag based on that information. So in this case on an Active one, the Item is already Active, we cannot delete it, so it returns false. If we look at a Proposed one, we simply return true. The WorkItem itself, which understands how the data is stored or has a better understanding than each of the states, then takes that information as canDelete and applies the appropriate method, in this case removing the Item from the collection of Entities to actively execute the Delete of the Item. State Change The other one that is more complicated is the SetState, which determines how the different states will change. If we look at the Active implementation, we can see, and in this case we start to actually see a case statement, but what's unique about this case statement is that in this case all of the Items are related to the Active state. So we have if we are requesting a change from the Active state to the Active state, it'll indicate as such, or it'll allow a change from the Active state to the Proposed or Resolved, simply by changing the state directly on the WorkItem. Any other state that is presented will result in a message saying that this does not make sense. Demo: Advanced Version Okay, let's run the implementation of the State Pattern. We have roughly the same interface here. Notice that some of the commands are a little different. We dropped the state specific commands and have gone with the general SetState command, but other than that everything is pretty much the same. So we have state, we're going to create a new one, we'll call it test1. We can then try to change the state and in this case we're going to call it, change the state to closed, it'll indicate that's not possible. Resolved, as well is not possible, so we're going to set the state as Active. We can print it, we can also edit the contents, edit, this is the description, and we can try to delete it. So as you see, the functionality is essentially the same with a slight variation on how we actually call the method. Benefits The benefit of the State Pattern should be obvious by now. One of the immediate benefits is the Separation of Concerns. Whereas the WorkItem used to contain all of the logic about creation, the data, the state, and all of the method behaviors, it is now dedicated to simply the creation of the WorkItems and the data they contain. The method behaviors have been abstracted away and are localized to the specific state of the object. The state previously was captured as a data element of the WorkItem. If the state is indicated by data values only, the actual state, especially a derived one, is not always clear. By using state objects, the actual state can be made explicit and clear since state objects rarely contain any internal data and are only providing method instantiations. The state objects themselves can be reused. This is where other design patterns such as the Pattern can be used so that only a few instantiations of the state objects are created at any time. Often, the state objects will only have a single representation implemented by the Singleton Pattern and will be reused throughout the application. All of this provides a way to simplify the program. This allows for a clearer understanding and easier testing, which all leads to greater maintainability. Known Uses So where would you see the State Pattern in use? The canonical example from the Gang of Four book is the TCP Connection, where depending on the state of the connection, each of the methods to open, close, and acknowledge the collection had completely different behavior depending on the state. Another popular example is how the cursor and the behavior of the cursor change when performing various mouse selection activities such as Drag & Drop. When the cursor is not over text or any images, we'll see the arrow pointer. When the cursor is over an image, we'll often see crosshairs and we'll see the I symbol when it is over text. With each change, the options available are different, the event handlers are different. And we'll also see the State Pattern in use in a client server fashion when there is state involved such as an Email POP Server. Conversely, we'll typically not see it in a stateless paradigm such as HTTP communications. Summary In summary, we can see that the State Pattern is a behavioral pattern and should be looked at along with the other behavioral patterns whenever the methods of an object need to change their actions during Runtime. We saw how, by using the State Pattern, we can separate the different concerns and divide them up into classes and objects specific to the state the context object is in. If you find yourself writing a lot of switch statements in your code referencing a common field or fields in your object, you might find that the State Pattern will help you keep your code more organized and more clear. We can also see that by expanding on the State Pattern we can even implement a system where the states are not known at design time and are discovered dynamically at Runtime. I hope you've enjoyed the State Pattern and I encourage you to examine the other behavioral patterns in the Design Patterns Library. Thank you, and good luck in your journey to being a true software craftsman. Strategy Pattern Introduction Hello my name is David Starr, and today we're going to be talking about the Strategy Pattern. Now the Strategy Pattern is arguably one of the simpler Design Patterns we might encounter in the world of Design Patterns, and it's a great place to get started if you're just introducing yourself to this idea of common patterns of Object Oriented Software Design. Now the Strategy Pattern is also very practical. I find a lot of uses for it in day-to-day coding, and it can really help us clean up some of our existing designs. Let's jump right in by taking a look at an example of why we might want to use the Strategy Pattern. Demo: Motivating Example We'll start by taking a look at some example code. Our example code will be that of a shipping calculator. The idea here is that we have a customer who is maybe checking out on a website, and we need to calculate the cost of shipping their order to them. Now that cost may vary depending on how the customer has chosen they want the package to arrive. The customer has the choice of choosing Federal Express or FedEx, UPS or the Unites States Postal Service, and we're going to calculate a different cost depending on which carrier the customer has chosen during the checkout process. Okay, here we are in Visual Studio and we're going to take a look at our sample implementation. We're going to drive our sample implementation through some unit tests that we've written over here. We could just as easily have used a command line utility and we could have created a command line exe to run our little app, but we've got some unit tests here. Now the intent is that when we're shipping via UPS, then our particular order is going to cost $4.25, when we're shipping via the United States Postal Service it'll be $3.00, and when we're shipping via FedEx it'll be $5.00, that's what our tests are showing us. Now we can break apart the functionality of our ShippingCostCalculator. Our ShippingCostCalculator is this little class here and we're going to new it up and then we're going to provide to it an order, we get an order from this little Mother class. This is just a helper within our test project, there's no black magic here. We'll jump in and take a look. All we're doing is we're creating an order, and an order has a shipping method, so in this instance our order actually knows how it wants to be shipped and we have a destination address and an origin address. Okay, so back over in our test, we're going to pass that order to our CalculatorServices CalculateShippingCost method. From that, we'll get the cost of our order and then we'll assert that our cost is correct. Now before we go too much further, we'll just go ahead and run all of our tests and they do, in fact, pass. So we know that our algorithm is correct, and maybe that's no problem. Let's go down into the CalculateShippingCost and take a look at how this particular method is implemented. What we'll find is that the CalculateShippingCost method takes an order as its input, and this is very common syntax that we might find in code. We are going to switch on the shipping method of the order. So how does the order want to be shipped, and that could be either FedEx, UPS or United States Postal Service. And one thing about using this technique is that it's very possible that we're going to get a shipping method passed in on this order that we're not actually coding for, and so in that instance we go ahead and throw a new UnknownOrderShippingMethodException. So we've had to account for that possibility. Down here in our methods that actually do the calculation, you may imagine that in a production system, rather than just having a single one-line return, after all not everything is going to cost $3.00, we're going to go out, make some service calls, we're probably going to calculate some things like the weight of the items in the order, I don't know, there are a lot of things that go into calculating the actual cost of shipping. So this would likely be a very large algorithm, as would the one for UPS. We have a different algorithm for UPS and finally another one for FedEx. For the purposes of our example, let's just work with these hard-coded numbers, realizing that we probably have a much more complex algorithm for deriving each shipping cost. Now what are some problems that we can note about this type of implementation? First of all, our order actually has to know what type of shipping our customer preferred. That's arguably not appropriate for an order to even know what type of shipping the customer wanted. It depends on the data model and the domain that you might be using. But one thing we can see is that when we add a new shipping method, let's say for example we want to ship with DHL and our company cuts a contract with DHL to do some shipping, we're going to have to open up this class and we're going to have to modify it. Now that sort of breaks the Open/Closed Principle right away because we're going to be modifying this CalculateShippingCost method. The Open/Closed Principle states that a class should be open for extension, but closed for modification. And I would venture to say that adding another case statement here would be opening up this class for modification. And then finally, anytime we want to change any of these algorithms, we're going to need to open up this ShippingCostCalculatorService class and ensure that our algorithm for, say, the Postal Service, if that's the one we're changing, doesn't impact the algorithm that we have for UPS and FedEx. We may very well have some shared state because of the mechanism we're using here. So, there are some issues with this architecture and it would be nice if we could calculate things independently of the ShippingCostCalculatorService class, and that's where the Strategy method comes in. Intent and Applicability Before just diving in and taking a swing at implementing this Strategy Pattern, let's take a look first at its intent. The intent of the Strategy Pattern is primarily to encapsulate a related, or we could say family of algorithms, such that they are callable through a common interface, and may be used according to the appropriate situation. The idea here is that we're going to let our algorithms vary as independent classes so that might evolve separately from the classes that actually invoke them through the interface. This allows our classes to maintain a single purpose. In the case of our ShippingCostCalculator, it's going to be responsible for taking an order, executing a calculation about that order, and returning the results. What we don't want is to bleed all of the concerns of UPS versus FedEx versus other shipping services into our ShippingCalculator. That would not allow our class to maintain a single purpose. And this nicely separates the calculation itself from the delivery of the calculations results. Well what are some flags we can look for that let us know the Strategy Pattern might be applicable to our situation? First of all, we've got switch statements. Anytime we see switch statements in a method that's trying to choose which calculation it should perform, that really should be a red flag to us. There is very likely a better object-oriented way of determining that logic than a switch statement. So switch statements are kind of a red flag. Also, we know that adding a new calculation like one for DHL will cause our class file to be modified. And we've already said that we want our Open/Closed Principle intact, so these are good indicators that we might want to look at an alternative. The alternative that we have implemented is an example that creates classes for each type of calculation we want to perform and uses a common interface for each one of those calculations so that they might be shared by the calculator class. Let's see how this looks in a classic UML model. The Pattern in UML Here in Visual Studio UML Designer, we see a rather classic model or explanation of the Strategy Pattern in action. Here we have a Context class. The Context class is the class that we will ask to actually do the work. In its construction, it takes an instance, a concrete instance of a class that implements our Strategy interface. Our Strategy interface declares a method that will be the one called by the Context class to actually perform the calculation we're interested in performing. Now we would call Context.DoSomething. ContextDoSomething would then use the strategy that it was given on its constructor to call PerformWork on the Concrete class. And in this case, we have two Concrete implementations of our Strategy interface. Now how does that look given the domain that we're actually using here? We'll have a shippingCostCalculatorService, this will be our Context. You can see on its constructor that it takes an IShippingCostStrategy as a constructor argument. An IShippingCostStrategy declares a Calculate method. The Calculate method wants an order to be passed in so that it can use the information in the order to calculate the shipping cost. Well, back over here on our ShippingCostCalculatorService, we can see that the CalculateShippingCost will then also take an order. And so within our CalculateShippingCost method we'll invoke our Concrete classes Calculate method. Demo: Implementation Example As you might expect in our code, we're going to create classes for each calculation that we want to perform. These are our strategies, and we'll use a common interface for each strategy so that we can invoke it through a reference to the strategy interface within our Context class. Now, again, we'll start back over in our Test methods. We have a Test method here that is going to new up our Strategy class, this is our UPSShippingCostStrategy, and it's going to pass it to the constructor of the ShippingCostCalculatorService. We will then new up an order or somehow obtain an order that we're going to use during our calculation, and then we'll call ShippingCalculatorService.CalculateShippingCost passing that order. It's not really that different from what we saw before, with the exception that we're passing our strategy into the constructor. Really quickly, I'll go ahead and run all of our tests to ensure they pass. They do, and now we can drill down and take a look at what our ShippingCostCalculatorService is doing. When we call its constructor, it's merely taking the Strategy and holding it as a member field, and later using that strategy to perform the work of CalculateShippingCost, so that it's merely returning the call to Calculate on the Strategy itself. Now we'll take a real quick look inside these various classes to see what they're doing, it's pretty simple. Here's our FedEx Strategy, it's merely returning 5. You can, again, assume that this would be a fairly complicated algorithm that we might go through to determine our actual shipping costs. We're just returning a constant here of 5. And you'll see similar implementations in our UPS Strategy and in our Postal Service Strategy. But all of them implement the IShippingCostStrategy interface, which defines for us the Calculate method that takes an order as a parameter. Of course, that was taken as an input to the constructor for the ShippingCostCalculatorService. And we'll see in a moment that there are some variations to how we might construct all of this, but we've achieved basic Separation of Concerns between our algorithms that does the calculation, and the class that's going to provide the results. We've also eliminated the need for the UnknownOrderShippingMethod. It's now going to be impossible basically, to find ourselves in a state, see we don't need it, we can compile without. It's going to be impossible to find ourselves in a state where we're going to throw that exception, because in order to get a ShippingCostCalculatorService we're going to have to pass in the correct Strategy in the first place, so we don't have any non-deterministic behavior here. Now that we've broken our class structure Consequences Now that we've broken our class structure apart to take advantage of the Strategy Pattern, there are some consequences of our new design. For example, although we may have been taking advantage of some shared member state within our Context class previously, now our strategies really have to be self-sustaining. So they can't use the local members of the containing class, like maybe our methods did before we broke apart into separate class structures. Also, we get to write tests for our individual concrete strategies, meaning that we can build up a test harness, maybe through unit testing, specifically for our UPS test and another one specifically for our DHL test. If we're testing our Context class, these strategies can be mocked so that we can provide very deterministic behavior via a strategy into our Context class itself. Now that we're using interfaces to abstract away the strategy, that interface can be our mocking point. And finally, we can add a new strategy without any changes to our Context class or our shipping Service in our case. Now the use of Strategy Pattern is very widespread and you'd be hard-pressed to find a code base that doesn't do something like this. However, there are some very common situations in which we'll find Strategy Pattern in .NET. Specifically, delegates in C# 3.5 and greater really are just the Strategy Pattern being implemented in a different way. We're going to take a look at how that works in just a moment. Also, it's a very common practice for people writing ASP.NET MVC to use the Strategy Pattern to inject services and repositories, things like that, into their MVC Controllers. Those can then be mocked for unit testing. If your solution happens to use an Inversion of Control Container like Unity or StructureMap, this can also be very beneficial. But as we've seen, you don't have to be using complex tooling and strategies like this in order to get some good advantage from the Strategy Pattern. Variation Examples Now as we've mentioned, there are some other ways of dealing with the Strategy Pattern or setting it up and having a solution that's considered a Strategy Pattern. For example, we can use Functions or Delegates within .NET to push in our strategies or we can even use Property Injection or finally we can, instead of passing the Strategy on a constructor, we can pass the Strategy on the method call that we're making. Let's take a look in Visual Studio at how some of those alternative models might look. Here in Visual Studio we have another implementation of the Strategy Pattern that is in a different project. This one is Strategy Variation, and it does exactly what we've been doing so far, but it does so in a slightly different way. Up here at the top, I've declared three different funcs, three different Delegates, if you will, that are implemented in three different ways, just sort of to highlight the fact that this can be done in three different ways in .NET. Here we have a FedEx Strategy, the Delegate for which is declared as a method. And here we have an anonymous delegate being declared for the upsStrategy, and an anonymous delegate declared through a Lambda expression for the uspsStrategy. They could all use the same technique or not. Here we have the order that we're going to be processing. We're going to process the same order three times. And here we are newing up our CostCalculatorService and passing in the FedExStrategy and then we print out the results of doing the calculation. We then do exactly the same thing with the UPS strategy, and finally with the usps or Postal Service Strategy. So if we run that, we'll see that our strategies were run properly and each returned the expected result. FedEx was 5, UPS was 4, and Postal Service was $3.25. One thing that seems maybe a little bit inefficient here is that rather than passing in the strategy as part of the constructor, what if we created a constructor for our ShippingCostCalculatorService that did not require the Strategy to be passed in. Here we've got our new constructor there, and rather than holding onto our func as we were doing in our original implementation, we'll just take our func, actually we'll just grab it up here, we'll just take our func on the call to the method, like so, and this lets us get rid of some code. So now our Context class really is just a bare-bones class and we're going to pass our Strategy in during the function call itself. So we can flip back over here and rather than newing up multiple CalculatorServices, we'll just use the same CalculatorService several times and we'll pass the appropriate Strategy for each one. So we'll pass FedEx Strategy in here, we'll pass upsStrategy here, and we'll pass uspsStrategy here, Compile, do a quick Run, and again, the strategies were executed properly. So, what we've seen is that we can actually inject the strategy on the method call itself. It doesn't necessarily have to go in the constructor. That does happen to be the more classic implementation of the pattern, however. Summary Alright, we've seen several ways to implement the Strategy Pattern, and in its essence what it helps us do is decouple a given algorithm or service implementation, something like that, from a class that's going to deliver back the result of that work being done. It lets us encapsulate algorithms into class structures so that they're independently testable and that helps us keep the Open/Closed Principle in place on our Parent Context class, the one that's going to be using the Strategy to do work. We know now that switch statements are often a red flag for us, telling us that maybe there's an opportunity here to use a Strategy Pattern, and the good news is this is a fairly simple pattern to master and there are several techniques for doing so, for implementing the Strategy Pattern. We saw that we can do so with Delegates in C# 3.5 and higher, and we can always use that classic implementation using interfaces. Thank you very much, and I hope to see you in class sometime soon. Template Method Introduction Hi, this is Steve Smith, and in this Pluralsight on-demand video we're going to have a look at the Template Method Design Pattern. Motivating Example The Template Method Pattern is used when you have a process or an algorithm that consists of several steps, but you want to allow different implementations of this algorithm. For instance, if you need to allow variation of the details of each step or certain steps, while enforcing the structure and order of the steps themselves, then the Template Method Pattern may be appropriate. For instance, a game engine could be used for a multiplayer turn-based game such as Tic-Tac-Toe, Chess or Monopoly, might consist of the following algorithm. The game would start with a SetUpGame method and then each player would take a turn. The game would determine whether or not it was over, and if so, it would display the winner. Given a structure like this, specific games like Tic-Tac-Toe, Chess or Monopoly could easily be implemented as subclasses. The intent of the Template Method Pattern is to encapsulate and enforce the workflow or process that is not variable in an algorithm. This allows subclasses to alter specific behavior via their concrete implementation. Each subclass can redefine one or more steps of the algorithm without altering its structure. The initial base algorithm can have empty stub methods or it can have actual implementations that are then shared among various implementations of this algorithm, allowing for greater code reuse and following the Don't Repeat Yourself Principle. You can learn more about the Don't Repeat Yourself Principle in the Principles of Object Oriented Design course available on Pluralsight On Demand. Applicability You should use the Template Method Pattern when you have two or more classes that should follow the same common algorithm or workflow. This workflow is invariant and while subclasses may redefine certain steps, they may not change the algorithm structure. This is an important feature of the Template Method Pattern. Some workflow steps may be encapsulated in the Base class with a default implementation and only overridden if necessary, allowing for these steps to be reused between different concrete implementations of the algorithm. Structure The Template Method Pattern structure consists of a Base class that defines a TemplateMethod here, and that TemplateMethod's implementation calls one or more steps in an algorithm as shown here. These steps are either abstract or virtual and typically are not public, but they may be. The concrete class, then, is responsible for implementing one or more of these steps, all of them if they're abstract, and then clients will call the ConcreteClass. When a client calls in, it will call the TemplateMethod and the implementation of that method will depend on what the concrete class has overridden. in the example shown here, when a client executes TemplateMethod, StepOne is going to implement and run the StepOne method defined on the ConcreteClass, while StepTwo is actually going to still call the method defined on the Base class. In this way, you can have a ConcreteClass that overrides only certain aspects of the algorithm defined in the Base class. How It Is Used The way the Template Method Pattern is used is very straightforward. Clients call Children of the Base Implementation. Child Types Customize Individual Step Behavior. They could change all, many or just one step in the TemplateMethod. This provides an effective way to achieve the Open/Closed Principle because the algorithm itself is closed to modification, but is open to extension by creating multiple different variations of the Child Implementation of that algorithm. You can learn more about the Open/Closed Principle in the Principles of Object Oriented Design course available on Pluralsight On Demand. Consequences There are some consequences on choosing to use the Template Method Pattern. The first is that the algorithm steps must be known and relatively inflexible at the time the pattern is applied. The Template Method Pattern relies on inheritance rather than composition, which can be a limitation in areas where you are not free to have your Child Class inherit from any particular Base Class. See the Strategy Pattern for a composition- based solution to this problem. Single inheritance can also make it difficult to merge two or more child algorithms into one. You should see the Decorator pattern for a possible solution to this problem. Hooks It's a common practice when using the Template Method Pattern to implement something called Hooks. Hooks are methods declared in the abstract class that have no implementation. They are, however, called by the Template Method. These allow subclasses to "hook into" the behavior of the algorithm at various points or to ignore the hooks entirely. Hollywood Principle The Template Method Pattern helps you to implement the Hollywood Principle. The Hollywood Principle is simply stated as, "Don't call us, we'll call you." What it means is that high-level components should not depend on low-level components. The Base class with the template method is considered a high-level component - clients should depend on this class. The subclasses of the template method's Base class are the low-level implementation - they don't call anything themselves and are only called by the high-level template method. Thus, they don't call us, we call them. Implementation Example Now we'll consider two different examples of the Template Method Pattern. The first consists of the Page Life Cycle within ASP.NET Web Forms. The Page Life Cycle uses the Template Method Pattern within the framework of .NET. And if you've used ASP.NET in the past, especially the Web Forms variety, then you are already familiar with how the Template Method Pattern works. The second one will be an implementation of our own. In this case, we'll be doing some order processing and customizing the steps in an order. Let's get started with our demo. In ASP.NET, all Pages inherit from a Base class called Page. If we go to this Page, we can look at some of the methods it defines, and we'll see that it has certain methods such as OnInit, OnInitComplete, OnLoadComplete, OnPreInit, etc. These, for the most part, correspond to events also defined on the Page. We'll find that many of these events are actually defined on the Control class that Page inherits from, and so on Control we'll find basic things like OnInit, OnLoad, OnPreRender, which we can then override. The order in which this particular class, the Control class, calls these different methods is defined in the Template Method for Control, which in this case is Render. Render is then responsible for making sure that all of these other things are called in the correct order as it builds up the page's control structure and has each subclass render itself. We can see how we can override the custom behavior of an individual step within this algorithm by simply overriding different methods on the page. For example, if we decide that we want to output something to the Trace on the OnInit method for this page, we can do so with this line of code here. We can continue to call the base implementation of OnInit if we want, or if we know what we're doing we can also just delete that and remove it. We'll leave it for now and let's go ahead and run this page. Here you can see the page as it's been loaded. This is the standard default page in a new ASP.NET project in Visual Studio 2010. We've turned on Tracing for this application, so if we go to Trace.axd and refresh, we'll see here is our first request that we made and our Trace.warn statement is shown here. Notice that the entire page lifecycle is also listed. These begin and ends are all defined in the Template Method that is used to render this page. If we want to further customize the behavior, we can do so. For instance, if we wanted to put something in the OnLoad event, we can override OnLoad and within OnLoad we can add some additional Tract statements. And then when we switch back to the browser, if we refresh the page, and then review the Trace, we'll see that now we have both calls to OnInit and calls to OnLoad. So as you can see, the ASP.NET Page framework is an excellent example of the Template Method Pattern in action. Now let's look at how we can use Template Method in our own application. Consider the need to ship an order. We can define an OrderShipment class here that includes a Ship Template Method, defining three steps in the algorithm. The first one is to verify the shipping data, second we want to get the shipping label from the carrier, and finally we want to print that label to some Text writer. Now if we decide to implement this, we could create a UpsOrderShipment that can verify the shipping data, simply checking for null or empty. Then we can say that we're going to get this label from the carrier. We'll pretend that we're going to call a Web Service to do this, but in fact, we're just going to do a String.Format. And then we go to print the label, we'll just write it out to the writer that's passed into us. Now if we call this on our page, we can simply reponse.Write that we're Sending the order by UPS. We can new up a new UpsOrderShipment. This is a bad idea at this point, because we are referencing this implementation directly. What we would rather do is look up the order using an ID or something like that, and have some kind of a factory provide us back with an OrderShipment class that we can then call the Ship method on. We'll set our shipping address to be NimblePros, Hudson, OH, and call the Ship method, and let's see what this does when we run it. So here you can see it says, Sending your order UPS, and it outputs our UPS data to the screen. Let's go back and look at our implementation and see what we could do to change it or extend it. First of all, we created this Template Method using the abstract shipment class first, and thus we've created these methods that don't necessarily need to live in the client. This will become apparent when we try and extend this for additional reuse. For instance, if we take this class now and decide that we're going to implement a FedEx version of it, we can start by copying, pasting our initial implementation, and then just creating a FedExOrderShipment. Now let's say that for instance, the shipping data is going to have the same verification, we won't have to change this method at all. Then getting the shipping label from the carrier we might call the FedEx Web Service and have it be FedEx in our String.Format, but we might decide that printing is the same too. Now we can go back up to our implementation and with a little bit more cut-and-paste magic we can see how this would look using FedEx. Again, newing these up directly is a bad process, don't do this in your system. Once we've renamed our variable, we have a FedEx order now that's going to be shipped. And if we build this and run this page we get now, Sending the order UPS and Sending the order FedEx. So let's look at how we can clean up our implementation. First of all, since we're sharing this verified shipping data between these two and we're also sharing the print label, we could refactor our code so that these two methods live within our Base class. A simple way to do that would be to take this implementation of VerifyShippingData and simply copy and paste it up into the base class. We can leave it as virtual so that some future method could modify it, but now we no longer need it in our child classes, making them simpler and eliminating duplication, and so we're following the Don't Repeat Yourself Principle. We can do the same thing now with the print label. We'll leave it as virtual, as well, in case we need to change it, and we can remove it from UPS as well. And now when we're done you can see that our two implementations of OrderShipment only have to deal with a single method. Now normally we would have a suite of unit tests that would verify that everything still worked as we expected, but in this case we're just going to rely on the fact that if we refresh our page here, which I've just done, we should get the same result, and we do. So an important lesson here is that it's best to start off with your concrete implementation and then when you need another concrete implementation, create the base class and only put the things that vary into the child classes. If you try and start out with defining the entire structure in your Base class and making everything abstract, you're probably going to end up with additional duplication in your child classes that you can remove by pushing those up into the Base class. Related Patterns We've seen there are several patterns related to the Template Method Pattern, including the Strategy Pattern, which allows you to inject a complete algorithm implementation into another module, the Decorator Pattern, which you can use to compose an algorithm or behavior from several subparts, and the Factory Method Pattern, which defines a common interface for creating new instances of types, while allowing this to be overridden by multiple implementations, each defined in a child type. References If you're looking to learn more about design patterns, I recommend that you check out the following books, The first one is by the Gang of Four and it's the classic Design Patterns book. The next one is Design Patterns Explained, followed by Design Patterns in C#, these are both good books as well. However, if you were going to pick just one book to read to learn about design patterns, I would probably ask that you start out with Head First Design Patterns, which does a great job of teaching this subject. If you can only pick one of these books, I would say you probably want to get the Design Patterns book as a reference, and then if you can afford to get two of them then I would say definitely Head First Design Patterns is the one to get next. You can learn more about the Template Method Pattern on Wikipedia, as well as numerous other websites. And we talked about some of the related patterns including Strategy, Decorator, and Factory Method. Summary In summary, the Template Method Pattern uses inheritance to define an algorithm in a superclass while delegating responsibility for detailed implementations to child classes. This provides for greater reuse, but less flexibility than the Strategy Pattern, which has a very similar goal. You should remember the Hollywood Principle, which is, Don't Call Us, We'll Call You, and how it's related to the Template Method Pattern in this instance. I hope you've enjoyed this Design Pattern overview of the Template Method. My name is Steve Smith for Pluralsight on-demand. I hope to see you again real soon. Unit of Work Introduction Hi, this is Scott Allen of Pluralsight, and in this module we're going to look at the Unit of Work Design Pattern. The Unit of Work is another pattern that's quite commonly seen inside of data access scenarios. Why do we use a Unit of Work? Because the objects that we retrieve from some persistent data store, we need to track any changes we've made to those objects so that when it comes time to save those changes, we know exactly what needs to be sent to the database or the Web Service or the file system, wherever we're retrieving this persistent data from. A Unit of Work can make data access more efficient. So imagine we need to go out to the database and we need to find some employee object and update it with some new information. At that point, we could tell a Unit of Work to commit all the work or save all the changes that we've made, and it can go out and update a record that represents the single employee. But imagine if we had to not only pull out the single employee, but also some of her colleagues, as well as a manager object associated with this employee, and make changes to 10 or 12 different objects. We could call Save individually on each of those objects, but then we'd have 10-12 trips to the database. Instead, we're going to make changes across all those objects throughout some business logic and then tell the Unit of Work, which has been tracking what changes have been made, we're going to tell that Unit of Work to commit all those changes. And now it can perform a single operation against the database and perhaps batch together some Insert, Update, and Delete statements to send it to the database all at once. So, a Unit of Work is partly about efficiency. A Unit of Work can also help manage concurrency problems. So when we tell a Unit of Work to commit, it can make sure that that employee record hasn't been modified since we last retrieved it from the database. If it has, it could throw an exception, we could go back to the user and we can say, sorry, someone else has updated this employee already. A Unit of Work can also manage transactions if you're working against a transactional store like a database. So when we tell the Unit of Work to commit these changes it can make sure that all the changes are put into an atomic operation by wrapping all of the updates it has to perform inside of a transaction. These are the qualities that we want exhibited from a component that is a Unit of Work. Intent When we talk about transactions with Unit of Work, we need to make the distinction between a physical transaction and a logical transaction. A physical transaction is one of those things that you actually perform against a durable store. In SQL Server you can say Begin transaction and perform some work, and then either commit the transaction or roll back that transaction so that all your work is atomic. It either all gets saved inside of a database or everything gets reverted back to its previous state. But the real goal or the real intent of the Unit of Work Design Pattern is to give us something that provides a logical transaction inside of our business logic, so that our business logic can say, here's some objects I want to change. I'm going to set their properties, perform some computations, modify their state, and I'm going to do that across a whole collection of objects or several different types of objects, and now my logical transaction is complete. I finished this portion of work. I have updated the insurance policy, I've changed the account invoice, we now want to save all those changes. That's a logical transaction. So in this diagram, you could imagine that we need to pull out a customer and that customer's orders from the database, and maybe every order has some line items associated with it in a collection. We're going to run these objects through a series of business components. One's going to apply some Pricing Discounts to Apply Total Price, then we'll compute the taxes for this order, then we need to update the customer balance. Perhaps we also need to adjust the inventory level for our warehouse, and this is all a logical transaction inside of the business that needs to commit and save all those changes when we're finished the goal of placing an order. And the beautiful abstraction here is that the business logic doesn't need to worry about what pieces of state have I actually changed inside the customer or what pieces of state have I actually changed inside of an order. It just makes all those changes and announces to the Unit of Work that everything is complete. It's up to the Unit of Work now to recognize what has changed and then save those changes into the database. And the Unit of Work will probably use a physical transaction, but from the business logic perspective we're not too worried about the implementation details, we just know that this commit is going to be atomic just in this little world where we were modifying customer and order and order line objects. UoW in ADO.NET Before we go any further, I want to introduce you or reintroduce you to a couple classes that implement this Unit of Work Pattern that have existed in the .NET framework since the very beginning. These classes are the DataTables and DataSets that make up the low-level ADO.NET API. with ADO.NET, I can construct a DataAdapter and give it some information that it needs to connect to a database and retrieve information from a table in that database. I can use that DataAdapter, then, to fill a DataTable. And once I have a DataTable, I can start making modifications to that table. For instance, I can add new rows into that table, and I can also modify existing data that already exists in that table that we've retrieved from the database. And all the time I'm making these modifications, inserting rows, deleting rows, modifying existing rows, the DataTable is tracking changes, it knows which rows have changed, which rows need to be inserted, which rows need to be deleted now when we come back and we tell the SQL DataAdapter to update this table. What Update will do is look at that list of changes and start formulating Insert, Update, and Delete commands to synchronize this in-memory DataTable with what's in the database. This line of code is essentially the commit for our Unit of Work. And all of this logic, we could have taken this DataTable and passed it through several different components. We could even serialize it and pass it out of process and that DataTable is going to keep track of all the changes that we've made through all these different unrelated business components until we reach that point where we call Update and it synchronizes changes. DataSets, DataTables, DataAdapters, all of these tools can do the job, but they don't give us a good object-oriented API to use in our business layer. The concept of working with rows and tables and sets, that's all very data-centric. These days there's a slew of technologies available that let us take a very object-oriented approach to accessing and modifying data. These are technologies like NHibernate, the ADO.NET Entity Framework, and LINQ to SQL. It turns out that all these technologies also implement this Unit of Work Design Pattern. ObjectContext Now that we've seen how DataSets work, I want to show you how the Unit of Work Design Pattern is implemented by the ADO.NET Entity Framework. To work with the Entity Framework, I first need to define a data model that describes to the Entity Framework how to map CLR types, like an Employee type and a TimeCard type, into specific tables that are in the database, and I can also map properties to individual columns that are in that database. Once you have this Entity DataModel defined, you can instantiate something known as the ObjectContext. So the ObjectContext is the gateway to the database. All we need to do is pass it a connectionString that defines what database to connect to and where to get the metadata. And at this point we can start using the Context to retrieve information from the database. For instance, I might go looking for the firstEmployee by telling the context that I want to query Employee information in the database, it'll know what table to go to for that. Then I'm going to order the Employees in a descending order by their HireDate and take the first one. So that should give me the first employee that was hired. And the Entity Framework knows how to formulate the proper query to send to SQL Server to retrieve that object. At that point, I could start making changes to this employee, so I could, for instance, update the HireDate by adding one day to it. And I could go to that same context that we've created and perhaps retrieve the lastEmployee. So the lastEmployee would be the person that was most recently hired. Instead of OrderByDescending, we'll just use OrderBy and we could change the lastEmployee's name. so at this point, we have instantiated an object context, we've used it to retrieve two different employee objects, we've modified properties on both those objects. At this point, we could say context.SaveChanges and this is the commit for the Unit of Work. You see, all along the context has been tracking changes on those employee objects. It knows what properties have changed on those objects and when we call SaveChanges, it's now up to the ObjectContext to issue Update statements to synchronize the data that we have in our in-memory objects with the data that's in the database. And it's not just these two employee objects, it could be an object that we brought back from this specific context. It will track changes on all those objects. When we call SaveChanges, it will synchronize the changes for all those objects. You should think of the ObjectContext as being a Unit of Work. IUnitOfWork Remember the goal for a Unit of Work is to allow different business objects to participate together inside of a logical business transaction, to be able to coordinate and perform work together, but without coordinating by coupling tightly to each other, but by relying on a component that implements this concept of a Unit of Work. And quite commonly, you don't want to use a component directly that performs this Unit of Work business, you want to program to an interface like an IUnitOfWork interface that describes everything the business component will need to participate together. In this IUnitOfWork interface, we have defined two different repositories the business components can get to, an Employees Repository and a TimeCards Repository. It's quite common to see Repository Design Pattern and Unit of Work Design Pattern in play together, and we've talked about the Repository Design Pattern in another one of the modules in this Patterns Library at Pluralsight On Demand. The other thing that we want to do with a Unit of Work is tell it when to commit. This is the point where whatever is behind this interface needs to track down everything that has changed and start issuing commands to the data store to synchronize changes. Now we can pass it around an object that implements IUnitOfWork into different business components and they can retrieve employee information, they can retrieve TimeCard information, they can add new TimeCards, they can add new Employees, they can delete objects, and when all of those business objects have finished their work, someone can call commit and say, we are now logically complete. And at that point, the objectContext, which is one way to implement this IUnitOfWork in a concrete manner, the ObjectContext can go out and save things into the database. Now that the IUnitOfWork interface has defined the abstraction that we need for Unit of Work, we can have some classes that implement that interface and when we instantiate one of those classes we can pass that single object into all the different business components that need to coordinate their activity together in a single logical business transaction. In this example, we're passing in an object that implements IUnitOfWork to the constructor of a controller in an ASP.NET MVC application. What the controller can then do, is work with the different repositories that are inside of that Unit of Work to retrieve information or add and delete information. And at some point, the Controller can decide that the Unit of Work is complete. Other business components might work with the same Unit of Work, but in this case it's the Controller that decides when everything is finished, it's calling commit. The typical scenario when you're using the Unit of Work Design Pattern is that you have some component, some piece that's orchestrating all the different business activities, and it's that orchestrator that knows when to call commit. This is a very simple example with an MVC controller. It happens to be the only one using this Unit of Work, but it knows when to call commit. It knows when all the work is finished, when we're trying to create a employee, we've done all the work of validating that employee, we've added it to the repository, and now we're going to tell the Unit of Work to go through and save all the changes that it's tracked. Implementing IUnitOfWork Implementing this IUnitOfWork interface with the Entity Framework is very straightforward. And I should also point out it's very straightforward with technologies like NHibernate, WCF Data Services, and LINQ to SQL. All of those technologies already have some component that implements the Unit of Work behavior for us. It does the change tracking, it does the atomic save operation. All we really need to do in a concrete implementation of IUnitOfWork is forward the property and method invocations to the right place on that component that already does the work for us. With the Entity Framework, as I pointed out before, this is the ObjectContext class. So inside of a concrete implementation of IUnitOfWork, we'll call it SqlUnitOfWork, we'll create a new ObjectContext, initialize it with the right connectionString, and now when someone needs a repository from here, we'll create a repository that essentially has a reference to that context, because it's going to need that ObjectContext, it's going to need that Unit of Work to create the repository. It's the context that's doing all the change tracking, so we always need to do creation off of that context. In this scenario, a repository is doing nothing more than ObjectContext.CreateObjectSet. That creates a queryable sequence of objects off of that ObjectContext. And when we retrieve a particular employee or account or invoice from that ObjectSet, it's going to be wrapped so that the Entity Framework can track changes on it. When we call commit on our IUnitOfWork interface, that's just going to go to the SaveChanges method on that ObjectContext. That's the point where it goes out and retrieves that list of everything that has changed and formulates the Insert, Update and Delete statements. In addition to a concrete implementation of IUnitOfWork that actually talks to the database using the Entity Framework, we might want to provide an alternate concrete implementation of IUnitOfWork that is just working with in-memory data. This is extremely useful in scenarios like unit testing, where you do not want the unit test to invoke behavior that actually goes out to the database, you just want it to work very quickly against in-memory data. That way you don't have to worry about getting the proper schemas and database setup and all that. So an in-memory Unit of Work could simply expose some in-memory collections and in-memory repositories and have a commit method that doesn't actually save anything, we don't really have data to persist, everything's in-memory, but we can keep track of whether or not committed was called or not. At this point, it becomes very easy to write tests where we instantiate in-memory Units of Work and we pass those Units of Work into MVC Controllers or business objects, and then we can write tests that run very fast and efficient and give us a quick feedback cycle. And it becomes very easy to test things such as when I tried to save an employee, did we commit the Unit of Work, and we can write an Assert on that. So in addition to testability, we've also shielded our business layer and our presentation layer from any implementation details of what's actually going on with the Entity Framework. Applicability and Consequences The Unit of Work Design Pattern is applicable to almost any data persistence scenario, and in fact, we've seen many persistence frameworks already provide a component or a class or an API that implements the Unit of Work behavior, we've seen the ObjectContext with the Entity Framework, we've seen TableAdapters, DataSets with ADO.NET and other frameworks like NHibernate. With NHibernate, you have the concept of a session, which implements the Unit of Work behavior. Now one caveat with the Unit of Work is that you have to be aware of lifetime issues. A Unit of Work is ideally only going to exist for the period of time needed to complete the business transaction. And that's because a Unit of Work is tracking changes on all the entities and objects that you're bringing to life. So it's keeping references to those objects, even after you invoke commit or SaveChanges. If you try to keep a Unit of Work around for too long, that means those objects are not going to be garbage collected and you can run into a number of different problems. So you almost never want a Singleton Unit of Work. Typically for web applications, we'll use a single Unit of Work per HTTP request or a single Unit of Work per service method. In desktop applications, you might use a single Unit of Work per form. Related Patterns There are two patterns related to the Unit of Work that you'll commonly run across in applications that are using the Unit of work Pattern. The first pattern is the Repository Pattern. We have a dedicated module in the Repository Pattern in this Pattern Library at Pluralsight On Demand. A repository tries to encapsulate data access and mapping details, so that the business layer just treats persistent data like it's in-memory. The second pattern is the Identity Map Pattern. Many Units of Work use the Identity Map Pattern internally. An Identity Map tries to enforce object identity just like primary key values enforce row identity in a database. So inside of a database schema, if I have an Employee table, I've probably assigned some primary key value like an ID, and it's impossible for me to insert two rows with the same ID value, the database won't allow that. Inside the same Unit of Work, it's quite common that a Unit of Work will know which property on an object represents its primary key value. We described that in metadata. And inside the same Unit of Work, we should never have two objects, both of the same type, that have the same primary key value. In other words here, we shouldn't have two employee objects that both have an ID of 1 inside the same Unit of Work. That creates a lot of conflict when it goes time to save changes because we don't know which employee object we should be using as the authoritative source for the information that we want to save in the database. So, when we retrieve a particular record from the database, and that's mapped into an object, the Unit of Work looks at the property on that object, the primary key value that's in one of the properties on that object, and it says let's check and see if we already have this object somewhere, and if so, we're going to use the existing object instead of creating a second object that has that same primary key value, thereby avoiding any sort of conflict when it comes time to save changes. Summary In this module we looked at the Unit of Work Design Pattern and we found a couple of advantages to using this design pattern in our applications. First of all, it allows our business logic and presentation logic to be free of data access code. Somewhere inside the implementation of a Unit of Work there's going to be logic that knows how to take information in our objects that the business logic works with, take that information and save it in a data store somewhere. The Unit of Work also frees up our business logic from keeping track of all the changes that it's making. All the business logic has to worry about is walking up to objects and calculating values and setting values. It doesn't need to keep track of exactly what objects it has changed or even what values have changed on the properties of those objects. And finally, the Unit of Work allows our business logic to work in logical transactions. So the business logic can start a unit of Work, retrieve some information, manipulate some objects, and then save all the changes when it's finished. Visitor Pattern Introduction Hi, this is John Sonmez from Pluralsight, and in this module we're going to be talking about the Visitor Design Pattern. The Visitor Design Pattern is one of my favorite design patterns. I think it's a very useful design pattern, and it is also one of the design patterns that isn't used as much as it should be. I find that a lot of people find the Visitor Pattern to be complex or it looks complex when you look at the UML diagrams, and so they tend to avoid it, but hopefully by the end of this module you'll have a good understanding of how to use the Visitor Pattern and how to apply it as we walk through some examples. First we're going to look at a real-world example of using the Visitor Pattern. Then we're going to go into the code and we're going to see how we can refactor some code to use the Visitor Pattern and to make it so that code reduces some of the duplication that you would have to have if you didn't have the Visitor Pattern. Then finally, we will look at the UML of the Visitor Pattern and we'll see that it's really not that complicated even though there are quite a few parts to it. Breaking it Down Let's start by breaking down the Visitor Pattern so we can have a better understanding of what it is. So here's the formal definition that you would find in the Gang of Four Design Patterns book. Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. So, again, not something that is very simple to digest, just reading that paragraph. So let's see if we can break this down and really understand what is being said here. First, we're saying to represent an operation to be performed, so we have some kind of operation, we're going to do that operation, and what are we going to do it on? On the elements of an object structure, so we're going to have some kind of object structure. Maybe we have a tree, maybe we have an array or collection, but we're going to have some structure of objects and we want to perform that operation on all of them. So Visitor is going to let us define a new operation without changing the classes of the elements. So the idea here is that we should be able to create a new, almost method, on each one of those classes that exist in that structure, but we can't change them. So this might seem impossible to do, but we'll see how to do this with the Visitor Pattern. And so if we wanted to summarize this, one way to say this would be that using the Visitor Pattern, we're basically going to give an object tree in our object structure some new functionality without changing any objects in that entire structure. Real Life Example So there's actually a pretty good real-life example of using the Visitor Pattern to solve a problem that you're probably already familiar with. So let's look at the problem first. Selling. In a traditional company where you have salespeople and you have some products that you want to sell, you typically have to have a single person who's the trainer, who's going to train the salespeople, and each salesperson has to be trained on a particular product. So if you have five products, you might train different salespeople on each of those products or you might cross-train them so they all get the training of each one of the those products, or however you do it you're going to have to train each salesperson specifically for the product that you want them to sell, and they have to go out and sell it. Now, this requires a lot of resources and a lot of time, and each salesperson has to be a specialist, they have to know how to sell a particular product or about a particular product. Now we can solve this problem, and it has been solved by using Visitor Selling or multi-level marketing. So think about the multi-level marketing situation. If you're familiar with multi-level marketing, it's basically this idea that instead of training all these salespeople in your organization, you're going to use the common customer as a salesperson, so someone that would possibly become a salesperson and would need all this training and all these products. All that they now have to do is just call up their friends and their family, invite them over to their house, and the salesperson shows up and sells them all. So this is a great example of the Visitor Pattern. If you think about what's happening here is instead of the earlier case where we saw each salesperson needed to know each type of product and had to become a specialist in that type of product, and if you added a new product you would have to add some more training to the salesperson. In this multi-level marketing technique, if you add a new product, you only have to have this one guy over here that understands all of the products. Or maybe you have different salespeople that are specialists in a particular product, but you can sell all these people, because instead of recruiting the sales force, you're just recruiting one person that's going to commit to getting their friends and family together at the same place to hear a sales pitch. So by using this pattern, you're saving a lot of effort because you can reach a lot more people and you don't have to constantly train an army of salespeople. Instead, you're just having a few master salesmen that can really sell a particular type of product, and you're using what you would have in your Salesforce as the person that gets all the other people together or gets your customers together. They don't actually know how to sell, they're delegating that responsibility, instead they're just knowing how to gather their friends and family. Net Worth Without Visitor So I've created this sample application here that we're going to use to demonstrate the Visitor Pattern. But first let's take a look at this problem that we're trying to solve. So the idea here is that we have some structures here. We've got a person and that person has some assets and some loans. They have real estate accounts, they have bank accounts, and they have some loans, and each one of those things has some particular attributes. The loan has the amount that's owed, the monthly payment, the bank account has an amount of monthly interest, and real estate has an estimated value and some monthly rent. Now given this set of objects, we might want to find out for a Person, what is their net worth? So, I've actually solved this using a non-Visitor approach. So if you look here, we're creating a new person, we're adding some bank accounts, some real estate, a loan, and we're going to calculate their net worth by looping through each bank account, adding that to the total. Then we're going to loop through the real estate, we're going to add the estimated value to the total, and then we're going to go through the loans and we're going to subtract whatever they owe from the total and that's going to be our net worth. So we'll write that out. So let's go ahead and run this, and you can see the amount that comes out is 42,000. So it's a pretty simple example, it's actually not that difficult of a program, but there are a few things to note here. One is that we're having to loop separately through bank accounts and real estate and loans, and these things have different attributes on them. For example, the bank account has an amount, the real estate has an estimated value, and our loan as an amount owed. So we can't really group this into any particular class that we could just iterate through, because they have different aspects that we might not have control over to change. The other thing to think about here is let's say we wanted to calculate something else in this structure. Let's say that we wanted to calculate what their monthly income or how much they owed every month was. So we'd have to loop through this and we'd have to do some calculations, and we'd have to write a lot more code here. Refactoring to Visitor Now let's go ahead and refactor this code to make it use the Visitor Pattern. The idea here is that we want to have a Visitor that can calculate the net worth. We don't want to have the logic for calculating net worth here where it is external to everything and we have to know about the specifics of every asset. And we don't want to put it in our classes, so we don't want to have to have the loan be able to calculate its net worth, and the bank account, and have to add them all up, because we don't want to add that logic. And the reason why is because if we started thinking about the monthly income, and we started thinking about all of this functionality that you could do with these assets, we don't want to have to add methods every time that we want to add some new operation that we can perform on these assets. So we're going to use the Visitor Pattern to implement the operation, to separate the operation from the structure so that when we want to implement new operations we don't have to modify any of the code in this structure. So in order to do this, the first thing that we're going to do is we're going to create a Visitor interface. So I'll create a new interface, I'll call it IVisitor, and on this interface we're going to create a method for each type. So for a loan, for a bank account, for real estate, we're going to be handling them differently because they have different properties and we need to be able to handle them specifically. So we're going to create some methods on here. We'll create a method called Visit and the first one will take realEstate and the next Visit will take a BankAccount, and the third one would take a Loan. Now for each new asset, if we created some new asset types, we'd have to create a new method here, but we won't have to change the asset type itself. Now we'll go ahead and create an interface for each one of our assets to implement so that we can use the Visitor with it, so that it'll accept a visitor. So we'll go ahead and create an interface here and we'll call this IAsset because these are all assets. And each asset should be able to be visited, so we're going to create a method on here called Accept and Accept is going to take an IVisitor and we'll implement this to be able to accept a Visitor. So the idea here is that each one of these assets is going to be able to accept a visitor and then the visitor is going to be able to operate on that asset, and it'll make more sense as we start implementing this. So first we have our person, and we can change this. We don't want to have RealEstate, BankAccounts, and Loans, we don't want to have all these lists, we want them all to be Assets. So first let's go ahead and make all of these things Assets. So, we'll implement IAsset here for our loan, and you can see we have to implement this member of Accept. And the way that we implement Accept is we're just going to call on whatever Visitor gets passed in visit, and we're going to pass ourself. Then the Visitor will take this object or this asset and then it will do whatever it's going to do on that object. We'll do the same thing here with BankAccount. We'll make this an IAsset and we'll implement this exactly the same way. We're just going to call Visitor.Visit, pass in (this), so it'll operate specifically on that type, and we'll do the same thing for RealEstate, and we'll pass in (this). So now what we should be able to do here is change our Person. Instead of having all of these lists, let's just have one list, let's just have a list of IAsset, we'll call this Assets, and we'll just create a new blank list here. Now we're going to go ahead and make our Person implement IAsset as well so that it can be visited. And for this method, what we actually want to do is we want to make sure that each one of the person's assets gets visited, so we'll go ahead and loop through each asset and for each asset we're going to call Accept on the visitor. So this is just going to chain this down to make sure that each asset gets visited by this Visitor. Now we don't actually have a Visitor at this point, but we have the structure so that we can create a Visitor, and any Visitor that we create is going to work on all these assets. So let's go ahead and create our NetWorthVisitor. So I'll create a new class here called NetWorthVisitor and it's going to implement IVisitor, and you can see here that it needs to implement these three methods so it can deal with each one of these asset types. What we want to do is be able to calculate the net worth, so we're going to add everything up. So we're going to store the total here. We'll just make this a property. And for RealEstate, when we visit RealEstate, the way that we can add the total is we'll just do += and we'll do realEstate.EstimatedValue. When we visit a bankAccount, we'll do Total += bankAccount.Amount, and when we visit a loan we'll do -= loan.Owed. So now our visitor should work on all of these asset types, and it should work on Person as well, because this Accept method will make sure that the Visitor visits each asset that that person owns. So let's modify our main program and see how this will work. So instead of bankAccounts here, we're just going to change this so we're just going to be using Assets, and let's make sure that the Assets here is capital. So we'll change all of these to Assets, so we're adding them all to our collection. We no longer need to do any of this. Instead what we're going to do is we're going to create our Visitor. So we'll make a netWorthVisitor and we'll create a new NetWorthVisitor, and all we're going to have to do here is we're going to do person.Accept, and we're going to pass in the netWorthVisitor and that's going to cause the netWorthVisitor to visit each Asset in that person and add them all up together. Then we can just take our netWorthVisitor and spit out the total. So let's go ahead and run this and see what we get here, and let's fix this name real quick since we had to change this to a capital A. So now if we run this, you can see we still get 42,000, but the difference here is that we haven't added any new logic to Person or Loan class, we've just added this Accept method, but there's no real logic in it. Instead what we've done is we've created this Visitor that encapsulates all the logic of calculating the net worth, and we've taken it out of here so that we have this ability now to add any kind of new operation to this whole set of Assets without having to modify each Asset individually. Monthly Income Visitor We haven't yet demonstrated the true power of the Visitor Pattern because we only have one visitor, we have this netWorthVisitor. But let's go ahead and create a new Visitor and we'll see how easily we can implement this Visitor without having to change anything as far as the bank account, real estate, loan or person is concerned. We're going to just create the Visitor and we're going to automatically add this capability instead of having to add new methods to these classes. So I'm going to create a new Visitor and we're going to call this Visitor a monthly income visitor. We'll just call him an IncomeVisitor. And the idea of this Visitor is that he's going to calculate what the monthly income of a person is or what their debt is, how much will they have to pay per month. So we'll need a variable to hold that. So we'll make this be a double and this will just be the Amount. Now we need to implement this IVisitor interface, so we'll implement all the members here. So for realEstate, how do we calculate what the monthly amount that they owe is or that they make? We'll simply take whatever the amount is currently and we'll add to it, realEstate.MonthlyRent, so that one's pretty simple. For bankAccount, we're going to take the amount and we're going to add the bankAccount amount times the bankAccount MonthlyInterest rate. For the loan, we're going to take the amount and we're going to - the loan.MonthlyPayment, whatever the minimum monthly payment is. So you can see here also that we have different logic in each one of these cases, but we haven't had to add any logic to our classes, and that's really the nice thing about the Visitor Pattern is we're not bloating our classes. Every time we want to do a new operation, we're not having to create new methods in each one of these classes. So let's go ahead and see how easily we can use this now. So we'll go ahead and create an IncomeVisitor, and for our IncomeVisitor all we have to do is call person.Accept and now we're going to accept an IncomeVisitor, and now we can write out what the income is. So let's go ahead and run this. Now you can see that the net worth is 42,000 and the income is $510.00. So you can quickly see how by using the Visitor Pattern in this case that we could easily add new operations without having to modify any of this code once we've set up the skeleton framework here for the Visitor Pattern. There is a little bit of work that we have to set up here, if you look at we created this IAsset that has this Accept, but once we've done that, as long as all of our Assets implement this IAsset and they have Accept on them, we can then use the Visitor Pattern on the root object or any of the objects in here, and it's going to work. Formal Definition The UML diagram for the Visitor Pattern has quite a few parts to it. Let's go ahead and examine each one of these parts so we can understand how we've implemented the Visitor Pattern and what the general makeup of this pattern is in code. So starting over here on the left you can see that we first start off with an Object Structure. And in our demonstration this was our Person class. Now the Object Structure uses an Element or it has Elements. In our example, we had Assets as our Elements. In fact, our Object Structure was an Element as well, just so that it could be visited, and Element has Concrete Elements. And each one of those Elements needs to define an Accept method or some method to Accept the Visitor that ends up passing a reference to itself to the Visitor so that the Visitor can operate on it. If we look over to the right, you can see we have our Visitor. This was our Visitor interface and then we can have multiple Concrete Visitors, and each one of those Concrete Visitors is going to implement that Visitor interface and it's going to have a Visit method for each of the Concrete Elements that it can operate on. This is also known as double dispatch, because we're first accepting a Visitor and then we're calling a method on that Visitor and it's going to operate on the Element that we pass in. In that case, it'll be the This Reference. So the key thing to note here is that each Visitor is going to have a method for each of the Concrete Elements that needs to visit, and each Visitor is going to represent an operation that's going to be able to be performed on those Elements. This kind of flips the normal way of doing things sideways where typically you're going to have methods defined in the Base Element and then for each new method or new operation, each Concrete Element would implement that method. In this case, the Visitor is going to be the one that is going to provide the implementation so you don't have to modify that side of the tree, nothing in Element or Concrete Element ever gets modified, and you can keep adding functionality without having to change that. Summary So the Visitor Pattern is a very useful pattern that you can use in circumstances where you want to make sure that you don't have to modify a structure, but you want to be able to add operations that work on all the elements of some structure. In this module, we looked at what the Visitor Pattern is, we broke down that definition to make it a little bit more simple. Then we took a look at a real-life example of sales and we saw how multi-level marketing is somewhat like the Visitor Pattern because we rely on the customer to accept the salesperson, and then the salesperson is able to sell to that customer, instead of having a whole army of salespeople. Then we took a look at a code example where we wanted to calculate the net worth, and then we wanted to calculate the monthly income or expenses of a person. And so we were able to use the Visitor Pattern to add that functionality to that person in that tree of Assets that belong to that person without having to modify any of the assets or modify that person, once we had implemented the Visitor Pattern. Then finally we took a look at the formal definition of the Visitor Pattern. And the Visitor Pattern can be very useful whenever you're in the situation where you have some code that has a lot of different operations in it that aren't necessarily related to those classes, but since you need to operate on all of the classes in that set, you have put that logic in there. And so by using the Visitor Pattern you can take that logic out and move it to Visitor classes that perform that operation and allow your actual classes or your actual structure to be a lot simpler. Rules Pattern Introduction Hi there. My name is Steve Smith, and in this Pluralsight course we're going to examine a Design Pattern that isn't in the usual books, but which I have found to be particularly useful in a number of real-world scenarios. It involves identifying areas of frequent change in your application, typical with a lot of complexity, and replacing that complexity with a collection of objects that represent business rules. I call this the Rules Pattern. If you have any questions or feedback about this course, you'll find me online at or on Twitter as @ardalis. There are some related courses on Pluralsight that you may find helpful in learning more about this pattern. In particular, there are two solid principles that heavily motivate the Rules Pattern. I'll be discussing them briefly here, but for more information on all of these principles, be sure to watch my SOLID Principles of Object Oriented Design course here on Pluralsight. Motivating Example Let's begin, as we do with most design patterns, by describing the problem the pattern is designed to address with a motivating example. In the case of the Rules Pattern, the typical problem we're trying to address is growing complexity in a particular area of our application. We have a class or method with very complex business logic and we believe based on past history or information we have about the future that additional changes to this area of the code base are likely. Some examples of these kinds of business logic include customer discount calculations, achievement systems for badges or points, and ratings for credit or insurance agencies, just to name a few. Demo: Customer Discounts Now to make this motivating example a little more clear, let's take a look at an actual example that demonstrates the behavior the Rules Pattern is designed to address. In this case, we're going to examine some code that determines which customer discount applies. Imagine for a moment that you are the sole developer for a small retail business. Over time, the business has come up with a discount structure for its different customers. First-Time Buyers receive a 15% discount, Veterans get a 10% discount, Loyal Customers begin receiving a 10% discount once they've been a customer for a year, 12% after 5 years, and 20% after 10 years, Seniors age 65 and older get 5% off. Customers should always receive the best discount that applies to them. So, for example, a First-Time Buyer who is also a Veteran should receive 15%, while Senior Veterans should receive 10%, etc. Now, marketing has just come up with a new promotion and you need to add a couple more cases to the discount determination. The company is going to start offering special discounts on customers' birthdays. Most customers will get 10% off on their birthday, Loyal Customers will get an extra 10% off on their birthday. Let's look at how this code is structured today without the use of the Rules Pattern, and what it would take to add this new functionality to it. As it stands now, we have a simple class called DiscountCalculator. DiscountCalculator, as the name implies, is responsible for calculating the discount that a customer is eligible for. The way it does this is a customer is passed into the CalculateDiscountPercentage method and that method begins with the assumption that the discount will be 0. It then goes through a series of if checks to apply each of the rules, which are noted by comments within the code. Here you can see the discount for Seniors is applied based on when their date of birth is relative to the current time. We can also see the DateOfFirstPurchase, which is used for checking whether or not the customer has made a purchase. If they have, then they may be eligible for a loyalty discount based on how many years ago that first purchase was. If they haven't, then this gives them an opportunity to get their First-Time purchase discount of 15%. If they are a Veteran, then they are eligible for that 10% rule. In each case, since the discount that we are going to apply should always be the best one to the customer's benefit, we're using the Math.Max function so that we always compare the discount of the current rule with the best discount the customer has gotten thus far in this method. Once we're done, we simply return the discount. Now the customer needs to also receive a special discount of 10% on their birthday, as well as an additional 10% if they happen to be a Loyal Customer. So, we can do this in a couple of different ways. First, we can go in and say here, if the customer's date of birth is today, give them a discount of 10%. So, we'll just copy what we have here, do some nice copy/paste programming. Now we actually only want to check the month and day and not the year, so now we know that that's their birthday, and we'll just make a note. Now in this case we probably want to do a Max as well, just to be consistent. And then we also need this same check now to be in here, so if they have a value and if it's been a year, so for in this block we should add 10%. Alright, so there we go. We can build that and it seems to work. Now we have some unit tests, we'll run those later. At this point, the other thing I wanted to point out though is some CodeMetrics. If we go ahead and refresh these we can see that our cyclomatic complexity now for this particular method is an 11, which isn't horrible, but it's starting to get up there. And you can see our maintainability index is now under 50, so we're down to 49 for this one method, and it's only 20 lines of code, which again, is not horrible, but anytime your number of lines of code exceeds what you can see on one screen, it's starting to indicate that you might have a little bit more complexity than you want to in that particular method. Of course, you can always use this trick to fix that, but I don't necessarily recommend that, that only gets you so far. What's the Problem? So, what's the problem with the kind of code we just saw? First, it has growing complexity. One measure of complexity we can use is cyclomatic complexity, which measures the number of possible paths through a block of conditional code. With the changes we just made, the cyclomatic complexity of the method increased from 7 to 11. So is there a magic number which we should keep our cyclomatic complexity under? Not necessarily, however, one paper suggests that 10 is a good starting point. To quote, the precise number to use as a limit, however, remains somewhat controversial. The original limit of 10, as proposed by McCabe, has significant supporting evidence, but limits as high as 15 have been used successfully as well. Limits over 10 should be reserved for projects that have several operational advantages over typical projects, for example, experienced staff, formal design, a modern programming language, structured programming, code walkthroughs, and a comprehensive test plan. In other words, an organization can choose a complexity limit greater than 10, but only if it is sure it knows what it is doing and is willing to devote the additional testing effort required by more complex modules. You can learn more about cyclomatic complexity at the link shown here. The other problem that should be obvious is duplicate code. It's not uncommon when we have methods like this that we start to get some kind of a rule that affects multiple different branches within our conditional logic, as we did in this case. In that point, oftentimes we will have copy and pasted code that has to go inside of different branches of the if or switch logic tree. This quickly begins to degrade the quality of our software. Intent The intent of the Rules Pattern is to separate the logic and execution of individual rules from the logic that processes these rules. The goal is to allow new rules to be added without the need for changes to the rest of the system. This goal aligns closely with the Open/Closed Principle, which is the letter O in the SOLID Principles acronym. The Open/Closed Principle states that software entities, classes, methods, function, etc. should be open to extension, but closed to modification. What that means is we should be able to change the behavior of the system without having to change the code itself. With the Discount Selection example we just saw, we were only able to extend the behavior of the code by directly modifying its structure. Clearly it does not currently follow the Open/Closed Principle. And since we're talking about SOLID Principles, let's also talk about the S, which is the Single Responsibility Principle, which states that a class or a method should only have one reason to change. The reason why we want to separate out individual rules from the rules processing logic, is that these are separate concerns. If we change how we process rules in general, that should go in a rules processing class or method. However, if we change the individual behavior of a particular rule, either how it chooses to select something or the action that it takes once it is selected, these should go inside of the Rule class. So by separating out individual rules into their own classes and having a rules engine responsible for processing those rules, we're applying the Single Responsibility Principle to our system. Applicability Now let's talk about when the Rules Pattern should be applied. You should consider using the Rules Pattern when you have a system that is suffering from conditional complexity and additional changes of the same nature are anticipated. If you have a system that has comingled the concerns of choosing which actions are applicable, and the execution of these actions, the Rules Engine can also make sense in that scenario. Finally, if you have a system that needs to support user created logic for determining when and how to apply actions, the Rules Engine Pattern can also be helpful in that scenario. Structure In terms of the structure of the Rules Pattern, it can vary quite a bit. Typically there is some kind of an Evaluator class, which references a collection of Rule implementations. In the simplest case, every Rule is executed and the Evaluator examines the results and chooses what to return or what action to take as a result. For instance, in our discount example, the Evaluator would hold the logic that determined that the highest discount should be the one returned. Note that this pattern shown here is very similar to the Command Pattern. In fact, the Rules Pattern is in some ways a special case of the Command Pattern. Demo: Using Rules Now let's look at how we can implement a simple Rules System with the Customer Discount Selection Code that we just saw. First, let's take a look at the Birthday code we had added, and let's go ahead and remove that code. Now what we're going to do instead is we're going to incrementally apply this Rules Pattern to our DiscountCalculator through a series of refactorings. So the first thing that we're going to need is a collection of rules, and for that we'll also need a definition of a rule, so let's create an interface and we'll give it a simple method, CalculateCustomerDiscount for a given customer. Now here we need a collection of these rules. For now we'll just populate these rules inside of our constructor. Here we're going to add a new BirthdayDiscountRule, which we'll have to create at this point. Here we're going to say that the customer's discount is going to be 10% if it's their birthday. We'll start out with the default case, though, of returning 0. In this case, we'll just return the 10. Now this gets us the first part of what we're trying to do. We will get to the part where we add it to a loyal customer in just a moment. Now we just need to run this rule. So in our CalculatedDiscountPercentage, we'll start out by setting the discount to be whatever we calculate from our list of rules. So this should work and, in fact, we can write a test to verify that it does. So since we haven't looked at any of our tests yet, let's go ahead and do that. Jump down here and see, we're going to create our calculator here and our Setup method. And we currently have tests to say that we should get 15% for a new customer, 10% for a Veteran, 5% for Senior. We can run these. We need to fix this real quick. Now we can run our tests, and we see they're green. So now let's write a test for someone's birthday. They should get 10% for birthday, and so to set DateOfBirth = DateTime.Today, and we expect that to be a 10% discount. And, of course, it thinks this is their first purchase so we need to add that as well. So they bought their first purchase yesterday, even though they were born today. And now we see it's working, but do you notice there's actually a bug that we've just uncovered, which is that our test for Seniors also has their birthday as being Today, albeit 65 years ago, but it's still returning the correct amount for a Senior, which is 5% instead of what they should get, which is 10 on their birthday. And the reason for that is that we didn't do this Math.Max rule right here. So this is an example where we've basically discovered a bug in our system where we were doing something differently in one part of our code everywhere else, but here we were doing it without that because we went in and added this above that point. If we'd gone and put this rule set after that, and went and ran our tests again, we'd see that the Senior test should fail and, in fact, it does. Let's fix this bug that we've found by creating a rule for seniors. So back in DiscountCalculator, instead of using this section here, we're going to go ahead and create a new rule, SeniorRule, and we'll take that logic right out of our code, and stick it in here, and all we have to do is Return, otherwise, return 0. Now having done that, since we already have our Rule calculation here, we should now be able to run our tests and they should work. So it's running correctly now, we need to change our tests though, so we'll say that their DateOfBirth is DateTime.Today.AddYears. We'll add a day as well, we'll say their birthday was 5 days ago, and we'll run that test one more time. Then the last thing we need to do is add that rule to our rule set and then we should be able to rerun our tests and they should work. They do. Now we've also got a test here for Veterans, we've got code for that down here at the bottom. This is a simple rule we can extract out, so we'll just cut it, write another implementation, remember to add the rule, and our test should still pass. Now we just want to add rules for loyal customers. In this case, we can just do the check for the birthday within that rule or we could create a separate rule for Loyal Customers on their birthday. Depending on how many of these different variations of rules you're going to have, you could create a different rule for each one of these cases, so you could have a 1 year rule, a 5 year rule, and a 10 year rule. You could create a more abstract rule that simply takes in as parameters the number of years and what discount they get. We'll show an example of that, because that, I think, is a good combination of limiting duplication and limiting complexity. So let's, once again, create a new implementation. And in this case we're going to have the years and the discount. To calculate CustomerDiscount, we're just going to add the _yearsAsCustomer integer to the period of time When the customer first became a customer, and we'll see if that exceeds the current date, and if it does then they are not eligible for the discount, otherwise, they are. This is one of those areas where you might have an off by one error. If this is their anniversary date, we want to also give them the discount, so we'll check that, and we would make sure we'd have a test for that case, and then we would just return the discount here. And then at this point we could also run the check for their birthday. I think that'll be the simplest place to do it. One option here would be to apply the BirthdayRule within the LoyalCustomerRule and see if we get back a result. I think we could try that here. And so there's our additive CustomerDiscount from the birthday. Now we've deferred some of the logic of the LoyalCustomerRule to its creation. As you'll recall, we had three different cases based on how many years as a customer they had been. So let's add those now when we create those rules. We're going to add a LoyalCustomerRule, years as a customer 1, discount 10, and 5 and 12, and 10 and 20. And with that, we should now be able to get rid of all of this and, in fact, we can flip this now and we're left with just that. We can run our tests one more time, we don't actually have any tests for Loyal Customers, however, so we should add one of those. We'll take our Senior test and modify it, Return12PctFor5YearLoyalCustomer. (Typing) And we see our tests are failing, so let's go back and change how we're doing this Loyalty Customer. Now we could write actual tests for this class instead of running our tests through our original method, which would actually be a better idea as that would have caught this issue that I've got right now, which is simply that we've got a problem with this. If that number of years is greater than today, that means it hasn't passed, it really needs to be less than. Once again, tests to the rescue. Now they all pass. Let's verify now the birthday piece of it. It's additive 10%, so 5YearLoyalCustomerOnBirthday. They were, in fact, born that day. And change this to 0.22, there we go. Now we have just one more test, one more rule, and that is, if they don't have, if they're a First-Time customer then they should get 15%. This one's an easy one. Return 0, if(customer.DateOfFirstPurchase.HasValue), flip that, return 15. So that's our exact same if check that we have here, so we should be able to delete this now, rerun our application, rerun our tests, and now we've screwed it up because we didn't actually add it. And there we go. So remember as you create these new rules they're not actually going to run unless you add them to your rules collection, but now you can see that our DiscountCalculator code has gotten much simpler. In fact, if we go back in and run our Code Metrics, you can see that our cyclomatic complexity is now just a 2, and none of our rules have any significant cyclomatic complexity. Our LoyalCustomerRule has a 4, so we've done a good job, I think, of limiting our complexity here. We have a small collection of rules and we know that if we need to add a new rule tomorrow when the business user comes and says, oh wait, I have another discount rule in mind, we can do that by just adding another instance of IDiscountRule and, of course, remembering to add it to our collection. Alternate Structure We've just seen a very simple Rules implementation that only has essentially an Execute method. In more advanced implementations, you may have rules that should only be executed if they apply, and they might have some selection logic, for instance, an IsMatch type of method. The Evaluator, in this case, would determine which rules match and then it would only execute the matching rules or in some cases only the first matched rule. If the system needs to create such rules dynamically, you can use Lambda expressions for the matching logic, perhaps passed in via the Rules constructor. Considerations When using Rules to replace complex conditional logic, there are a number of considerations to keep in mind. It's simplest if you keep your rules Read Only, so they do not have any side effects. However, if you create rules that change the system your rules are evaluating, you may need to consider dependencies between your rules. For instance, if one rule says, if the customer has been with us over a year, set the Customer.IsLoyalCustomer property to true and another rule depends on the setting of isLoyalCustomer, now you've created a dependency and you'll need to ensure that the latter rule always runs after the former rule. sometimes you can address this in simple cases by always running your rules in an explicit order or by assigning a priority to the order in which they're executed. It may also be that certain rules trump all others if they match, in which case you may want to have a way to issue a Halt command to your Rule processor. Finally, you may find that your rules change frequently enough that you want to allow end users to edit them, in which case you need to consider how you will persist the rules and how you'll create a user interface to allow them to be edited. Business Rules Engines Now related to the Rules Pattern is the concept of a Business Rules Engine. These are software systems that are designed to embody business rules. These can range from simple pieces of small applications to huge Enterprise-spanning beasts. Typically these systems have a graphical user interface that allows end users to create rules which are then saved in a database or perhaps on a filesystem. Now there are many commercial and open source options in this space. Assuming you're a .NET developer, you can use the Rules Engine that ships with Windows Workflow as part of the .NET framework. It can be separated from Windows Workflow so you can use it with just the Rules system in your application. In this module we've see how you can create your own simple Rules Engine, however, if you find that you're adding more and more complexity to your handmade system, you should consider replacing it with a more full-featured and robust Rules Engine. Practice: Greed Kata If you'd like to practice applying the Rules Pattern to code, you can go through the CustomerDiscount code that I included in the exercise files for this module or you can go through the Greed Game Kata, which is also included in the Before folder with the exercise files. If you don't have access to those files, you can also find it online at the URL shown here. The Greed Game is a simple dice game where with each throw of the dice you can pull out certain sets or combinations and apply a score to them. Here's an example of what the rules look like. As you can see, the requirements show that a single one might be worth 100 points, a single five 50 points, three ones are worth 1000 points, and three of each of the other types of dice are worth 200, 300, etc. points. Now as you go through the exercise of creating a scoring method for the Greed Game, consider refactoring to use the Rules Pattern once you encounter some conditional complexity. Once you're done, you can then compare your solutions with others online. A simple search will reveal a number of other people's attempts at this particular kata. And then repeat the exercise until you're comfortable applying the Rules Pattern. Demo: Greed Overview So before we wrap up this module, I want to show you some examples of the Greed Kata and what that might look like if you go ahead and perform it. And I also wanted to point out a problem with our DiscountCalculator code, and what you could do to fix that. Now before I show you, if any of you have figured out what the issue is, think about it right now. There's a problem where some of the time these tests are going to fail. Alright so, I'm going to tell you now. What happens to a lot of these different tests when it's the first of the year and we have not specified a particular date of birth for someone? For example, this 10% Veteran, he's going to have no date of birth on here, which means his birthday is automatically the first of the year. That's true for any of these ones where we didn't set a date of birth. Now what that's going to mean is that they're going to implement the wrong rule when they come into the DiscountCalculator. They're going to run through the, where is it, the new BirthdayDiscountRule, and trigger this rule in addition to or instead of whatever rule they previously had. In the case of the veteran, it may not be too big of an issue because their rule just happens to be 10% as well, which is actually even worse because that means it'll be all the more difficult to detect. Now there's a couple ways we could fix this. One of them is to pass in the current date everywhere instead of using DateTime.Now. This is bad, this is a dependency. You can eliminate this through the use of the Strategy Pattern, which is another design pattern you can look up in here, or we could do the same thing that we did with our customer first purchase and we can simply say that if we don't know the date of birth let's go ahead and make it a nullable DateTime and then in cases where we don't set it, it'll default to null and then it won't match the first of the year on those cases where it's not set. Alright, so I'll leave that fix as an exercise for you. Let's look at an implementation of Greed real quick. Here's one I did that does not use Rules and it has a simple Score method that takes in the roles of the dice and it goes through and it counts the dice with the values. This isn't necessarily a best practice way of doing this, this is just one example of one I did once, counts how many of them that there are, and then gets the score here based on the SingleDieScore, and then finally returns it. So let's look at each of these. There's a Rule, as you recall, that all the 1's are worth 100, all the 5's are worth 50, so when we try and get SingleDieScore that's what that does, and likewise, if there's a set, if the set of size 3, then it's going to be worth 100 times, so this GetSetScore says it's going to be worth 100 times the number on the die, except for in the case of 1 and then it's worth 1000, so there's a special case for 1. And this is the whole bit of code, right, so about 50 lines of code you can do everything in the basic version of that Kata, and this is driven by these tests here, so I have tests that verify that 1 is worth 100, two 1's are worth 200, three 1's are worth 1000, etc. And you can run these tests and see they all work. Now more importantly is if we look back at the game, as we go to add additional Rules and things to this it can get more and more complicated, we're going to have to touch this code. Let's look at what a Rules-based version of this would look like. And so here I have this notion of a RuleSet and I populate it with the rules that I'm using. Now I had some tests that worked one way when I wasn't using the extra Rules and another way when I was using the extra Rules, so I added a flag in here to say whether or not I was using all the Rules, but if you simply are using all the rules, you would just get rid of that flag and just add all the stuff like this. Now I made some of the Rules a little bit abstract, so I have this singleDieRule that I can use for multiple different Rules, right. So I have a Rule that says 1's are worth 100, and 5's are worth 50, and then I have a TripleDieRule that says 1's are worth 1000, and down here's the rest of them, i, which is 2, is worth 200, 3 is worth 300, etc. In the advanced Rules you also get four of a kind, five of a kind, six of a kind, and that's what these are doing. You can also have a notion of a straight or three pairs. So this is just the constructor, and it just sets up all the Rules. And then my Score method is a little bit more complicated because it has to actually run through all the Rules and figure out which one is the best one to use that'll yield the best score. And so there's a little bit of logic here to go through and determine which one is the best rule, which it only does if the score is better than it previously was, and then ultimately it will return the score. Now if we look at any given Rule, those are all defined here. I created an IRule interface that just has an Eval method. I created a RuleSet, which has information in here for determining which one is the best result. Here's the OneScoreRule, the FivesScoreRule, these were both used in the course of setting this up, I created these initially and then eventually I abstracted them out into the SingleDieRule. So you can see that these two really just pass through into the SingleDieRule at this point, and they could probably be removed, but that's sort of how the code evolved. For each rule I just need to know for Eval that it's going to return a ScoreResult and a ScoreResult needs to know which dice were used because those dice got picked up, they're no longer available for other rules to be applied to. They need to know the score that was the result of those dice, and then they are going to set which Rule was used so that we know which Rule was the best Rule when we run the RuleSet. So I'll let you play with that code. It's in the After folder. And I encourage you to go ahead, run through the Kata yourself and see how you do. There's also full tests for the Rule-based version as well, so these are all the tests now. Summary In this module, we've learned about the Rules Design Pattern. You should consider using the Rules Pattern when you have a growing amount of conditional complexity in your application. As you apply this pattern, you want to separate the logic of each individual rule and its effects into its own class. This follows the Single Responsibility Principle. Next, you want to separate the selection and processing of Rules into a separate Evaluator class. This will help you follow the Open/Closed Principle as you'll be able to add additional Rules without changing the logic of the Evaluator class or any of the existing Rules in the application. Finally, you should consider using a Business Rules Engine if your application's requirements warrant it. To learn more about the solid principles, see the URL shown here, and to learn more about Rules Engines in general, I recommend the following articles. There's a good article on what's called Soft Coding versus Hard Coding on the dailywtf site. There's a good article on guidelines for whether or not you should use a Rules Engine. In this case, it's pretty much talking about a commercial Rules Engine. You can see a number of different simple .NET Rules Engines listed in the StackOverflow discussion shown here. You can learn more about Business Rules Engines, in general, from Wikipedia, and you'll also find a good introduction to the Windows Workflow Foundation Rules Engine here. Thanks, this has been the Rules Design Pattern. I hope it's been helpful for you. My name is Steve Smith. You'll find me online at or on Twitter as @ardalis, and I hope to see you again real soon. Specification Pattern Introduction Hi and welcome. This is Steve Smith. In this module we're going to examine the specification design pattern, which can be used to help reduce complexity in your business entities and data access logic, among other things. The pattern involves encapsulating rules for matching certain objects within their own named classes, and this can be especially helpful if you find that your UI code is cluttered with a lot of filtering logic that doesn't belong in that layer. Let's get started. We're going to cover the origin of the specification pattern first, and then we'll see some examples of real world scenarios in which it can be applied to improve application design. We'll look at the intent of the pattern and multiple ways in which it can be implemented, as well as some of the benefits that it provides. Then we'll look at a few common uses, as well as how the specification pattern works with another pattern, the repository. And finally, we'll take a look at some specific data access implementations using Entity Framework. The specification pattern was first published by Martin Fowler and Eric Evans as a whitepaper on Martin's website in 2002. You can find it there today. Eric incorporated the pattern into his approach to building software, described in his 2003 book, Domain-Drive Design. If you'd like to learn more about domain-driven design, or DDD, I recommend watching the DDD Fundamentals course here on Pluralsight, authored by Julie Lerman and me. Intent The pattern is named specification because it specifies in an object the work to be done by an operation. This is an example of a design approach to object-oriented programming that uses objects to represent things that aren't typically representative of objects within the problem domain. Another benefit of applying this pattern is that the specification of the work can be separated from performing the work itself. This helps us follow the general software principle of separation of concerns. There are several candidate problems that the specification pattern can be applied toward. Probably the most common use of the specification pattern is to represent queries. It's not uncommon for business applications to make the same kinds of queries, but to duplicate the criteria in many different locations, or perhaps the queries are centralized, but they're implemented as separate methods on an ever-growing object such as a repository. Queries aren't always just about data access though, they can also be used to represent criteria for objects, selecting which objects are fit for a particular application use. Rules engines may use specifications to define which rules should be applied, for instance. In many of these scenarios, the use of the pattern is invisible to the user, it's just an internal application concern. Sometimes though, saving search criteria is a feature the user actually interacts with. For instance, a smart play list in a music application can respond to changes in the library that meet its criteria. Most of us have interacted with these kinds of user-oriented specifications in applications we've used. Another scenario in which specifications may be used is in the definition of requirements. For instance, identifying a shipping container that has the appropriate capabilities, such as refrigeration, and available space, and which is going in the right direction, could all be derived from a specification for a shipment that requires refrigeration, and is trying to get to Chicago. These kinds of criteria can be used to create the appropriate object to meet a particular set of requirements. Implementation The typical minimal implementation of a specification is simply a class that has a method called IsSatisfiedBy. This method accepts some kind of object. If that object meets the criteria defined within the specification, the method will return true, otherwise it returns false. This specification can easily be applied to a collection of objects acting as a filter. Specification should be implemented as value objects, meaning that they have no identity. One instance of a particular specification is equitable to another, provided that they both have the same criteria. This means that they can be created and destroyed as needed, without the need for persistence. The exception to this is the use of a smart list or a specification that needs to be persisted for later use by a user, and these can be persisted as a value object associated with an entity. Value objects and entities are both discussed further in the Domain-Driven Design Fundamentals course. You should try to avoid cluttering your entities with complex Boolean logic and rules. While it is better to have these rules in the entity than duplicated in UI-level code, having them there can also bloat the entity and its responsibilities, especially if the rules are particularly complex or there are many such methods or properties. In this example, a song entity has a rule for determining whether or not it should be included when the player creates a smart list. In this case it probably shouldn't be the song's responsibility to know about how the smart playlist chooses songs to include. At the same time, the smart playlist may already have enough other responsibilities that this could be separate from it as well, and can perhaps be placed into an object whose sole responsibility is ensuring this query is performed correctly. Predicates You can model simple Boolean rules as predicates. Predicates are rules that evaluate to a Boolean. A common way to work with predicates in .NET is to use the Func of T,bool, or an expression of Func of T,bool types. If you're used to using LINQ to build queries, you've probably worked with these types as part of lambda expressions. For example, a predicate that would filter out songs that have a rating of 3 or less would look something like this. You can read this as s such that s.Rating greater than 3, and this would return true for any song with a rating of 4 or 5, but false for any song with an integer rating of 3 or less. These kinds of predicates work best for small, simple conditions, they're not named, and they're often defined separately from where they're executed. For instance, they might be written in the UI layer, but executed somewhere inside of a data access layer when they're actually filtering the underlying data or collection. They're also frequently defined as part of a class whose main responsibility is something other than querying or filtering, and so they may be difficult to test independently. Let's take a quick look at an example showing how we can use predicates to filter a collection of songs in a music library. This demo application is called myTunes, not to be confused with any similar-sounding music management applications. Looking at the source code for myTunes, we see that we have a class called Song, and a song has a Title and an Artist, a Year, an AlbumId, and a list of Genres that it might belong to. Now once we build this project, we can actually open it up in LINQPad and start working with the data. LINQPad can be used to communicate with a SQL database, or you can use it to just execute ad hoc C# statements. You can even have it work against your existing solution so that you can work with the data types and models that you already have written. In this case, I've already wired this up so that it's working with our Web.dll from the project that I just showed you, and that project has a SampleData class that I used to populate all of the data in the database. In this case, I'm not going to be hitting the database, I'm just going to be working with that sample data directly in memory. In addition in order to make my life a little easier while I work with some of the model types in my project, I've imported the Web.Models namespace into LINQPad for this particular set of queries as well. If you haven't used LINQPad before, it has a helper method called Dump that will dump out whatever data you have into the results window. So when I run this application right now, you'll see that this is my sample data when it is dumped out. Here is the list of Albums, the list of Genres, and we can reduce these down so they take up less space, and the list of Songs. This is the contents of my SampleData at the moment. Now let's look at how we can write a predicate to work with some of this data. Looking at the songs, you'll see that each one has a rating. As we showed in the slide just now, we can write a predicate to filter out songs that only have a certain rating. For example, this expression here is going to take all songs that have a rating of at least 4 and return those back in its own enumerable. So when we run this, we only get a list of songs, and we can see that they all have a rating of 5. Now the predicate in this case is shown here, s = greater than, s.Rating greater than 4. Typically when I refer to one of these I will pronounce this as, s such that s.Rating greater than 4, or if you know the type you could say song, such that the song's rating is greater than 4. Now as I mentioned, one of the things that is a disadvantage of using predicates directly like this is that they don't have a good way to be given a name that you can refer to them by. However, one approach that you can take to this is to assign the predicate to a variable, and then you've got a variable name that you can use. To assign this predicate to a named variable, we simply need to create a variable of the appropriate type. In this case it's going to be a Func of the type, bool, and what this means is that it's a function that accepts a parameter of type song and returns a Boolean. Now we need to give this a name, so we'll call this our topSongsPredicate, and we'll assign that to our actual predicate here, and we see that that works. And then to test out that this does what we expect, we can use it in place of the original predicate, and perhaps have a more readable version, and you see the results are the same, we still get 10 items, all with a rating of 5. One last thing to show you is that you can also define an expression in much the same way. So I can take this predicate, and now I can define it as an expression. (Typing) At this point it's not going to allow us to use the expression directly, in this particular case, because the data type I'm using does not support it. I'm not using an IQueryable directly, I'm using a list, and list does not contain a definition for where that will take an expression directly like this. However, to convert an expression into the underlying predicate, you can simply call .Compile, and now this will work. Now the reason why you might want to use an expression instead of a predicate directly is that you can work with an expression, you can pass around an expression, you can edit that expression and build upon it, and when you're using things like LINQ to Entities, LINQ to Entities is going to want to use an expression to be able to convert that into SQL. Confirming that this still returns the same results, you can see that it does. Now this is how we can work with very simple Boolean expressions like this song rating greater than 4, we'll see in a few minutes how this type of expression can get very complex, and it becomes more and more compelling to move that complexity into its own type rather than having that be in-line within some other method. That's not to say you can't create complex query logic using predicates, it's just that they're not necessarily the best for that purpose because they then become difficult to reason about and understand. So if that's the case, where does complex query logic belong? Complex query logic is a common occurrence in real software systems, but where should we put it? We've already seen how complex rules can clutter entities and value objects, and if such rules involve multiple domain types, they may not really belong on any one of these types due to the coupling this would create. However, we also don't want to move this logic outside of our domain model if possible. Certainly we could perform all such querying in the UI layer, or with stored procedures within the data layer, but this pushes important business rules outside of our domain model, reducing the value of the model and making this logic more difficult to test and reason about in the context of our application. Predicates offer a simple means of filtering, but they're not ideal for complex querying since they don't communicate intent well and aren't first class citizens within the model. They can be difficult to test when they are embedded within other code, they're not named, although you could assign them to a variable in order to try and give them one, or add code comments, which is far from ideal, and so essentially predicates fall short once you start to deal with additional complexity. Dealing with complexity is exactly what domain-driven design is meant to address, and so this is the DDD design pattern specification comes into play. Uses and Validation A specification states a constraints on the state of an object. The object need not be present, a specification can stand alone, and can even be persisted independently from the objects that it evaluates. The specification can check any object to see whether it satisfies its criteria, assuming it's of the appropriate type. And finally, the specification should be modeled as a value object, meaning it has no identity and can be compared with other specifications based only on its state. Let's examine some of the common uses for the specification pattern. Validation is a very common one, which is often otherwise built into an entity directly. Validation logic can increase the complexity of types and may result in coupling with other types if the validation is dependent on the state of other objects. Also, validation is often context specific, so although an entity might start out with a simple isValid method or isReady, this can often evolve over time to include various scenarios. Is it valid for what? Is it valid for saving, for purchasing, is it valid for moving into some new state, etc.? Each of these variations could be modeled as a separate specification. Another common use for specifications is selection from a collection, or querying from a data source. For this purpose, the specification is frequently used along with the repository design pattern, which models a data source using a collection-like interface. As we'll see, using the specification with the repository can help reduce potential duplication, as well as leaking of the underlying data store abstraction through the repository interface. Finally, the specification can identify the requirements of an object so that one is created that can satisfy certain needs. The specification in this case may be passed into a factory method that uses the specification to determine which type needs to be created and then returned. Consider this validation example, which Pluralsight might use to identify courses that are ready for publication. This is a simple example, a more realistic one might return information about the validation rule that resulted in the validation failure. In this case, there are many reasons why a course might not be ready to publish. It might have no modules or no author contracts, it might be lacking a publication date or a description, perhaps one or more of the modules is lacking the necessary URLs for the slides or other downloadable materials, or maybe one of the contracts is still in need of a signature. If any of these conditions occur, the validation fails by returning false. Otherwise, validation is successful and the specification method returns true. This example introduces a simple, generic interface for specifications. You can use this interface to create your first specifications, it's the basic pattern introduced by Eric Evans in his Domain-Drive Design book. However, it's most appropriate for use against in-memory collections of objects. This makes it fine for most validation scenarios, but once we start talking about using specifications as a mean for defining criteria for queries against data sources, it can fall short. Specifications and Data If you were to use the IsSatisfiedBy Boolean function shown in the last slide for a query method, such as against an Entity Framework DB set, you would run into some difficulties. Consider this example of a list method that uses the specification to filter the results. This method will compile just fine, and it will run fine provided that courses is a simple collection. However, if _courses is a DB set and the resulting query is going to be translated into SQL, a runtime error will occur since Entity Framework cannot convert isSatisfiedBy into a SQL statement. You can fix this runtime error by first converting courses to an in-memory list, but now all of the records will be pulled from the database into memory, and then filtered there, which can be extremely inefficient for large numbers of records, and likely to cause performance problems in your application. An alternative approach is to utilize predicates within our specifications so that Entity Framework or other object relational mappers can convert the rules into SQL. This means changing the interface to include a predicate of the appropriate type, like so. Implementing the logic from our previous specification using lambda syntax results in this implementation. This produces the same logic as the previous code, but in a single statement using a predicate combining many different statements using and operations. More importantly, Entity Framework can use this predicate to generate SQL that will run on the database for our query. Converting the list method that we just saw to use a predicate instead is very straightforward. This is a commonly used approach when combined with the repository pattern as a way of making the repository more flexible and open to variations defined by calling methods. You can apply this to your data access or repository methods without even using a specification pattern. However, you may wish to constrain how clients work with your repository methods to reduce duplication of these kinds of lambda expressions in different levels of your application such as the user interface. It's very common with repository interfaces like this one, or that return IQueryable to see MVC controllers full of lambda expressions that are more of a data access nature than a UI concern. To enforce the use of specifications, you can return to the previous implementation of list, which takes an instance of a specification, in this case using the new ISpec version that uses a predicate. This version has the same runtime behavior, but now requires client code to go through a specification in order to define the query that they're going to execute. This can help keep your repositories from growing over time to include many different query methods, violating the open/closed principle. Using this approach will ideally result in well-named specifications being reused, and developers taking greater care with how they query records through the interface, or it might result in them just calling the parameter list version of list and adding a .Where method to the end of it, filtering the results in memory. Hopefully the latter is caught in your code reviews since it will result in the same type of performance issues that we've already discussed. You can certainly do both as well, having a list method that accepts a predicate, as well as one that takes a specification, and this is probably the best approach since it balances the ability for you to take complex queries and store them as objects in specifications, while still allowing your developers the flexibility to pass in simple predicate expressions to filter down queries without having to create a new specification for every different variation that might come along. Note that not all predicate expressions can be converted into SQL statements by Entity Framework. In particular, anything that uses a custom function that you created probably will not work and will result in a runtime error. Now we're going to use LINQPad to communicate with our project and operate on it through Entity Framework using our AppDbContext shown here. I want to point out that I've added a namespace for System.Data.Entity, and we'll see why in just a moment. So first let's take a look at the list of songs. When we run this, you'll see that we have quite a few queries running. First is our selection from the Songs table, and then you can see we're also querying from Albums for AlbumId 1, and then AlbumId 2, etc., and that's because we have lazy loading enabled by default. And so when Dump is called it iterates through all the properties on the object, resulting in these additional calls. So we have 20 songs that were called back, and if we look at this object set, this DbSet, we'll see that it has quite a bit of complexity involved on it. Many other things are being shown here besides just our song type. This is true because Entity Framework wraps up what it returns, and gives us a proxy that includes the actual song type, as well as a bunch of other Entity Framework structures. We can optimize this call by including Albums in the first call. In this case you can see that we only made one SQL query before we got back our list of songs. You don't want to have lazy loading turned on in your web applications if you can avoid it, because you want have as few database requests as possible. This will ensure that your web server returns web requests as quickly as possible. Now I don't personally like having magic strings in my code, so if you include that namespace that I already mentioned, the System.Data.Entity namespace, that will allow you to use a lambda expression here. Using the lambda expression, we get the same result as if we'd used the string. However now if we refactor our code, this code will automatically be updated as well. Now Entity Framework uses LINQ to Entities to translate predicate expressions into SQL, which is how it's creating the SQL statement here and joining on Albums for us. We can take advantage of this when we make our queries. For example, in addition to including the Album, we can also add some filtering. (Typing) In this example we're going to only return back songs with a year greater than 2000, and we only want to see the title, not all the columns. Here you can see the SQL that was generated as a result of this expression. Not only did we change the Where statement, but we also changed the Select statement so that we're only returning the column that we're interested in. This can be a big help in the efficiency of your queries, especially if you have very wide tables, or tables with very large data types, especially binary types. Of course we can perform this same filtering on a list of objects, and if we take our songs and simply add a .ToList to it, running the same query will result in the same 14 items that we had before. However, if you look at our query, you can see that now once again we are selecting all of the columns without any Where clause for this query. Having Entity Framework return the entire table's contents will be extremely inefficient for all but the smallest tables. Unfortunately if we have code that simply returns back an IQueryable, or an IEnumerable from a repository, unless we have some convention, we don't know whether or not we're going to be providing expressions that will operate on the database level through LINQ to Entities, or simply in memory. The other problem with LINQ to Entities is that it only works with certain known expressions. So for example if we change our query to look like this, now we're going to take advantage of the IsPreferred method on the song, which has some built-in filtering. You can see here that we don't have any errors in our code. If for instance I introduce an error, LINQPad will tell us immediately that we've got a problem. The fact that there are no red squiggles in this query tells us that it compiles correctly as C# code. When we run the code, however, we get a runtime exception telling us that LINQ to Entities does not recognize the method IsPreferred as something that it knows how to translate. One way we can fix this issue, again, is by operating on the objects in memory. In this case, our query runs as expected, but as you can see once again, we are pulling back the entire database table in order to run this method against every single row that gets returned from the database. This is extremely inefficient and not something we want to do if we can avoid it. Rather than producing code that may or may not work at runtime, despite compiling successfully, it's better for us to pass into the repository the expressions that will be used by Entity Framework's LINQ to Entities, then we can except as a convention that whatever is return from the repository is always an in-memory collection that we can further work with without any ambiguity. The specification provides a useful means of passing expressions into the repository for this purpose. It's worth noting that complex expressions can be built up by combining predicates or specifications into composite specifications. This is most typically done using either an and or an or operator, and using this approach allows you to build up complex rules from simpler ones. The resulting composite specification or predicate can be a named class itself, or you can create a class that will allow you to combine them at runtime in a dynamic fashion. Specifications can be used to build new objects, in addition to validating and querying or filtering them. When used in this manner, the specification can work from scratch to produce a complete new instance of an object that satisfies the specification, or it can be used based on an existing object. As an example, a shipment from one location to another may need to follow a defined route. The route consists of several segments from one location to another. Entire routes can be created from scratch, or if a shipment is interrupted in transit, and a segment is unavailable for some reason, a new route can be created based on the original that detours to reach the final destination. When used in this manner, the specification can be combined with the factory design pattern. The factory method accepts the specification as a parameter, and ensures that the resulting instance it produces conforms to the provided specification. At this point we've mentioned several real world implementations of the specification pattern, such as smart playlists, cargo container requirements, and shipment routes. In addition, specifications can be applied to medical populations. For instance, a drug trial might want to target patients that had certain characteristics. Stock portfolios might allow analysts to observe a set of stocks based on their traits, or to flag certain stocks for purchase or sale. Speaking of sales, sales regions could be defined within a company based on customer geography, what vertical industry they belong to, the company size, as well as other factors. Another example of using facing specification is the creation of repeating events such as Outlook and other calendars provide. These calendar applications provide users with a host of different options and rules for determining just how and when the event will recur, and a set of recurrence rules for a given event can be modeled as a specification. The specification pattern provides several benefits at the expense of creating a few more classes. The first benefit is separation of concerns. The logic involved in specifying a condition is encapsulated in a single class rather than added to an entity or left to clutter other application logic, such as within the user interface. This has the effect of decoupling the specification criteria from other implementation details, which in turn makes the specification logic easier to test in isolation from the rest of the application. Finally, specification classes have the benefit of being named and more easily documented as first class members of the domain model. They can also be serialized and persisted or passed between processes, when appropriate. Demo: Creating Smart Playlists Now let's look at an example of a simple web application that's designed to create music playlists, and see how we can transform it from one that doesn't use the specification pattern to one that does. I've already shown you myTunes, this music library application. This is what it looks like before I've performed any refactoring. This application allows us to filter all of the songs that we want to listen, in order to create a custom playlist. For example, we could find just the songs that have the word the in the title, and which have a certain minimum rating. We can also click on any given artist or album in order to see all the songs that are from that album, or from a given year, or from a rating. For the purposes of this demo, we're going to take a look at this query interface and see how we can use the specification pattern to improve it. This application is using ASP.NET MVC, and so the home controller's index method is the one that is being used for the query interface. Let's walk through some of the operations that are being performed. First, the query takes in a number of different parameters, including the selectedGenres, selectedArtists, the titleSearch that was entered, and the minRating. These will be used to construct the query. The page is going to pass a viewModel to its view. The full list of artists and genres is needed in order to populate the checkbox list shown on the page, and so those are added to the viewModel. Next the list of selected artists that was chosen, as well as the selected genres is pulled in, and this is used to repopulate the checkbox list, as well as to be used by the query that will return back the matching songs. Finally the set of songs is pulled in using the selectedArtists and Genres as part of the query, as well as the Rating. And then this is further reduced down by the titleSearch, determining whether or not the title contains the keywords that were selected. Finally the viewModel is populated with the songs and the view is returned. As you can see, this particular controller has a great deal of query logic embedded inside of it, and testing all of these cases would be very difficult to do because there's so many different things happening in this one particular method. This is violating the single responsibility principle, and if our query gets more complex, it's going to also violate the open/closed principle, two of the SOLID principles that you can learn more about in my SOLID Principles of Object-Oriented Design course. Two improve upon this, we're going to take advantage of the specification pattern, which I'll show you in just a moment. Another issue with this current design is that a new feature that is being requested, that is the ability to save smart playlists, is difficult to perform given the logic and the way it's designed currently. Now let's look at the refactored version of this code, which you'll find in the After folder in this course's associated download. Here's the new version of the interface, you can see that we've added a new Playlist Name textbox here along with a way to save it. Let's say that we want to create a set of great metal songs, we'll choose the genre of Metal and the rating of 4, run a filter, verify that this looks like a good set of songs for this playlist, and we'll name it Great Metal, and save this smart list, and now we are navigated to the Smart Playlists section of the site where we can see Great Metal is listed here. And for now I'm just including a JSON representation of the specification that represents this playlist. Here you can see that its GenreIds include number 4, which is going to be Metal, and also this minRating has been set to 4. Let's examine the code for this new version of the filter. The first thing to notice is that we're now working a specification, in this case it's the GlobalSongSpecification, and we'll look at that type in just a moment. This specification has an ArtistsToInclude, a GenreIdsToInclude, MinRating, and TitleFilter, the same things that we had originally, but now they're just properties on the specification. We add the selected items that were chosen via the user interface to the specification, and then get back the songs by calling a repository and passing in our specification. There is no query logic, there's no lambda expressions to speak of in this part of our code. Populating the viewModel, we still need to pass in the lists of artists and genres, as well as the selected artists and genres before passing that on into our view. If they click Save, then the Save button will have a non-null property and we're going to create a smart playlist. Now a smart playlist is separate from a specification, it's an entity with a name and an ID that we're going to persist in our database. In this case, we simply apply the name and pass in our specification to the smartPlaylist. Then we create a repository and use that to add the smartPlaylist to the database. One of the benefits of a specification is that it's much easier to persist than a lambda expression by itself. Let's take a look at our global specification, as well as some other specifications that I've created just as examples. First the GlobalSongSpecification that we've just used simply has these lists of GenreIds, AlbumIds, Artists and Title and MinRating, and a Criteria function. This Criteria function is an expression, and so Entity Framework will be able to use it to translate using LINQ to Entities, creating SQL that will make sure that this filter runs on the database. Notice that we are ignoring this particular items when we are serializing it using JSON. All of our query logic is embedded inside of this criteria, and so we could easily write unit tests, setting different properties, and ensuring that the criteria correctly filters out a given set of objects or a database query, depending on whether or not we're unit testing or integration testing. Looking at some other specifications, we have an AllSongsSpecification, which also uses the ISpecification of Song, which simply requires that it have a criteria. In this case, the criteria simply returns true for every item, and so this will always return back the entire list of songs. We could get back just an album, in which case we would create a SongAlbumSpecification, specify what that album is, and the expression is already set up to return that. Now some of these are probably a little more trivial than we would want to create individual specifications for, but I wanted to demonstrate how easy it is to produce individual specifications for any given set of criteria. Once you have a number of different criteria, you can compose specifications using and or or, in this case I've created an and specification that uses the PredicateBuilder that you can find here from This PredicateBuilder will take the leftSpecification.Criteria and And it with the rightSpecification.Criteria. This allows you to compose complex specifications from a number of simpler ones. Finally, the SmartPlaylist is allowing us to take the specification and save it in the database. This is done by simply converting the specification into JSON using JsonConvert from Newtonsoft.Json's library. The trick to store the specification in the database correctly is to create a separate property called Json, we ignore the JSON when we serialize this object to avoid having an infinite loop, but within our DbContext, we ignore the specification instead and use the JSON as the item that we're going to serialize to the database table. Thus if we look at the SQL that is generated by Entity Framework for this particular type, we are going to find that it has an ID, a name, and a column called SpecificationJson. That's it for this simple example of showing how you can use the specification to simplify the logic that is used inside of your controller, or other UI portion of your code, eliminating the need for complex query logic and ensuring that you have testable queries that you can have isolated from your UI code. This also allows us to save specifications at the user interface level so that users can have smart playlists that they can name and save for later use, and as they continue to add additional songs, those songs will appear in those smart playlists if they meet the criteria that are saved in that specification. Summary You can learn more about some of the related concepts mentioned in this course from the URLs shown on this slide. In summary, the specification design pattern is generally used for validation, filtering, and build-to-order scenarios. A specification defines a method or predicate that matches certain qualifying objects, and the specification pattern helps to separate concerns and decouple code from the objects that need to match other things and the matching logic itself. Finally, specifications can be more expressive than other approaches that might simply include Boolean logic within another method. Thanks for watching, and if you have any questions, please post them in the Feedback tab of the course.