How To Use Structural And Creational Design Patterns In C# | Mark Farragher | Skillshare

Playback Speed


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

How To Use Structural And Creational Design Patterns In C#

teacher avatar Mark Farragher, Microsoft Certified Trainer

Watch this class and thousands more

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

Watch this class and thousands more

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

Lessons in This Class

15 Lessons (3h 36m)
    • 1. Structural and creational design patterns

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

      5:22
    • 3. The abstract factory pattern

      18:16
    • 4. The builder pattern

      15:44
    • 5. Factory method

      17:49
    • 6. The prototype pattern

      15:08
    • 7. The singleton pattern

      13:39
    • 8. The adapter pattern

      18:15
    • 9. The bridge pattern

      17:37
    • 10. The composite pattern

      18:05
    • 11. The decorator pattern

      17:47
    • 12. The facade pattern

      16:18
    • 13. The flyweight pattern

      19:39
    • 14. The proxy pattern

      16:54
    • 15. Course recap

      3:10
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

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

143

Students

--

Projects

About This Class

fccd7ba1

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

In this course I will teach you the first 12 design patterns. These are all 5 creational- and all 7 structural design patterns. You use these patterns to create new objects efficiently and to create structure in your application architecture.

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

Why should you take this course?

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

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

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

Meet Your Teacher

Teacher Profile Image

Mark Farragher

Microsoft Certified Trainer

Teacher

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

See full profile

Class Ratings

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

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

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

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

Transcripts

1. Structural and creational design patterns: Let me ask you a question. Would you like to become a C sharp pattern? Architects. Okay, so I just made that word up. There is no pattern architects, but in my book, But I think that word means is that you are a senior developer with a keen understanding off software design patterns. If you are released developers or architects, this knowledge is essential for you to do your job. So in this course, I will help you learn the fundamental gun or Ford software design patterns. So we're going to look at creation all design patterns like the factory method pattern, the prototype pattern builder pattern on many others. We're going to look at structural design patterns like the adapter pattern, the composite pattern, the decorator pattern on many others. So we're looking out of the famous offer design patterns off the gun off. Four book The Gun or four book is basically the Bible off software design methodology on the patterns covered in the book are essential knowledge. If you're a developer, if your a C sharp developer, you really need to know these patterns. They are crucial. If you want to get promoted to lead developer or two architects as an architect. Oil in the world a all day is assemble architectures from design patterns. So are you interested in becoming a C sharp pattern? Architects. Then this is the course for you have created this course for developers who want to take a career tour to the next level. For junior developers who want to become lead developer for lead developers who want to become architects until want to brush up their knowledge off the essential software design patterns to make an awesome impression in their next job interview. So thank you for listening on. I hope I'll be seeing you in the course. 2. The gang of four and the 23 design patterns: Okay, let's talk about design patterns. What exactly is the design pattern in software engineering? A design pattern is a general reusable solution to a commonly a curing problem. It is a description or a template for how to solve a problem. There can be used in many different situations. Patterns are formalized best practices that's the programmer can use to solve common problems when designing an application or a system. A design pattern typically shows relationships on interactions between classes or objects, but without specifying the final application classes or objects that are involved. A good example is in admiration. When you need to iterated Lee, step through each item in a list. You would probably use the for each statements in C Sharp aunt Think nothing about it. But behind the scenes, there's actually a lot going on. The C Sharp compiler creates a special in numerator object to implement the for each loop in numerator is an object specifically designed to step through items in a list. The in operator has a current property for reading the current item. Andi, it has a move next message to advance the currents property to the next item. The move next message returns false When there are no more items, this is actually an implementation off a fundamental design pattern called it aerator. So each time when you need to iterative Lee, step through a list. You can, of course, develop your own custom codes, but it's much better to use the standard iterated pattern. This pattern was documented by the Gang of 4 21 years ago on generations of programmers have already used it and can vouch for its correctness. Design patterns also simplified teamwork with other developers. When you say we will use the iterated pattern, everybody knows what you're talking about, and you know exactly what kind of codes to expect when the pattern is implemented. Design patterns are kind off blueprints for a collection, off classes and object relationships that work together to solve a common problem. They allow you to use simple names to describe large sections off your application architecture, and this simplifies team developments enormously. Okay, now, in 1994 something very special happens. Four developers came together and wrote a book on design patterns. They were Harris comma Richard Helm, Ralph Johnson on John Flys IDs, and they became so famous that they are now simply referred to as the gun off four. The book they wrote was called design Patterns, Elements off reusable, Object oriented software, and in the book they presented a very interesting theory. They claims that they had discovered 23 fundamental design patterns, and that's all. Other patterns were simply combinations off these fundamental patterns. Their book has bean enormously influential to the field off software engineering, and today it is regarded as the standard reference manual for object oriented design, Siri and Practice. If you want to become an application architect, you simply have to know all fundamental design patterns by heart. So in this course I will teach you the 1st 12 gun or four patterns. This consists off all five creation all and all seven structural design patterns. You use these patterns to create new objects efficiently. Hands to create structure in your application architecture. Are you ready? Let's get started 3. The abstract factory pattern: Okay, let's kick off with the first pattern from the famous group Off 23. Gang off four design patterns. This one is called abstract factory Pattern on, and it is a pattern you use when creating new objects. I will start with a quick summary off what we are trying to accomplish with this pattern. Remember, there's a famous anti pattern called pattern love that's applies to developers using correct design patterns in the wrong circumstances. So it's very importance to realize when you're supposed to use the pattern so the abstracts factory pattern is a good choice. When you are trying to accomplish the following, you want to provide an interface for creating families off related or dependent objects without specifying their concrete classes. Your objects can be groups into a hierarchy. That income populates several distinct platforms, each consisting off a sweet, off related objects. The calling coat works with abstract interfaces and classes and does not need to know the exact types off the objects created by the factory. Okay, let's go through the points one by one. First of all, you must have the needs to creates two or more objects, but with a very specific relationship between them. These objects are often called products on. The pattern provides a way to creates a whole set off products. In one go, this sets off products is called a platform within the platform. The products into operates with each other in a specific way, and this brings me to the second points. To use the pattern effectively, you must have a large collection off objects that you can group into at least two platforms with each platform containing the inter operating set off products. And finally you're calling codes must only work with abstract platform interfaces and classes and never need to know the exact type off. The created objects the factory objects provides a creation service for the entire collection. Off platforms clients never creates platform objects directly, but instead they always ask the factory to do that. For them, the biggest benefits off the abstract factory pattern is to remove ugly. If then else blocks from your code, think about it without the benefit off having multiple platforms, you would need some kind off super platform that regulates the interaction off each possible product objects with all other products. The code would quickly devolved into a mess off switch. And if statements, there's an anti pattern for this, too. A single platform that tries to regulate all objects interactions in an application is called a god's object on. It's considered a bad practice. This design pattern makes exchanging platforms very easy because the platform factory class appears only once in the code in the top level factory, so you can quickly replace the entire platform simply by in Stan Shih ating a different platform factory. Because the service provided by the platform factory object is so pervasive it is often implemented as a singleton. But we will get to the singleton pattern in a later lecture. Here is the U. N. L. Diagram off the abstract factory pattern. On the left hand side is the products hierarchy. We have a platform off to related products. The abstract versions off these products are cools abstracts products, a Andi abstracted products be. There are two platforms, and this gives us four distinct products products a one. Its products be one in the first last four aunt product, a two and product be too in the second platform. On the right hand side is the factory hierarchy each platform against its own dedicated factory class concrete factory, one for the first platform on a concrete factory, two for the second plus form. There's also a common base factory called Abstract Factory. So now the idea is that a client's can simply call the abstract factory to create any off the A and B products. The abstract factory will determine which platform to use. Then, instead, she ate the correct platform factory and then ask that factory to create the actual products. We end up with either a set off products, a one on product, be one or the sets off products. A two on products be too, depending on which platform was chosen. What might surprise you is that there is no specific class for the platform itself. Sometimes you see a slightly more complex version off this pattern, with an explicit platform class. In that model, the products do not interact directly. Instead, it is the platform class that interacts with the products. This is slightly more elegant because the product no longer needs to reference each other, but it adds a number off extra platform classes to the pattern. In my model, I do not use platforms on the products interact directly with each other. The platform factory is responsible for creating a set of products that are compatible with each other. This keeps the number off classes down and makes the pattern easier to understand. Now let's look at a concrete example off the design pattern. I am going to show you on application that models food chains on different continents around the world. You might have heard off the rabbits and fox cycle. This is a mathematical model that simulates rabbits and fox populations. Foxes eat rabbits and proliferate until there aren't enough rabbits to feed the foxes. The fox population then crashes and then recovers. This leads to a kind off sine wave off rabbits and fox populations. I am going to write a program that simulates a population off carnivores and herbivores, using animals on different continents off the world. So these are the objects I'm going to need. You can see that I have to abstract products. Carnivore on who her before. I also have two platforms. Africa, Aunt Australia. The Matrix contains four products. Lyon, Zebra, Dingo and Kangaroo. So I'm going to need factories to create the correct set of products. I can't have a lion being paired with a kangaroo because these animals live on different continents and we'll never meet each other. So I will need a continent factory that will either create on Africa factory or on Australia factory for me. Finally, I'll adds a class called ecosystem. This represents the clients. I'll provide the ecosystem with a factory and then let it simulate one single alteration, with one carnivore eating one her before. So here is the complete list of classes in this example. Okay, let's take a look at the code. So up here is the definition off the continent factory. You can see that it's nothing more than a simple, abstract based class that defines the two product creation methods creates quite a for and create her before. Next are the two concrete factories African Factory on Australia factory. You can see that both classes derive from continents factory and implement the product creation methods. The African A factory creates lions on zebras as the Australia factory creates kangaroos and dingoes. Next are the products classes. We start with an abstract her before class, which right now has no implementation. But the Carnivore class has a single method called eat, which expects a her before arguments so carnivores can eat her before. Next are the concrete's products classes for lion, zebra, kangaroo on a dingo and down here is the ecosystem. The constructor expects a single argument off type continents factory and then uses that factory to set up a single carnivore on her before and down. Here is a wrong message, which kind of runs the ecosystem by having Z Carnivore eat for her before finally, in the main program methods I set up on entire ecosystem with the Africa factory and run it . Next I do the whole thing all over again. But now with an Australia factory, in both cases the ecosystem will consist off a single carnivore and her before from that continent on the carnivore will eat the her before now notice that the ecosystem class has no idea what kinds of objects are being created. It has no clue what zebra or a lioness all it cares about is creating a single kinda for on her before and then have the one eat the other. Let me run the program to prove that everything is working I'm compiling the code now on. No, I'm running is and there you have it. The lion eats zebra on the dingo, each the kangaroo. Here's a quick checklist you can use to implement the abstract factory pattern. Make sure you have a large products family with lots off annoying interdependencies between products on your product. Handling codes contains lots off switch and if statements, then creating matrix off platform versus products and check. If each products can be neatly groups into a platform, then make sure you have at least two abstract products and platforms. Create an abstract factory class with abstract, create methods for each product. Type creates a derived factory for each plants form and implement the create methods. And finally make sure the clients does not use new anywhere and only uses the abstract types. And here are some final comments. What I've shown you so far is an abstract factory design pattern that uses factories to create the product instances. But there's no rule that states that you must use factories. You can also use a builder or prototype pattern to create the actual objects. Pick the creation pattern that best suits your needs. The abstracts factory in my cold is where regular objects. But because it gets calls so many times from all over the place in your code, you often see it being implemented as a singleton. This is perfectly fine. Feel free to use the singleton pattern here, but do keep in mind that many developers consider the singleton pattern to be harmful and try to avoid it as much as possible. You might get into an argument with your colleagues on this one, and finally, you've seen that the abstract factory pattern effectively hides the concrete types off the products objects. This type of information hiding can be useful if you want to hide certain classes from the outside world. The pattern off choice for this kind of information hiding is called facade. We'll get with that shortly, but you could also use on abstract factory instead of a facade. Something to consider. Okay, so here's a summary off what we've learned. The abstract factory design pattern provides an interface for creating families off related objects without having to specify their concrete classes. Use this pattern, if you're objects, can be grouped into a hierarchy that encapsulates several distinct platforms each consisting off a sweet, off related objects. The calling coat on Lee uses abstract classes and never instance. Yates objects directly. Andi. It does not need to know the exact types off the products being created by the factory. You can combine an abstract factory pattern with the builder or prototype pattern, or you can implement the abstracts factory as a singleton. The abstract factory design pattern can sometimes be used in place off the facade pattern. 4. The builder pattern: here is the second pattern from the gang of four. This one is called Builder Pattern on. It is a pattern you use when creating new objects. Here's a quick summary off what we're trying to accomplish with this pattern. The builder pattern is a good choice when you are trying to accomplish the following. You want to separate the construction of a complex objects from its representation so that you can use the same construction process for different types of objects, or you want to parse a complex representation. Let's say an XML file. Andi creates one off several targets. Objects out of it. Let's go through the points one by one. So in the first case you have some kind off complex objects in the terminology. Off this pattern, we call the object a product. Usually the products will be on aggregate object, meaning it isn't objects composed off two or more child objects. We call these Childs Objects parts. There are a lot off possible permutations off parts, so instead off adding lots off complicated construction codes in the product itself, you instead move all that code into a separate builder class. Now the builder is responsible for constructing the product by repeatedly creating and adding parts until the product is complete. The idea is that different types off builders can create difference products by adding different combinations off parts. So in this set up, the products represents pure data on the builder represents the construction process on the two are kept strictly separate. You see this same type of separation in the second case, where we are parsing a complex representation on reading the data into a product. For example, there might be different types off financial transactions, stores in XML and text files. A single abstract transaction instance can be initialized from either on XML builder or a text builder. Both builders reads in the external files, extract the data and use it to construct a new transaction. Instance, The builder pattern offers a number off benefits over straight up construction off objects using the new keywords. First, the builder pattern is ideal if the construction process a cures in a number off discrete steps, instead off all in one go, the builder creates a new products part each time it's called, and it's maintains all intermediate state. When the product is finished, the clients can retrieve the finished products seconds. This pattern establishes a strict separation between data presentation, the construction process. All the complex codes for constructing the products is hidden away in the builder class. On the code off the products, classes stays clean. Third, the pattern is convenience. When a single product can be represented by several representations, for example, the products might be encoded in an XML file, a binary file or a text file in the builder pattern. We would use three different builders to construct a single unifying product instance from these three sources. Finally, the builder pattern offers fine grains control over the construction process. Unlike creation all patterns that construct products in one go, the builder pattern constructs the products step by step. This offers more flexibility. Here is the UML diagram off the builder pattern. The pattern is fairly simple. With only a few classes. The builder class is an abstract based class that specifies an interface for creating the parts off the product. Usually, this interface will be in the form off. Multiple abstracts builds parts X x x methods. The director will call these methods in the correct order to assemble products. The concrete builder is a subclass derives from builder that actually constructs and assembles the parts off the products. By implementing the builder interface, the class uses a protected field to keep track off the product it creates, and it provides an interface for retrieving the products. This will usually be a message called Get Results or something. The director is responsible for constructing a product. Using the builder interface. You initialize the director with a concrete builder. The director provides a construct methods that will call each builds part x x X methods to assemble a complete products. And finally we have the products class. This class represents the complex objects under construction. The concrete builder builds the products internal representation and defines the process by which is assembled. What might surprise you is that you use the director to build a products by adding parts in the correct order. But once the product is finished, you retrieve it directly from the builder. This is another separation off construction logic. The builders only specify how to add specific parts to the products. The director only decides which part methods to call Anne was ordered. Let me show you an example off the builder pattern. I am going to write software for a fast food restaurant. You might have noticed that places like McDonald's or Burger King work with standardized menus. There's always a burger fries drink on a dessert on the menu on the Kids menu. Doesn't have a desert, but it's includes an extra toy. So the products in this example are the actual menu, and the parts are the various food items that make up the menu. There are different types off menus in a fast food restaurant. There's always a burger menu, a salad menu on the kids menu. So I am going to needs three different menu builders to create these menus. Finally, there's a director class that's responsible for assembling the components off the menu. A burger or salads, fries Hey, desserts on optionally a toy for kids. So I am going to implement the pattern with the following classes. Okay, let's take a look at the code. I'll start with the menu director. This is a very simple class with a construct method that except a single menu builder arguments. The director then assembles a complete menu by adding all the possible components a burger or salads, fries, a desserts, a drink on a toy. Next is the menu builder. This is the abstract top level builder class that constructs an entire menu. There are builder methods for adding a burger or salads, fries, desserts on the toy. Finally, there's an abstract get results methods to retrieve the finished menu. Next are the concrete builders you can see that's I have builders for a burger menu, a solid menu under kids menu. Each builder implements the bills methods in a different way to create that specific menu, and next is the menu class. The menu is on aggregates object that uses a dictionary to store the parts that make up the menu. There's also to string methods to return the entire menu as a string. And finally, let's take a look at the main program methods. The codes here, Initialize is a burger menu builder and then uses a menu director to assemble the complete menu. Then it retrieves the finished menu from the builder and displays its on the console. The next card fragments does the exact same thing, but this time for a kids menu. Okay, let me run the program to prove to you that everything is working. I am complaining the codes now. Ums. No, I'm running the program under you have it. One burger menu on one kids menu. Everything works. Okay. Here is a quick checklist you can use to implement the abstracts factory pattern. First, make sure you have lots off aggregates products that differ only in their permutation off internal parts. On your construction called involves a number off sequential steps, then creates a concrete builder class for each prototype and move each construction step into a separate build. Methods then designed a standard protocol for all build steps and capture the steps off this protocol in the abstract builder class, then define a director that calls the builder methods in the correct order. That's finally make sure that the clients does not use new anywhere and only uses the builder to creates new instances. Okay, awesome final comments. What I've shown you so far is a builder pattern that uses simple methods to create parts. But you can also use a prototype or factory pattern to create the parts bickley creation pattern that best suits your needs. The builder pattern is especially useful to create composite objects. The composites pattern is a structural pattern that we are going to discuss in an upcoming lecture, as finally, you usually start out using factory methods to create objects. But then, as your colds gets more and more complex, you might want to re factor your colt to a prototype or builder pattern. This is perfectly OK. Feel free to swap one pattern for another as your codes evils. All right. Here's a summary off what we've learned. The builder pattern provides an interface for constructing a family off complex objects in multiple steps, so that's you can use the same construction process for different types of objects. Use this pattern, if you're objects, can be grouped into sets. That's differ only by the permutation off their internal parts. And if the construction process consists off a number off discrete steps, the director class ensures that the order off build steps is always the same for every type of objects. The calling colds never instance. Yates objects directly, and it does not need to know the exact details. Off the builds process, you can combine a builder pattern with a prototype or factory pattern. It's perfectly fine to migrate from a factory pattern to a builder pattern. As your codes evolves 5. Factory method: here is the swords pattern from the gang of four. This one is called factory message pattern. Andi is a pattern you use when creating new objects. He was a quick summary off what we're trying to accomplish with this pattern. The factory message pattern is a good choice when you are trying to accomplish the following, you want to define an interface for creating objects. But you want to let sub classes decides which class to instead she ate. You want to decouple the requesting objects from creating objects? The calling coats doesn't need to know what types of objects are creators. Okay, let's go through the points one by one. The key intense is that you want to request some kind of objects in the terminology off this pattern, we call the objects a products. This design pattern gives you fine control over how the products is created. The big disadvantage off the new keywords in C sharp is that it does exactly what you specify. It always creates a new objects off exactly the given type. This is all fine and good, but what's if you sometimes needs to create a subclass off the given type instead Or maybe you want to occasionally recycle on existing objects instead off always creating a new one . This pattern gives you that flexibility. The factory method sets up on abstract objects constructor that you can overrides in sub classes. This gives the subclass full control over object creation. The calling codes simply requests. A new object on the subclass decides how to respond, and finally, the calling. Cults must only work with abstract products classes and never need to know the exact type off the created objects. The factory class provides a creation service for the entire applications. Clients never creates products directly, but instead they always ask the factory to do that for them. So I've already mentioned two important benefits off the factory pattern. The first benefits is flexibility the clients requests on objects, and the factory subclass has full control over the creation process. It's can return on exact instance off the requested type, but it's gonna also return a subclass if necessary. The clients basically requests a new product, and it's up to the subclass to decide if this is going to be product a product be or product. See, the second benefits is that the subclass can also decides not to create a new object at all . There might be a perfectly fine existing objects lying around that can be returns. You often see this with immutable objects. Examples are string adults empty, four color adults read. These are both factory methods that to return a pre existing immutable object instead off creating a new one on the fly. Another benefits is cold. Maintain ability, all objects. Construction happens in a small number or factory classes. So if you need to change the type off products objects that are created, you only need to re factor a small amount of codes. Without the factory pattern, you would have to hunt through your entire code base on track down every single new operator. These benefits are so powerful that some developers are saying that you should always use factories for all object creation in your coat. Personally, though, I wouldn't go that far if the class that's in Stan Shih ations never changes, or if instant station takes place in a virtual method that sub classes can easily override , then there's no needs to use this matter. Okay, here is the UML diagram off the factory methods pattern. The diagram is fairly simple. On the letter, we have the products hierarchy with an abstract products super class and a concrete surplus on the right. We have the factory classes. There's an abstract super class factory called Creator with a factory methods called well factory messes. The factory method is abstract on returns, a value off type products. The method is implemented in the factory subclass, which is called concrete Creator. This class overrides the factory method and explicitly returns an object off type concrete products. To use the pattern, you creates a variable off type creator on initialize. It's with an instance off a concrete creator class. Then, when you call the factory message, it will return a concrete products. There's a very popular alternative pattern implementation, which looks like this in this model. The factory method is actually a static method off the products class. The static method even weighs its arguments and decides what kind off products subclass to return. The static pattern is slightly more elegant than the Creator pattern. Consider in the Creator pattern. The client has to specify which Concrete's creator to instance she ate so the clients actually has limited control over the type off products objects that will be returned. But in the static pattern, all creation logic is hidden away inside the static method. So now the clients has zero control over the creation process. I prefer the static pattern because it is slightly less verbose than the Creator pattern. I don't have to explicitly in Stan, she ate a creator. Before I can start creating product objects, a static methods is available right away. Okay, let's look at an example off the factory method pattern. In the previous lecture, I automated a fast food restaurants that serves kiddie menus that contains a small toy. So in this lecture, let's automate the factory that creates these toys. My toy factory uses a process calls injection molding to create plastic toys. In this process, a special plastic powder is injected into a mold on, then heated. The powder turns into plastic on the mold determines the shape off the plastic. The toy creation process is always the same. The factory prepares a quantity off plastic powder. Select the correct mold, injects the powder, heats the mold, extracts the toy that's finally paints the toy. So I am going to implement the pattern with these classes. Okay, let's take a look at the code. It all starts with a toy class. This is my abstract product class on It contains three abstract methods for creating a plastic toy. Get powder quantity, get heating time and get color. These methods return information to customize the toy creation process. The concrete products classes are the actual toys, fire, truck, duck and superman. These classes corresponds to the three toys that the factory is making. Each concrete class implements the get powder quantity, get heating time and gets color methods. You can see that the Superman toy requires 20 grams off plastic powder needs one minutes heating time that is painted blue. But now look at the fire truck. It needs 40 grams of plastic powder, two minutes off heating time, and it's painted red. Okay, let's look at the toy creator class. This is my abstracts factory class that specifies the toy creation process. It has a message for each step in the toy creation process. Prepare powder, select mold, injects, powder, heats, moles, extracts, toy and paint toy. Let's look at the make toy methods, which automates and the entire toy creation process. The method starts by creating a new toy instance by using the creates toy methods on this is the factory message. It is abstract needs to be implemented in a subclass. Next, the Make toy Methods asks the toy how many grands off plastic powder are needed. It calls the prepare powder methods to reserve this exact amount of powder. Then it select the correct mold and injects the reserves amount of powder into the mold. It asks the toy for the hating time and then heats the mold for that specific duration. It's extracts the toy. I'm then asks the toy for the paint color, and then it's paints the toy in that specific color. So the only abstracts methods in this entire process is create toy on the sub. Classes will implement these methods. So here is the fire truck creator class on. You can see that it implements the creates toy method by simply returning a new fire truck objects. The duck Creator class does the same, and it returns and you duck objects. That's finally here is the Superman Creator, which returns a new Superman instance. The main problem methods is down here. It declares a variable off type toy creator. And then initialize is it's with an instance off a fire truck creator. Finally, it calls Make toy to create an entire fire truck. The next code fragments does the exact same thing. But this time for a Superman toy. Let me run the program to prove that everything is working. I am compiling the code now, and though I am running the program and there you have it one fire truck and one superman, everything works. Okay, here's a quick checklist you can use to implement the factory method pattern. First, make sure you need control over how your code creates new objects. Do you occasionally need to return a subclass or reuse an existing objects? If not, then stick to the new operator. Next creates a concrete factory class for each type of object, Then create an abstract factory that unifies all concrete factories and finally make sure the clients does not use new anywhere and only uses the factory methods to create new instances on the Here are some final comments. In my example, the toy creator create a toy by calling a sequence off methods, starting with an abstract create toy method. We call this a factory method pattern. However, if any off the other methods are also virtual or abstracts, then we would call this a template message pattern, and in fact, you often see the factory method pattern and the template method pattern together in the same coat. The big advantage off a factory method is that it can return the same instance multiple times, in effect, decoupling the act off, requesting an object from the act off, creating an object that's finally you usually start out using factory methods to create objects. Then, as your cold gets more and more complex, you might want to re factor to a prototype or builder pattern. This is perfectly OK. Feel free to swap one pattern for another as your calls evolves. Okay, so here's a summary off what we've learned. The factory method pattern provides an interface for creating objects, but it lets sub classes decides which class two instance she ate. Use this pattern. If you're objects creation cults sometimes needs to return a subclass or reuse an existing objects. The factory method pattern is often seen together with the templates, message pattern, the calling colds never instance, Yates objects directly and does not need to know the exact type of objects being constructed. It's perfectly fine to migrate from a factory pattern to a builder or prototype pattern as your codes evils. 6. The prototype pattern: here is the fourth pattern from the gang of four. This one is called Put out a type pattern on. It's a pattern you use when creating new objects. Here's a quick summary off what we're trying to accomplish with this pattern. The prototype pattern is a good choice when you are trying to accomplish the following, you have a prototype objects instance on you want to create new objects by copying the prototype. Constructing a new object from zero takes a lot of time and effort. You want to move all construction logic away from the calling codes. Okay, let's go through the points one by one. The key intense is that you needs to construct an object with construction logic that always requires a number off identical steps. For example, you might be constructing a document that needs to be loaded from an XML file, and no matter what's document you create, you always start out with the same generic XML. Coz initializing a documents in this scenario is a complex process simply in Stan Shih. Ating a class is not enough. You also need to load onto parse the generic file loads on parse any extra custom is Asians and initialized the documents. The prototype pattern helps you to standardize the generic parts of each documents. The idea is that you load the generic XML once on stories in a prototype instance, Each time when you want to construct a new document, you simply clone the prototype instance in memory and then customize the clone. The prototype pattern offers a number off benefits over straight up construction off objects using the new keywords. First, the prototype pattern is ideal if the construction process a cures in a number off discrete steps. Initializing the prototype once on copying it in memory each time you need a new object is much more convenient than manually constructing aren't initializing each objects. This will simplify your colds. Second, there's a big performance benefits, too. Initializing your objects from an external file, say an XML file can be very slow. It's much faster to do this only once for the prototype object, and then copy the prototype in memory each time you need a new objects. Here is the UML diagram off the prototype pattern. The pattern is really simple. With only a few classes. The prototype class is on abstract based class that provides a clone method. There are two sub classes. Names concrete Prototype one and Concrete Prototype to that, both implement the clone method. When the client's needs a new object, it's declares a variable off type. Put out a type comes instead shades. It's with Isar concrete prototype one or concrete prototype to It's then calls the clone message to acquire a copy off the concrete prototype. Let me show you an example off the prototype pattern. You might have noticed that the images off my you'd emmick horses all look the same. It's always a left hope, with some kind off funny picture on the screen. The image for this course shows the blueprints off the Rights Flyer one. The very First powers airplane launched by the Wright Brothers in 1903 My other You Demi courses have different images. I have a course on multi threading that shows spools off threads. Andi. I have a course on memory management that shows two cards off the memory card game, so I'm going to write a program to create these images. The process off constructing these images is always the same. I start with a bit more then I load the laptop image into it, and then I add whatever course image is appropriate. The course image is blended over the laptop image so that it fits exactly into the laptop screen. I could construct each image by hands, but instead I'm going to use the prototype pattern. I will implement the pattern with the following classes. Let's take a look at the code. I'll start with a clone herbal class. This is simply an abstract class that sets up the clone methods. Nothing special here. I could have used an interface to, but I'll stick with an abstract class to match the design pattern. Next is course image. This is the actual prototype on represents. The laptop image here is on initialized method that sets up the object. You can see that I load the laptop image from disk From here on, the prototype is ready for use, and down here is the implement, its clone method. You can see that I start by calling the member wise clone method. This creates a shallow copy off the prototype image and stores it in the clone variable. But now I have a problem. The copy refers to the same image as the prototype. So if I try to make any modifications to the copy, I would be also modifying the prototype image to fix this. I call the clone methods on the bit map. This will create a duplicates off the biz map. Aunt assigned it to the copy. So now both the prototype on the copy refer to unique and separate images. Next is the course image maker class. This is the client's class that will construct the course images. For me. The class has a create image method that's expects the prototype on a file pass as arguments. It will then clone the prototype loads the seconds image Andi blend that second image on top off the prototype image. And finally, let's take a look at the main program methods. The codes. Here in Stan Shades, the prototype Andi Initialize is it's then. It uses the course image maker to creates three course images and right in to disco. Let me run the program to prove that everything is working. I am compiling the codes. No hands. Now I'm running the program. Okay, so now the program has run without errors. I am going to open a file browser window now so I can show you the assembles course images . Here we go. I'm there. They are three course images. Everything works fine. Okay, here is a quick checklist you can use to implement the prototype pattern. First, make sure your objects have complex, multi step initialization codes, and then they're all derived from the same generic templates, then creates an abstract prototype that declares a clone Methods creates concrete prototypes that implement the clone methods. Then, as a client's class, that initialize is objects by starting with a Clones prototype. Finally, make sure the calling coat does not use new anywhere and only uses the client to create new instances. And here are some final comments. My example. Used based class. Andi. I mentioned that you can also use an interface now. You might be aware that the dot net framework already has been interface for clothing objects. It's called Ike Low Nable. So why didn't I use not one? The reason I didn't use I clone Herbal is because it is completely unclear if I clone Herbal should create a shallow war. A deep copy. Microsoft never defined how the interface should behave and therefore they actually discourage you from using its in any kinds off public interface. Instead, you are encouraged to create your own clone method just like ideas in my code. Here's the difference between a shallow copy Onda Deep copy in a shallow copy. All value types on references are copies. The clone contains copies off each value type member, but all off the reference type members will be shared between the clone on the prototype, a deep copy goes one step further. The value types on references are copies, but also all off the objects that the reference types refer to. This creates a deep copy off the original prototype that does not share any objects with it . It's super easy to create a shallow copy indulge net. All you need to do is call the member wise clone methods, but there's no standard way to create a deep copy. You have to manually clone each reference type member just like I did in my bid my fields. But here's a tip. There's a very quick and easy way to instantly creates a deep copy off any object. All you need to do is serialized the prototype into a memory stream and then d c realize it back into a clone. This coat will do exactly that. Okay, here is a summary off what we have, Lawrence. The prototype pattern provides an interface for constructing objects by copying a prototype and modifying the copy. Use this pattern if you're objects. Initialization is expensive, and all objects share a common generic template. The clone methods can either make a shallow or a deep copy off the prototype. A quick and easy way to make a deep copy is by serializing the prototype into a memory stream. Onze d serializing it's back into a clone. You should never use the I clone herbal interface in public code because Microsoft never defined if it should make a shallow or a deep copy. 7. The singleton pattern: here is the fifth on final creation pattern off the gang off four. This pattern is called Singleton Pattern on, and it is a pattern you use when creating objects. Here's a quick summary off what we are trying to accomplish with this pattern. The singleton pattern is a good choice. When you are trying to accomplish the following, you want to ensure that a class has only one instance you want to provide global access to that single instance you want to make use off lazy initialization, also sometimes called just in time initialization. Okay, let's go through these points one by one. The 1st 2 points are key. Here you have a class on. You want to make sure that there is only a single instance off that class at any given time ? Sure, the more you want your entire application to have access to that single instance, a singleton often uses a process called lazy loading. This means that the singleton is in Stan. She hated just prior to first use on. Not when your application starts up. This can be useful when initializing the singleton is an expensive operation on. You want to delay it for as long as possible. The Singleton pattern offers a number off benefits over straight up construction off objects using the new keywords. First of all, it guarantees that there will always be only one instance off the Singleton and that everyone is sharing that single instance. This makes the singleton acts as a global variable that can pass data from one part of your application to another. The big advantage off Singleton's over regular global variables is that you can later change your minds on allow multiple instances. After all, you can even limit the number of instances to any number and use object pooling to share instances between clients. However, the singleton pattern is the most inappropriately used pattern in the world. Singleton's are intended to be used when a class must always have exactly one instance. But developers often use Singleton's in a misguided attempt to replace global variables. A singleton, for all intents and purposes, is a global variable on the question you must ask yourself is, Why on earth do you need a global variable in an object oriented design? Singleton's should only be considered if all three off the following criteria are satisfied . One there is not a single class in your entire code base. That could be the owner off the Singleton instance to you absolutely need lazy initialization. Sorry, there is no other way to provide global access to the singleton. If any off these criteria cannot be satisfied, then please do not use a singleton. Here is the UML diagram off the singleton pattern. As you can see, it's Hey really simple pattern. With only a single Singleton class, the class provides a static property getter called instance that returns the Singleton instance. The lazy initialization is his own in the instance property. The first time you access this property, the Singleton class will initialize the instance before returning it to you on any subsequent access. The initialized instance is returned right away. A common use case for Singleton's is to provide global access to system wide services like diagnostic logging. I am going to design a very simple locking Frei work on Expose it as a singleton. The three singleton criteria are fulfilled. I cannot identify any part off my code that could own the diagnostic longer. I need a lazy initialization toe open the log file and there is no other way to provide logging services to an entire application. I will implement the pattern with the following class, so let's look at the code. So here's my cold on. Here is the longer class. It's a simple longer with a constructor that opens the lock file. There's a public log methods to write a string to the lock file, and there's a finalize er to close the lock file. Note that the constructor off the longer class is protected, so you cannot create instances off the lower class with the new keywords you have to use the instance property. And speaking of which, here is the instance property. You can see that it is a static property getter that uses a private fields to store the single instance. If the instance field is no the property first instance, she hates the longer and then returns it if the field is not know the property returns. The instance right away Also notes that the lazy initialization codes is protected with the lock statements. These lock ensures that only a single thread can execute the code at any given time, so this small fragments of codes implements threat safe, lazy loading and ensures that the log file is opens only at the last possible moment. Finally, here is the main program message. You can see that I use the static instance property to access the longer. And then I use it to write three lines to the log file. Let me you run the program to prove that everything is working. I am compiling the cold. No. And now I am running the program. Okay, so the program has run without errors. The three lines have bean written to the long file. So now I will open a file browser and show you the bin slash debug folder where we will find the lock file on. Here it is. And you can see not the three log lines are there. Everything works. Here is a quick checklist you can use to implement the singleton pattern. First, make sure there is not a single class in your code base that can be the owner off the singleton Instance. Second, make sure you needs lazy initialization inserts. Make sure there is no alternative way to provide global access to the singleton. If these three criteria are provided for, you can proceed So next define a singleton class with a protected constructor and put any initialization colds there. Then on a Singleton Field member called instance, adds a static property getter calls instance and implements lazy initialization. Protect the lazy initialization with the lock statements. If you will have multiple threads accessing the singleton, that's finally change the calling colds to use the instance. Property toe access the singleton. And here are some final comments. Most importantly, please remember that Singleton's are just glorified global variables. You should seriously ask yourself why you need a global variable in an object oriented design because you're not supposed to actually need them. Codes with Singleton's everywhere is considered to be an anti pattern. There are a few valid use cases for Singleton's, for example, to provide global access to system wide services like diagnostic logging. You also sometimes see developers wrapping Web service proxies with Singleton's to ensure that only a single proxy gets constructed. The benefits off this are debatable, but its not necessarily about thing. Other valid use cases for Singleton's are facades on state objects, and you can also use Singleton's in combination with the abstract factory, the builder on the prototype design patterns. The advantage off a singleton over a global variable is that you are absolutely sure off the number off instances when you use Singleton's, namely one on and you can always change your mind later on. Increase the number of instances. But again, always remember that a singleton is a global variable and sink long and hard. Why you need a global variable in the first place. Okay, so here is a summary off what we have learned. The Singleton pattern provides an interface for ensuring that a class has only one instance , and it provides global access to that single instance. The pattern provides lazy initialization, which is useful if initializing the singleton is an expensive operation. The advantage off a singleton over a global variable is that you can increase the number of instances later should that be necessary. Singleton's are nothing more than fancy. Global variables aren't. They should be used very sparingly. 8. The adapter pattern: Okay, let's kick off this section with the first structural design pattern from the famous gang or four design patterns Book. This pattern is called adapter pattern, and it's a pattern you use when connecting two incompatible objects together. L starts with a quick summary off what we're trying to accomplish with this matter, so the adapter pattern is a good choice. When you are trying to accomplish the following, you are converting the interface off one class into another interface that your client expects. Adapters. Let's two classes work together that couldn't otherwise, because of incompatible interfaces. You want to wrap on existing class with a new interface, or you are trying to introduce on old legacy components into the system. Okay, let's go through the points one by one. The main issue here is that you haven't off the shelf components that offers compelling functionality that you want to introduce in your application. But unfortunately, the components has a non standard A P I that is completely incompatible with your application architecture, for example, you might be using data tables everywhere in your application to represents tabular data. You need the component to transform the data, but it can only read and write data using events, so the only way to hook this components into your architecture is by using an adapter, an object with a data table interface on one side, on and on event based interface on the other, the adaptor provides a kind off universal connector that hooks the two domains together. Another use case is when you are wrapping on existing class with a new interface. For example, you might have a class that contains a sequence of data, but that does not implement the I innumerable interface, so you will not be able to reiterate over each item in the sequence with the four each statements. To fix this, you can create an adapter that wraps the class, provides a public I innumerable interface on uses the native AP I off the class to implement the enumeration. Finally, you can use adopters when introducing legacy components into a new system. A classic example is when using com objects in the Net come stands for components object model, and it is a C plus plus based, object oriented platform develops by Microsoft. The Net framework contains a number off the doctor classes that make a common objects look and behave exactly like a dot net components so that you can use them inside C sharp applications. The adapter pattern offers a very important benefit and utters greatly improved cold reuse languages, platforms and AP Eyes change all the time and due to incompatibilities olds. But useful code is no longer in use today. 15 years ago, everybody was programming in C plus plus and come today see sharp on the dot net framework are the hot new game in town. On 15 years from now, we'll all be probably doing something different all over again. Adapters ensure that codes written decades ago can still be useful in modern applications. On a cold written today can still be useful in 15 years. The com slash .net adapter is a great example of these benefits. Because of this adapter, you can use decades old comb objects. Internet applications today, even though the com and dot net domains are utterly incompatible with each other, another benefits off the doctors is that you can reuse codes across different platforms. Components specifically designed for one platform can be reconfigured to happily inter operate with another platform. This prevents you from having to reinvent the wheel every time on rewrite the components from scratch. Okay, here is the UML diagram off the adapter pattern. In the terminology off this pattern, we have a client object on the left. Andi. It wants to make a request two and objects on the rights which we will call the add up T. Unfortunately, the client requires a specific interface which the add up T does not implement and therefore the two are unable to communicate with each other. To fix this problem, we are going to need an adapter that is both capable off communicating with the clients around the other tea. The pattern provides for this with an abstract based class on a concrete subclass. The targets class is the abstract based class. It's implements the required clients interface so it can be called by the clients. But it also sets up on abstract request methods which will call the Arab T and return the data. The adapter class is a concrete subclass that derives from target. It implements the abstracts request message on contains codes that directly calls into the adoptee class, gathers the data and then returns. It's in performance That's the clients understands. Let me show you an example off the adapter pattern, I will implement a programme that's displaced historic stock prices from popular tech companies like Apple, Microsoft's on Google. Now let's pretend that I have a very cool financial data base that contains the historic stock prices off many companies over a large range of years. But unfortunately, the database has a very specific interface. The stock prices are returned as a raise off decimal values, with each array item corresponding to the stock price in a particular month. Now, this doesn't help me, is all because my entire application is architected to use data tables for storing stock price history. I do not want to re fact or my codes to work with the Rays on. I also don't want to edit the financial data base, so that's the set up off my problem. I'm going to have to build an adapter to connect my application to the financial data base so I will implement the pattern with the following classes. Okay, let's take a look at the code. I'll start with the Add Up T, which is called stock history. DB. You can see that it has three methods for returning stock data. Get a couple gets MSFT, which is Microsoft's, and get GOOG, which stands for Google. These methods return 12 months off stock price history. For Apple, Microsoft and Google, the data is returns as a decimal array, with the most recent stock price as the first item. This doesn't help my application at all because it expects all stock data to be in the form off a data table. In fact, let's check out the targets class to discover exactly what interface the client will need. So here is the targets class called Stock History Targets, and you can see that it is an abstract class with a single method called get stock prices. The method expects a single string argument, which corresponds to the stock ticker symbol. It then returns a data table object with all 12 months off history. Let's take a look at the client's class to see how it deals with the data. The client is called stock up, and it has a method here called show stock history. The methods expects a single studying argument, which corresponds to the stock ticker symbol. It then declares a variable off type stock history target. Andi Initialize Is it with an instance off stock history adapter. The message then calls the targets to retrieve the data table off stock history and uses this loop to display the historic stock prices on the console. You can see not the data table. Contains dates in the first column and the corresponding stock prices in the second column . Okay, so the only missing piece off this puzzle is the adapter class. It needs to bind the array based interface off the stock history. Db Class with the data table based interface off the stock history targets class And here is the stock history. A doctor class where all the magic happens. The class is a subclass off stock history targets on its implements. The abstract get stock prices method. You can see that the method uses a simple switch statements to retrieve the correct stock history and then assembles the information into a new data table object and returns it. So this class is the actual adapter. It communicates with the clients by implementing the get stock prices message. Aunt returns a data table in the correct forms that the clients will understand, But internally, it's communicates with the stock history db class by calling one off the stock history methods, aunt retrieving the data as a decimal array. So this adapter effectively re maps the legacy interface into the new data table interface that the clients understands. And this allows the stock up class to communicate directly with the stock history Devi class. Okay. Finally, let me show you the main program message. The cold here simply creates a new stock up instance and then uses the clients to request the 12 months stop price history off the apple stock. It then displays the historic stock prices on the console. Okay, let me run the program to prove to you that everything is working. I'm compiling the cold now and now. Angle to run the program. Here we go. And there you have it. 12 months off. Historic apple stock prices. Everything works. Okay, Here is a quick checklist you can use to implement the adapter pattern. First identify all three actors in this pattern. The clients the out of tea and the adopter Then identify the interface that the clients requires on to put it in an abstract target class derive a concrete adapter class from the abstracts targets based class right the adopter coat to map the client interface to the adoptee interface on a place that cold in the doctor class. Modify the client to use the adapter every time it needs to access the Adam T. And here are some final comments in upcoming lectures were going to take a closer look at the bridge decorator facade and proxy design patterns. These are all patterns for connecting two or more objects together on the differences between adapter on these other four patterns can sometimes be a little confusing. So here are some simple rules of some to help you distinguish between these patterns. The doctors make things work after they are designed. The bridge. Next things work before they are designed adapters exposed on alternates. Existing interface to a client's a proxy exposes the same interface on a decorator exposes an enhanced interface. An adapter changes the interface. Often existing object a decorator enhances and objects without changing its interface. If Assad defines a new interface, whereas an adapter reuses an existing interface, okay, so here is a summary off what we've learned in his lecture, the adapter design pattern changes the interface, often existing object to make it compatible with another object. The pattern improves code reusability because it allows components from alternates or legacy platforms to be used in your application. A practical example is the comb adopter in the Dark Net framework. The adapter pattern is part of a group off patterns for connecting objects. Together, it shares the group with the bridge decorator facade ons. Proxy patterns. Each pattern connects objects together in a different way. 9. The bridge pattern: Here is the second structural design pattern from the gang off four design Pattern book. This one is called Bridge Pattern on. It is a pattern you use when you want to strictly separates an interface hierarchy from its implementation hierarchy. We'll start with a quick summary off what we are trying to accomplish with this pattern. The bridge pattern is a good choice when you are trying to accomplish the following, you need to combine two or more or to organo class hierarchies. You want to bind on implementation to a class at runtime, you need to clean up a proliferation off classes, resulting from a coupled interface with lots off implementations. You want to share on implementation among multiple objects. Let's go through these points. Okay, so the best way to explain how the bridge pattern works is through a concrete example. Let's imagine for a second that we're building a charting library. This is a library that can generate complex pie charts, bar charts, line graphs and so on. You're going to needs lines, circles on rectangles to draw these charts, so let's start building the shape object hierarchy. You will probably end up with something like this. These are some fundamental shapes that's makeup charts, but you also have to add on implementation. We are going to need some kinds off drawing interface to export the shapes to an SVG image so that we can display the shape on a webpage and maybe also another class to render the shape to an open GL graphics device. So now you're object hierarchy. Looks like this. You can see the problem here. Each implementation class appears in three places in the shape object rough. This leads to platform codes being spread out all over the autograph instead of being neatly contained. The problem here is that we are trying to shoe horn the implementation class hierarchy into the shape class hierarchy on these two have nothing in common on attempting to combine them only leads to a very large objects. Three. The solution is to completely separate the two objects hierarchies and use a special bridge to connect them. The modifieds objects hierarchy will then look like this. In this new design. The shape class acts as a bridge between the shapes on the drawing a p I. It holds a reference to an instance off draw a P I on defines on abstract high level drawing interface. The line square and rectangle classes inherit from shape on to implement the high level drawing interface by calling the low level drawing interface provided by the draw a p I class by initializing a shape with different AP I instances, you can make any shape draw itself on any A B I. The big benefits off the bridge pattern is that it reduces the number of classes. In the previous example, I needed 10 classes to draw my three shapes on two platforms, but with the bridge pattern, I've count the number of classes down to seven. The pattern also improves cold. Maintain ability. If you do know to use the pattern, you end up with implementation codes being spread out all over your class hierarchy. But with the pattern, all the implementation Cold lives in a single class within its own independent hurricane, which makes it much easier to maintain another benefits off. Having the implementation in a separate class is that you can initialize it at runtime. The platter allows you to define an interface at compile time, aunt specify the actual implementation at runtime and finally the pattern provides the freedom to make future changes with interface on implementation completely de couples. You can make changes to both without breaking the architecture. As long as the bridge between the two holes, everything will keep working. Okay, here is the UML diagram off the bridge pattern. The object hierarchies are on the left and right outside. Off this diagram on the left, we have the interface hierarchy with an abstract based class called abstraction. This class sets up on abstract, high level interface shown in the diagram as a single operation method, and it also holds a reference to an implement or instance there's a concrete's interface called Redefines Abstraction. This class derives from the obstruction based class and implements die level methods. It does this by calling the low level methods provided by the implementer instance, and on the right is the implementation hierarchy. The top level class is called implement or on. It implements some kind off abstracts, low level a P I. In the diagram. The FBI consists of a single message called Operation in. There are also two concrete's implementation classes called concrete implements or a on concrete implement, or be these two classes derive from the implement or based class and implements the low level interface. Now you can clearly see the bridge in this diagram. It is the reference to implement or held by the abstraction class to demonstrate the bridge pattern. I'm going to actually implement the example I talked about at the start of this lecture. So I am going to build a shorting library that uses the bridge pattern to separate an abstract shape hierarchy from on implementation hierarchy. I'm going to use the exact same classes I talked about earlier, so I will implement the pattern with the following classes. Okay, let's look at the code level. Starts with the shape class. You can see that it's an abstract class that sets up on abstracts interface with a single drawer method. This is my high level interface, a single message for the shape to draw itself. If we look at the class constructor, then you can see that you have to call it with an instance off draw a P I. The instance gets stored in this protected field here, which makes it available to stop classes. This reference is the bridge that connects the shape classes with the A P I classes Now before I move on to the concrete shape classes. Let's first take a look at the A P I classes. Here is the draw a p I class and you can see that it is an abstract class that sets up a single abstract draw line method. And here are two concrete AP I classes S p g a p I arms open G l a p I. Each class inherits from draw a p I on implements the drawer line method. You can see here that I am out putting the actual SPG and open GL commands to draw a line. This is where you would put the actual implementation calls to draw a line. OK, now let's look at the concrete's shape classes line square and rex angle. Each class inherits from shape on implements The draw method. You can see in the line class that the implementation simply uses the draw a p. I instance to draw a single line. But now let's take a look at the square class. It also implements the draw method, but it makes four AP I calls to draw the four line segments not makeup square. Note that the square class has no idea how to draw itself as a bit map or SVG image. And conversely, the draw a P I classes have no idea what a square is. The two objects hierarchies are completely independence. Okay, finally, here is the main program message. You can see that it's declares a shape variable. Instance. Shayes. It's with a line instance, and initialize is It's with the open G L drawing a P I. It then asks the shape to draw itself. And then here is the same cold all over again. But now it's a rectangle being initialized with an SPG drawing a p. I let me run the program so we can see what's happening. I am compiling the codes. No, um, I'm running the program. No. And there you go. One line drawn with open GL vertex commands and one rectangle drawn with SVG commands. Everything works. Okay. Here is a quick checklist you can use to implement the bridge pattern. First identify two or more or tagen, all class hierarchies in your application. The separation could be along the line off abstraction versus platform or domain versus infrastructure or front and versus back End four interface versus implementation, then design an abstract, client oriented interface that defines what the client wants and then design an abstract, platform oriented interface that defines what the platform provides. The platform interface should be minimal, necessary and sufficient. Add derived specialization classes for each concrete abstraction on a map, the client interface to the platform interface and finally add derived classes for each concrete's platform. Here are some final comments There are some similarities between the adapter and bridge patterns. Both map one object interface to another. However, the two patterns differ in how and when they are implemented on adapter makes things work after they're designed, the bridge makes them work before they are designed. The bridge is designed upfront to lets the obstruction on the implementation very independently. On adapter is re tro fitted to make unrelated classes work together, and finally, you sometimes see the abstract factory pattern appear together with the bridge pattern. This is useful if the abstraction class needs to delegate the creation off the implementation class. For example, if the type off implementation depends on external factors that they're only known at runtime. In their case, you can use the abstract factory pattern to create the implementation objects. Okay, here is a summary off what we've learned in this lecture. The bridge pattern lets you combine two or more. What's organ All class hierarchies. The pattern reduces the number of classes in your code and concentrates all implementation cold in its own class hierarchy. The pattern provides the freedom to make changes to interface on implementation without breaking the architecture. You can provide the implementation at runtime by using on abstract factory to create the implementation objects. The pattern is similar to the adapter pattern, but it is intended for decoupling instead of adapting. 10. The composite pattern: and here is the third structural design pattern from the gang or four design pattern book. This one is called composite Pattern, and it is a pattern you use when you're creating a three structure off components that's can contain child's components. I'll start with a quick summary off what we're trying to accomplish with this pattern. The composite pattern is a good choice when you are trying to accomplish the following. You need a three structure to represent a part hierarchy. You want to compose objects out off one or more child objects. You want clients to treats individual objects. Ons, compositions off objects in exactly the same way. Let's go through these points. So in this pattern you are working with objects, which, in the terminology off this pattern I calls components on The key issue here is that some components actually contain one or more child's components on. These child components can also contain child components of us, forming a three off components. We have a special name for components with or without child components. Any components with at least one child components is called a composite on any components with zero Children is called belief. The nice thing about this pattern is that it lets you treats composites ons leaves in exactly the same way. Clients will only interact with the components interface, which offers no information if given components, as Children were not. This fact is irrelevant to the clients. The composite pattern offers a number off benefits. First of all, the pattern lets you set up a hierarchy off components. You use the pattern to declare components that can contain components that can contain components. This is perfect for three like data structures like folder hierarchies, organizational charts, tables of contents and so one. But the pattern offers another advantage. The calling coats doesn't need to know which components have Children and which do not. All clients only interact with the components interface Aunt are completely unaware if they're dealing with a composites or relief object. This effectively hides the complexity off the data structure from the outside world. The composite pattern is ideal if you are applying a sequence off operations on a three like data structure. Andi, your calling coat doesn't care if the operation gets applied to a composites or relief objects. Here is the UML diagram off the compass, its pattern at the top off the diagram is the abstracts components class. It declares a very simple interface, which consists off a single message called Do This. Both the leaf on the composite class will implement these methods in their own way. On the left is the leaf class. It's represents a component without any child components. As a result, there is no need to implement additional methods for handling child objects. Instant. All the leaf class does is implement the single do this method on the rights is the composite class, which represents a component with one or more child components. As a result, the class has some extra members for managing child components. First of all, there is a protected Fields member called Elements, which contains a list off all child's components. There are also extra members for managing the collection off child objects in the diagram. One off these members is shown the ads elements methods. Finally, the class also implements that do this method. Burt's contrary to the leaf class. The composite class applies the methods to both itself and all child objects, a simple for each loop. It's a raise over all elements and calls the do this method on each child components, and this is the fundamental difference between a leaf on a compass. Its object. A leaf will only apply the operation to itself, whereas a compass it will apply the operation to itself and all of its Children. Two demonstrates the compass, its design pattern. I will show you an example. I am going to creates a simple class library for rendering on HTML webpage. I will implements classes for each HTML tag that's I'll use. In my example, I will implement the tags as either leaves or composites, depending on if the tag is allowed to have nested content for North, my components interface will have only one single message, called surrender. This method returns the components in its HTML representation. The render methods in a composite automatically calls the render methods off any child objects to render the entire HTML sub tree in a single goal. I will implement the pattern with the following classes. Okay, let's take a look at the cold. I will start with the HTML node class. You can see that it's a simple abstract class that sets up a abstract surrender method. All sub classes off HTML note will override this message to render themselves in the correct manner. The first, so class will look at is the leaf note. This represents a leaf note in an HTML documents. So a note that does not have nested child notes. You can see that there are no new members introduced here. The leaf note is simply an empty subclass off html note, with no additional methods or fields. And here is the text class, the first non abstract sockless off HTML. Note. This class represents a fragment of text in an HTML documents. So here is a protected string fields for holding the text. Um, here is a constructor for initializing the text fields. The render methods simply returns the contents off the text field. The class does not have child components, so there's nothing more to render. Okay, now let's move on to the Composites branch off the object hierarchy. All starts with the HTML tag class, which sets up on abstract interface for composites. You can see here that's on HTML. Tag is an abstract subclass off the HTML knows class aunt. It introduces several new members. First of all, there's a tag name field here that holds the HTML tank name to render. And here is a generic list off HTML nodes called elements that's contains the collection Off Child's components also notes that this method here, called Ad Child, lets you adds a new child components to the collection. On Here is a protected constructor that lets you initialize. The tag name on here isn't Orender methods. The methods not only renders itself but also all of its Children. This coat starts with an opening tug, then collects all outputs from the child components and then adds closing tag to complete the HTML fragment. And here are the concrete, so classes off html tag. They are the HTML body and P class, and each class corresponds to the HTML tag off the same name. These Sir classes simply provides a public parameter less constructor. That initialize is the tag name. Okay, I'll conclude with the main program message. The cold here sets up a simple HTML documents consisting off a nested HTML body and paragraph tug, and finally it adds a nested text elements inside the paragraph. Then the code calls the Rendall message on the outermost HTML element, which will render the entire documents, including all Children. Let me run the program to prove to you that everything is working. I am compiling the coast. No ons. Now I'm going to run it. Here we go and there you have it. A very simple HTML documents consisting often outer HTML elements, a nested body, elements in estates, paragraph elements and finally, some text. Everything works okay. Here is a quick checklist you can use to implements the composite pattern. First identify all composite objects in your application that are composed off nested child's components, then creates on abstract component based class that contains the lowest common denominator interface. The interface should only contain the A P I that needs to be applied uniformly across all objects. Then add a derived leaf class and adds any leaf management's methods to this class. Add a derived compasses class and add child management's methods to this class. Then implement the components a P I for the leaf and composite classes, and you can add as many sub classes off leaf and complicit as you need. And here are some final comments. The most important facts you need to realize about this pattern is that it completely hides the fact that a component can contain child components. The differentiation off components into leaves and composites is completely invisible to the outside world. This is not a problem if the outside world only needs access to the components, a P I. The sub classes can decide how to implement the A P I without having to expose any kind off child's management interface to the outside world. However, sometimes you might needs to iterated over each components in the hierarchy with a pure, compensates person. This is impossible because information about the hierarchy is only contained in the composite objects as notes in the components or the leaves. The only way to make this work is by adding a separate visitor or in normal rate of pattern . You sometimes see developers moving all child's management's codes into the components class to avoid this problem. This provides instance in admiration and visitor support directly have the component level . If you do this, please keep in mind that this actually weakens the composite pattern because now the leaf class will also inherit the complete child's management. A p I on that coat doesn't make any sense in the leaf class. Okay, so here's a summary off what we have learned. The compass is pattern is a good choice when you want to compose objects out off one or more child's objects. The pattern treats individual on composite objects in exactly the same way. The pattern is ideal if you are applying operations to a tree. Data structure on the calling coat doesn't care if the operations are applied to a composite or relief objects. Complicit objects can be inaugurated with in normal razor or visitor pattern. Some people puts the child's management a P I in the components class. This provides instant in admiration support at all levels, but it also makes the pattern more brittle. 11. The decorator pattern: here is the fourth structural design pattern. This one is called decorator pattern Andi. It is a pattern you use when you want to extend the functionality off a class, but without actually creating a subclass, I'll start with a quick summary off what we're trying to accomplish with this pattern. The decorator pattern is a good choice when you are trying to accomplish the following, you want to attach additional functionality toe one object dynamically. You are unable to use subclass ing for extending the functionality. Okay, let's go through the points, so the key here is that you want to extend. The functionality often object, but for some reason or other, you are unable to use soft classing. So how would you do this? The solution is very similar to the composite pattern that we discussed in the previous lecture. We learned that in the compass, its pattern a component consists off a nested three structure off child's components. Calling a message at the roots off the tree automatically calls all child's message to. In the example, I showed you how you can use this pattern to represent on HTML documents with nested tags. Andi, right, a render methods that produces the correct ALPA's. Now the decorator pattern is very similar again. We have a nested structure off child objects, but now the original objects is at the root off the tree. Under the child, objects are called decorator objects. The original objects on the decorators all share the same interface. Each message first calls its parents, which may either be another decorator or the original objects. And then it performs additional functionality. By stacking objects in this manner, you can effectively add any kind of behavior to any objects. Please note that this pattern allows for extra functionality to be added to a method, but you cannot add extra methods to an object each decorator shares. The exact same interface with the original objects also notes that the original objects is now hidden beneath layers off decorator objects. Trying to access the original objects directly is no longer possible. The decorator pattern offers a number of benefits. First of all, the pattern allows you to enhance the functionality off a message in any objects without having to use self classing. This can be useful if you are unable to subclass the object, or when the message in question is not virtual. The nice thing about decorators is that they sidestep the multiple inheritance limitation in C sharp. Due to this limitation, you cannot inherit functionality from two or more based classes. A class can only ever have one super class, but you can easily apply to or more decorators to an object. So in effect, decorators kind off acts like interfaces with a default implementation. Finally, the pattern hides the original objects beneath layers of decorators. This can be useful if your client will only call high level methods on. You want to hide the complexity off the decorators from view? Here is the UML diagram off the decorator pattern At the top off the class hierarchy is the components class. This is an abstract based class that defines the common interface for the original objects on and all decorators. In the diagram, the class has one single abstracts message called Operation. There are two subclass is derived from the components based class one is called concrete components, and this is our original objects. This object contains the default functionality that we want to extend with decorators, and so this class provides the default implementation for the operation methods. The other subclass off the components based class is called decorator. This is an abstract class that acts as the base class for all decorators. Now notice that this class has a protected field that holds a reference to another components. You initialize the decorator by calling its constructor on providing the reference components as an argument. The class also implements the operation methods by having it simply call the same operation message. In the reference components, there are two. Subclass is derived from decorator, concrete decorator, A and concrete decorator. Be notice how they introduce extra functionality to the components. Concrete decorator A. Ads on into an Allstate on concrete decorator be adds new behavior to the operation methods . So here's what you do to put this pattern to work. You initialize a stack off decorators like this calling the Operation Message will first call the operation message off concrete Decorator A, which will immediately delegate the call to Concrete Decorator Be, which will again immediately delegates the call to concrete components. The concrete components will perform the default implementation, and then concrete decorator be gets a chance to perform additional work. And finally, concrete decorator, a also gets a chance to perform additional work. I am going to demonstrate the decorator pattern with the following example. I am going to write software for a pizza restaurant in a pizza restaurants. You always have a selection off standard pizzas. Margarita Quadros, a Joni Fungi Answer one. But you can also combine the pizza with extra toppings. You can ask hum salami, extra cheese, mushrooms, peppers and so on. Now, to incorporate all of this in a single class hierarchy would be very difficult, because each topping can be combined with each Peter. I would have to add sub classes for every combination off pizza topping and an impossible task. So this is a perfect job for the decorator pattern. Instead, off trying to put everything into a single class hierarchy, I am instead going through implements the pizza as components on the toppings. As decorators, I will have an abstract component class called pizza Elements that's implements a uniformed A P I across all pizzas and toppings. I will also use the methods called get price to calculate the price off the finished products. This message will be implemented in all objects so that I can simply call get price on the final stack off decorators and components to get the price off the finished pizza. There's also a concrete's components, cools pizza that defines one off these standards pizzas, and there are separate decorator classes for each topping. Each decorator modifies the get price methods to add its surcharge to the price. So here are the classes. Implement the pattern with Let's take a look at the code. Here is the components based class called pizza Elements. You can see that it is an abstract class with a single abstract methods called Gets Price, which returns the price off the pizza as a decimal value. So this method is going to be implemented in all pizzas on all topping classes. Next are the concrete's components. Take, for example, the margarita class. It's implements the pattern for a standard margherita pizza, and you can see that the pizza costs $8. And here is the funky pizza, which is slightly more expensive at $10. And here is the pizza topping class, which acts as the base class for all decorators. In this example, you can see the components reference here. Implement it as a protected fields the class constructor initialize is the fields with this arguments here. So when you create a decorator, you always have to specify the parents object the pizza topping class implements to get price message on. You can see here that it simply calls the get price message off the referenced components and returns that value. There is no additional functionality here that will come in the concrete decorator classes , and here is a concrete decorator. The with extra hum class is a subclass off pizza. Topping on overrides the guest price message. You can see that it calls the base implementation and then simply adds $1.50 to the price. This is the price off having extra ham on your pizza, and here is the with extra cheese class, and you can see that cheese is cheaper than him. Only $1 Okay, finally, let's look at the main program message. The cold here uses a sequence off nested calls to set up a margherita pizza with extra ham on display. The price the next code fragments sets up a fungi pizza with extra hum hands, cheese and also displays the price. Let me run the program to find out what these pizzas will cost. I'm compiling colds now and now I'm going to run it. Here we go and there's your answer. A Margherita pizza with extra home costs $9.50 on a funky with extra ham and cheese costs $12.50. Everything works. Here is a quick check lists you can use to implement the decorator pattern. First, make sure you needs to add functionality to an existing class on that you cannot subclass that class and that there is an interface that is common to all, then creates on abstract class with the lowest common denominator components interface. Derive the existing class from the components based class creates on abstract decorator class that also derives from the components based class. Then define decorators for each additional piece off functionality and finally have the clients define the type and ordering off the components on decorator objects. Here are some final comments I have already mentioned the similarity between the composites and decorator patterns. In fact, you can view the decorator pattern as a composite with a single child. At each level, however, a decorator is intended for adding additional functionality. It is not meant for objects aggregation. Both the decorator and complicit patterns have different but complementary, intense. Consequently, you can actually combine the patterns, and in practice you do often see the complicit on decorator patterns together. Finally, remember the difference between the adapter proxy on decorator patterns. An adaptor provides a different interface to which subjects the proxy provides the same interface, and a decorator provides on enhanced interface. Okay, here is a summary off all that we've learned in this lecture. The decorator pattern is a good choice when you want to attach additional functionality to one object dynamically, and you are unable to subclass the objects. The pattern treats components on decorators in exactly the same way. The pattern is ideal. If you want to apply layers off enhancements to an object operation, you can combine the composites on decorator patterns. 12. The facade pattern: Here is the fifth structural design pattern from the gang Off four book. This one is called facades. Pattern on. It is a pattern you use when you need a simplified, high level interface to the functionality off a complex, low level subsystem. Loyal starts with a quick summary off what we're trying to accomplish with this pattern. The facades pattern is a good choice when you are trying to accomplish the following. You want to provides a unified high level interface to a sets off low level interfaces in a subsystem. You want to make the subsystem easier to use. You want to wrap a complicated sub system with a simpler interface. Let's go through the points. The key points here is that you have a complex subsystem somewhere in your application architecture. This subsystem will consist off many low level components on Did you interact with the subsystem through a large number off complex AP eyes? This kind of subsistence offers on enormous amounts of power and flexibility, but it can also be very hard to use. You'll need detailed upfront knowledge about the architecture off the subsystem to be able to use it efficiently. So what do you do if you have to expose the subsistence. To a large group of developers, the steep learning curve off the subsystem will be a major impediments to adoption ons. There's a big risk that some people will use the A P I incorrectly on introduced bugs into the system. The facade pattern solves this problem. It encapsulates the subsistence within a single interface objects. This object provides a high level interface to a narrow domain off the subsystem. So instead of having to make a sequence off complex AP I calls, developers can now simply call the high level facade interface. The facades will then make a worthy, correct low level calls into the subsystem to get the work done. The facades pattern offers a number of benefits. By using a facades, you dramatically reduce the learning curve. To successfully interact with the subsystem. Developers are no longer required to master the entire low level a P I. Instead, they only have to familiarise themselves with the high level facade interface before they can get started. This will significantly speed up the adoption off the subsystem. The pattern also promotes the decoupling off the subsystem from its many clients The high level interface effectively masks the details off the low level subsistence a p I, which means that you could make sweeping changes to the subsystem without having to worry that the client coats will break. However, the facades pattern also has a number of risks. The biggest risk is when the facades is the only access point to the subsystem. Remember that, I said at the start off this lecture that the subsystem AP I offers on enormous amounts of power and flexibility. All this flexibility is gone if clients are forced to use the facades to gain access to the subsystem. But exposing the subsistence to clients is also not risk free on exposed subsystem removes the decoupling between the clients on the subsystem, which means that your freedom to change the subsistence a p I is significantly reduced. And finally, a facades can quickly turn into an anti pattern. If the subsystem covers, say, more than 90% off your application architecture, then the facades effectively becomes a god object. This is an all knowing and all seeing master objects that controls every aspect of your application. This is an anti pattern because it's completely removes all off the flexibility and power that you get from an object oriented language. Almost all of your business logic is now in a single object. This is universally recognized as a very bad idea. Here is the UML diagram off the facades pattern. As you can see, the diagram is very simple. We have a complex subsystem consisting off many components with low level AP ice at the bottom off the diagram and above these subsystem is the single facade class that wraps this subsystem and provides a high level interface to its clients. The facade is a single object instance, and therefore it is often implemented as a singleton or a static class. Let me show you an example off the facade pattern. I am going to write the simple program for a bank to set up a mutual fund. Mutual funds are investment products where every month your bank deducts money from your bank accounts to buy a certain number of shares on the stock market. My application architecture has a subsystem for interacting with bank accounts and stock portfolios. The subsystem provides a low level interface for buying and selling stocks, getting current stock prices, making a withdrawal or deposit on the bank accounts and performing a credit check on a given customer every month. The bank has to perform the following process for each mutual funds. First, get the current share price off the stock, then check if the bank accounts has sufficient credits to buy the shares. Then withdraw the required amounts from the bank accounts. That's finally use this money to buy shares. I am going to wrap this process in a single message off a facades. Objects. I will implement the pattern with the following classes. Okay, let's take a look at the code. Here is a class called bank accounts, which will act as of the abstract based class for any concrete implementation off the bank accounts. The class defines the abstract methods deposits, withdrawal sounds, gets balance for, respectively, depositing money, withdrawing money and checking the balance off the account. And here is a concrete subclass of bank accounts called cash accounts that implements all the abstracts methods in the bank accounts class. There's also a class called equity, which acts as the abstracts based class for any concrete implementation, often investment products. The class defines the abstract methods buy stock sell stock and gets price for, respectively. Buying stocks. Selling stocks. Aunt checking the current share price. There is one concrete subclass off equity called stock, which represents a stock that you can buy or sell on the stock market. The class implements all the abstracts methods in the equity class to automatically create the rights kind of equity, I added. On Equity Factory here, the equity factory follows the singleton pattern to return only a single instance off the factory, and it has this method here. Two creates new equity objects. As you can see, the current implementation can only create stock objects, but you could easily enhance this to also supports index funds, real estate funds and other financial products. And finally, we have the mutual funds class here, which acts as the facades to the banking subsystem. The class provides a simple by method that implements the entire mutual funds process. I only need to provide accounts number when creating the objects on to take a symbol and the number of shares. When calling the by message all the details off, accessing the bank accounts, creating the right kind of stock, checking the balance and so one is done internally in this class, so the mutual funds class effectively acts as a facade and shields the implementation details off of these stocks on bank accounts. Sub system from the outside world. Finally, here is the main program message. It uses the mutual funds facade class to buy 10 shares off Apple. Using a cash accounts. Let me run the program to prove that everything is working correctly. I am compiling the cold now, and I'm going to run the colds now. Here we go. There you go. I now own 10 shares of Apple stock. Everything is working. Here is a quick checklist you can use to implement the facades pattern. First, identify a complex subsystem in your application architecture that you want to simplify. Then design a simple, unified interface for the subsystem creates a facade class with the simple, unified interface. Have the facades call the appropriate low level methods off the subsystem to implement The interface has finally modified the clients to always use the facades, and here are some final comments. The adapter on facade patterns are very similar. Both patterns make changes to an existing interface, but the difference is in the intense off the pattern on adapter changes a legacy interface to make components compatible with your application architecture, whereas a facades wraps a low level subsystem interface with a high level interface to reduce the learning curve off the subsystem. So the difference is in the intent making something compatible Verses reducing a learning curve. Another difference is in insane she ation. A facades is often a singleton because it wraps one subsystem, but adapters are usually in Stan Shih ated for every component they wrap. And finally, consider this scenario. You have a subsystem for creating sets off related objects. Does that remind you or something? Exactly. The abstract factory you can view on abstract factory as a kind of facades for objects creation. So in this scenario, you could also use the abstract factory pattern instead off the facade pattern. Okay, let me concludes with a summary off what we have learns in this lecture. The facade pattern provides a unified high level interface to a complex low level subsystem to make these subsistence easier to use. The pattern promotes the decoupling off the subsystem from its clients, but denying clients access to the low level interface also reduces power and flexibility. Facades can evolve into a common anti pattern called a god object. Adopters and facades differ in their intense adapter makes Negus e components compatible. Whereas a facades reduces the learning curve of a complex subsystem. Facades are often Singleton's on. You can sometimes use an abstract factory in place off a facade. 13. The flyweight pattern: here is the six structural design pattern. This one is called flyweight pattern, and it's a pattern you use when you want to share objects Instances across a very large data structure. We'll start with a quick summary off what we're trying to accomplish with this pattern. The flyways pattern is a good choice when you're trying to accomplish the following. You want to support a very large number off fine grains objects efficiently. The state information off each object can be retrieved on the mound. Okay, let's elaborate on this. So let's say I haven't application where I use the composites design pattern to organize my data in a tree structure. The composite pattern organizes components into leaf objects, which cannot have Children ons, composites, objects which do have Children. The leaves are at the edge off the three structure and the compass. It's make up the intermediate levels. I have a super fast Reedus database, which contains millions of strings. On. My goal is to build the composites three structure by reading the database, hands copying each string into a unique leaf instance in the tree. Now here's the problem. If I create one unique objects instance for each name. Then I will end up with millions off leaf object. Instances in memory on this is redundant because the names are already available in the reader's database. The flyways pattern is the solution to this problem. The pattern performs a remarkable trick. It creates one single leaf instance and shares its millions of times in the tree. Every composites in the tree ends up referencing the same leaf objects. Here's how it works. The first thing you have to do is examine the internal states off the leaf object. Andi split it into intrinsic states, which can be shared with others on, um, extrinsic states, which cannot be shared in my tree. Example. Each leaf has a unique name, so I only have extrinsic states which cannot be shared. The next step is to re engineer the client codes to always supply the extrinsic state. So every time my codes accesses a leaf, objects, it's must first look up the name in the database and then provides this name to any message . Call in the leaf objects on The last step is to introduce a leaf objects factory the client calls calls this factory every time it needs to create a new leaf instance. But the factory always returns the same leaf instance for each unique intrinsic states. Since my example has no intrinsic states, my factory will always return the same leaf instance. So you end up with a tree where every leaf note is the same object instance, and this works perfectly because the clients will always supply the name off the leaf. For each operation, the flyweight pattern offers a number of benefits. First of all, the pattern allows you to create a huge number off virtual objects without having to explicitly in Stan. She hates every single one of them. This lets you build a detailed data structure like a three or a graph, without having to instance she ate each note. This will save a lot of memory. If your data structure is very large, the pattern can help you not only reduce the memory footprints but also speed up your codes . If in Stan Shih ating objects isn't expensive operation, then the flyways pattern will help you by recycling the same instance for each unique intrinsic states. This will reduce the number of times that the object constructor needs to be called as finally, the pattern simplifies your codes. Traversing a data structure where some notes are in Stan Shih ated on others or not, is a complex operation. But the flyways pattern hides this fact from the clients so the clients codes can in Emma rates a large data structure off virtual objects without having to worry which ones are instance created on which ones or not. You can create very elegance codes by combining the flyways pattern with the Anoma Reiter or visitor pattern. This lets you efficiently in operates a very large data structure. Okay, here is the UML diagram office, the flyways pattern. The pattern uses an abstract based class called flyways. This class has a single message called Operation On. You can see that it expects the extrinsic states as an argument. The clients always has to provide the extrinsic states for each flyweight objects. There are two concrete sub classes off the flyways based class. The 1st 1 on the rights is called concrete flyways, and this is the actual flyways objects you can see in the diagram that it's implements the operation and that it also has a field called intrinsic states. This is the intrinsic states off the objects that can be shared with others. When you call the operation, the class combines the internal intrinsic states with the explicitly provided extrinsic states. These two combine into the full states off the objects on the message can use this states to perform useful work. When this pattern is running, you will have one concrete flyweight instance for each unique intrinsic stays. The other subclass off the flyways based class is on the left on his calls unshared concrete flyways. This is a special case on your implementation. Might not need this object because this flyweight will never be shared with anyone. You might have some kind off edge case scenario in your application architecture where you always want to create new instances off a flyways, regardless off the intrinsic states. The unshared concrete flyweight class is intended for this very purpose. And finally there's a flyweight factory. The factory has a factory message called Gets flyways, which expects a key put on it. This key uniquely identifies each intrinsic states. The factory uses a dictionary to return the concrete's flyweight instance Associate it with the specifies intrinsic states. You can add codes to the factory that recognizes edge cases and always returns a new unshared concrete flyweight instance for these cases. But again, this is optional. The clients in Stan she It's a flyweight factory on every time it needs a new object it calls the gets flyways message. The factory uses its internal logic to either return a shared flyways or on unshared flyways. But the client's doesn't care. It simply uses the objects, calls the operation and provides the extrinsic state. I am going to use the flyways patter toe implements, image loading codes for the Web browser. A typical webpage contains a lot of images, but sometimes the same image appears in multiple places. It would be wasteful to re lows the same image every time. So I am going to use flyweight objects to loads each image only ones. So the first thing I need to do is examined. The state's off the image. What state information do I have? Aunt? Is this intrinsic or extrinsic states? The image file name is intrinsic. The image position is extrinsic on the image. Size is also extrinsic. The client is going to specify all off the extra in six days, so I only need to store the intrinsic states. I am going to needs an image class that derives from fly weights. Aunt contains a file name, member aunts, A display method. I will not use unshared flyways in this example, so I don't have to implement the unshared concrete flyways class. So that leaves me with the following classes. Let's take a look at the codes. I will start with the base image class, which acts as the flyweight based class. In this pattern, you can see that it sets up on abstract message called display and that the display message expects arguments for the position and size off the image. This is the extrinsic states of the image, and it will always be provided by the clients. Next up is this concrete flyweight class called Image. The image class derives from base image and has a protected Stringfield called image file. Name on. This is the intrinsic states off the image and it is stored inside the objects. You can see that there's a constructor here for initializing the image with the full name. Okay, so now the display message has access to the full states. The intrinsic states is stored in the fields on the extrinsic states is provided in the method arguments. So now all the method has to do is combined this data on to do something useful with it. You can see from this code here that's the methods simply generates on HTML image tag with all the information, Andi writes it to the console. If this were a real Web browser, you could have the image class actually load the image into a bismuth onda render. It's on the screen every time the clients calls the display method. Next up is the image factory. It uses the factory method pattern to set up a factory for generating image instances. I used the image file name as a key. I look the image up in a dictionary, and I return it. If the image doesn't exist, then I explicitly in Stan. She ate it, added to the dictionary and then return it. You can see that I added some extract console right line commands so we can check that the factory is actually working correctly. And finally, here is the Web Page Render Class, which acts as the clients. It's instance, creates an image factory and then uses it to Winston. She ate the same image three times, but each time with a difference. Position and size. I'll concludes with the main program class, the main program message simply in Stan Shih eight's a Web page render aunt asks. It's to render itself. That should outputs all three image tags. Let me run the program to prove that everything is working. I'm compiling the coast. No hands, no, I'm running the program. Here we go and there you go. The program created one single image instance on. Then it's reused in that instance, twice for the other two images. But despite that, each display method call combines the intrinsic and extrinsic state to produce the correct our course. Everything works. Okay, here is a quick checklist you can use to implement the flyweight pattern. First, make sure you need to support a very large number off fine grains objects efficiently and that the extrinsic state information off each objects can be retrieved quickly and on the mound. Then split the object states into shareable intrinsic states non shareable extra in six states. Remove the extrinsic state from the object and add it to the calling argument lists off all effective methods, create a factory that can cash and reuse existing class instances. Change the clients to use the factory to request objects. That's finally change the clients to look up all extrinsic states and provide that information toe all affected methods. And here are some final comments. The key thing to remember with the flyways pattern is that it requires you to look up the extrinsic states on demand, so you need to have this data available in some kind off fast medium. If it's on external database, that's perfectly fine. But make sure the database has fast read access. The reason for this is that you need the extrinsic states every time you use the flyways objects. If there is a performance hits when accessing extrinsic states, then you will experience this hits every time you call any message on the flyweight objects , so make sure you have fast access to this data. You often see the flyways pattern combines with the compasses pattern because it's an excellent way to minimize the number off leaf object instances in memory. If the leaf notes off a complicit data structure, have a simple states that you can quickly look up on demand. Then you will get a big improvements in memory footprints by combining these two patterns. Okay, let me conclude by summarizing what we have learned in this lecture, the flyways pattern allows you to support a very large number of fine grains objects efficiently. Requirements for the pattern is that the state information off each object can be retrieved quickly on demand. The pattern reduces the number off flyways object instances in memory by sharing them among clients. To use the pattern you need to split object states into a shareable. Intrinsic states on a non shareable extrinsic states. The flyways patter is often combines with the complicit pattern to reduce the number off leaf object instances in memory. 14. The proxy pattern: and here is the final seventh structural design pattern. This one is called proxy pattern Andi. It is a pattern you use when you want to provide a placeholder for another object. L starts with a quick summary off what we are trying to accomplish with this pattern. The proxy pattern is a good choice. When you are trying to accomplish the following, you want to provides a surrogates or placeholder for another object. Let's elaborate on that. A little a proxy is nothing more than a stand in for another object. Clients do not call the underlying objects. Instead, they called the proxy on the proxy forwards those calls to the underlying objects. So why would you want to do anything like that? Well, there are a number off scenarios where a proxy is really useful. For starters, consider remote procedure calls. A remote procedure call is a call to an object that lives in another application domain, or perhaps even on another server. To make a cool to another server, you'll need to serialize all method arguments into a data packet, sends that data packets over the network to the target server wait for a return value D c realized the value. Andi, return it to the caller a proxy Objects hides all that complexity from view. You simply call the desire to message off the proxy class, which will then take care off all serializing sending, receiving on the serializing. The clients never realizes that it's communicating with an object on another server. We call these kind of proxies remotes, proxies. You can also use proxies to delay the instant station off objects that are very expensive to create the proxy acts as a stand in for the objects, and cash is as much information as possible at the very last moment before the object is actually needed. The proxy creates its with the cash data. We call these kind of process virtual proxies, and finally, you might have an object that may only be accessed in a specific manner, for example, by certain user accounts or at a specific time off the day you can use a proxy to wrap the objects on implements access checks in the proxy. Only when everything checks out will the proxy call the real object. We call these kinds of proxies protection proxies. The proxy pattern offers a lot of benefits. Remote proxies let you make method calls to objects that live in entirely different application domains or servers. The proxy acts as a stand in for the remote objects. Aunt hides the complexity off, making cross domain or cross server method calls from the outside world. Virtual proxies allow you to instance she hates expensive objects at the last possible moment. This will improve the start of time off your application, and finally, protection proxies lets you wrap access control codes around a pre existing objects. Here is the UML diagram off the proxy pattern in the terminology off this pattern, the objects getting proxies is called the subject. There's an abstracted based class called subjects that acts as the routes off the object hierarchy. Andi. It sets up the proxy interface in the diagram. The interface consists off a single message called Request the Real Objects. So the object getting proxies is on the left, and it's called the real subject. It's so classes the subject days class on implements do request methods. The proxy class Utley names Proxy is on the right. It is also derived from subjects which ensures that both of the proxy on the real object share the same interface. The proxy also implements the request methods, but it does so by storing a reference to the real objects in a field calls real subject. The proxy then uses that reference to call the request message off the real objects. The implementation off the method depends on the type of proxy. A remote proxy will have a lot of codes to open a network connection. Access to remote object, etcetera. A virtual proxy will use lazy loading. Two instance She ate the real objects as late as possible on the protection proxy will have access control checks. But all of this is completely hidden from the clients, which simply declares a variable off type subjects and then initialize is it with an instance off the proxy to the clients? There is no difference between the proxy on the real object because they share the exact same interface. I am going to use the proxy pattern to implements a rate limiter on a service. A p I rates. Limiters are very common in Internet services like the Twitter or Facebook, a p I. They limit the number of calls you can make for seconds to prevent the server FBI from getting flooded with calls. Usually, the limits is a few hundreds or 1000 calls per day or a maximum number of calls For seconds . I am going to create a very simple A P I that calculates the current value off one Bitcoin . Now that's actually very easy to do. There is a public Jason Web service as the u R l coin able dot com slash ap i dollars ph b This service will return the current value of one Bitcoin in U. S dollars. My FBI simply calls this public service parses the Jason results. Andi returns. It's as a decimal value to prevent my library from flooding the public service AP I with calls, I am going to add a rate limiter to my coat that restricts the number of calls to one per second. Then I'll adds a bad clients that floods the FBI with 10 calls for seconds to see if the rate limited works. I will implement the proxy pattern with the following classes. Okay, let's take a look at the code. I will start with the coin AP I class. You can see here that it is an abstract based class that sets up abstract methods. Calls get value in USD This method returns the value off one Bitcoin in U. S. Dollars. And here is the Bitcoin ap I class. This is the rial object in the proxy pattern. The class is derived from coin A p I ons implements the gets value in USD methods. You can see here that the methods uses a weapon request to retrieve the Jason Data Parsons is and then returns the Bitcoin value in U. S. Dollars. Okay, Now for the rate limits or cause here is the proxy objects calls with great limits. You can see that it also derives from coin a p I. And so it shares the get value in USD methods with the real objects. The class has a constructor that receives a reference to the real objects in the arguments on its stores. This reference in a protected field calls real subjects and here is the implementation off the get value in USD methods, you can see that the codes uses a date time fields to determine when the message was last calls. If the time interval between this coal on the last is less than one second. Then the call will be denied on the proxy returns on invalid operation Exception. But if the time interval is actually one seconds or more, then the proxy simply calls the rial objects to get the Bitcoin value and returns its to the clients. And finally, here is the bad clients class. It sets up a Bitcoin ap I variable, but it wraps it in a call to with rate limit. So now the clients is communicating with the proxy instead of the real objects. Then the code uses loop to call the Bitcoin message every 100 milliseconds. Notice that I wrapped the call in an exception handler to prevent the clients from aborting the moment the rate limiter kicks in. Okay, let me run the program to prove that everything is working. I am complaining the cold. No. And I am running the program. No, I'm There you go. Only one out of 10 calls is let through. Everything works. Okay. Here is a quick checklist you can use to implement the proxy pattern. First identify the need for a proxy. Do you need a remote access, lazy loading or access control, then define an interface that will make the proxy and the real object interchangeable on a proxy constructor that receives and stores a reference to the real objects implements the proxy interface that's finally make sure declines in Stan she ate the proxy instead of the real objects sounds. Here are some final comments You've probably noticed that the proxy pattern is very similar to the decorator pattern the UML diagrams off. Both passwords are almost identical. The difference between these patterns is in the intense. You use decorators to provides on enhanced interface to an existing objects on. Modify the behavior of existing methods in subtle ways. But you use proxies to either lazy and stan shapes and objects. Hide the fact that you're calling a remote service or control access to the objects. Proxies are very common when you're using remote procedure calls. The dot net framework has many libraries. For this task, there's the remote ING library, the Web service library on the double UCF framework. All of these automatically creates proxies to access very mult objects. And finally, here is something to consider. To use the proxy. The client's needs to declare a variable off type subjects on then initialize. It's with an instance off proxy. This is not very clean codes because now the clients gets to decide whether or not to use proxies, aim or elegance. Implementation is to combine the proxy pattern with the factory message. Pass one on use a factory methods to automatically create the correct object. The decision to create proxies instead of real objects can now be controlled by a configuration setting. Okay, here is a summary off what we've learned. The proxy pattern provides a surrogate or a placeholder for another objects. You use proxies for lazy object loading, for providing access to remote objects or to implement access control checks. The proxy on decorator patterns are very similar, but they differ in their intense. You can combine the proxy pattern with the factory method pattern to automatically create re correct objects. 15. Course recap: congratulations. You have completed the entire course. You are now a certifies C sharp design pattern employer. I have shown you all 12 creation ALS on structural design patterns, what their intense are and when you should implement them. Knowledge off these patterns will benefit you enormously. When you're developing your own projects, you have mastered the following creation all design patterns. The abstracts factory Parton that lets you create families off related or dependent objects , the builder pattern that lets you construct a family off complex objects in multiple steps . The factory method pattern, which creates objects on let's factory sub classes, decides which class to. In San. She ate the prototype pattern, which constructs objects by copying a prototype and modifying the copy on the singleton pattern, which ensures that a class has only one instance. You have also mastered the following structural design patterns. The adopted password, which changes the interface often existing objects to make it's compatible with another object. The bridge pattern, which lets you combine two or more or talking all class hierarchies. The composite pattern, which lets you compose objects out off one or more child objects. The decorator pattern, which attach is additional functionality to when objects dynamically. The facades pattern, which provides a high level interface to a complex subsystem. To make it easier to use the flyweight pattern, which supports a very large number off fine grains objects sufficiently. And the proxy pattern, which provides a surrogates or placeholder for another objects. These patterns have given you a rich toolbox off ready made templates that you can use when writing your own codes or when collaborating in a development team, especially when you're working on complex application architectures. If you discover some interesting insights off your own, please share them in the course discussion for them, for us all to enjoy. Goodbye. I hope we meet again in another course.