The Decorator Design Pattern

What is the Decorator Design Pattern?

The Decorator pattern applies when there is a need to dynamically add as well as remove responsibilities to a class, and when the sub-classing would be impossible due to the large number of sub-classes that could result. Also, use it when you want the capabilities of inheritance with sub-classes, but you need to add functionality at run time.

Intent

  • Attach additional responsibilities to an object dynamically.
  • Decorators provide a flexible alternative rather than making many subclasses to extend functionality.
  • Client-specified embellishment of a core object by recursively wrapping it.
  • Wrapping a gift, putting it in a box, and wrapping the box.

Discussion

Say, you are working on a UI and you want to add borders and scroll bars to your windows. You could define the inheritance like… Window class interface, then you have concrete objects WindowWith_Scrollbar, WindowWith_Border etc..  This type of architecture creates a lot of subclasses and not much room for modularity.  It will be hard to change the concrete classes if you want to add some additional functions to them.

The Decorator pattern suggests giving the client the ability to choose what features they want.  There might be a problem of chaining features together to produce custom objects as well. The solution to such problem is to encapsulate the original object inside an abstract wrapper interface. Both the decorator objects and the core object will inherit from the abstract interface. Then the interface uses recursive composition to allow an unlimited number of decorator to be added to each core object.  One thing to note is that the interface must remain constant when successive layers are specified using the decorator pattern.

The decorator pattern hides the core components of the objects inside the decorator object. Trying to access the core object directly would be a problem.

UML Diagram

400px-Decorator_UML_class_diagram.svg

 

Example

One example is making a pizza ordering system. You can use the decorator pattern to implement a simple pizza ordering system by creating a pizza(component) and a plain pizza(Concrete Component) that is just the base or dough. Then the decoratorPizza(Decorator) which has the plain pizza and other functions. Lastly, the toppings(Concrete Decorators) for your pizza like: mozzarella, the sauce, pepperoni, etc.

In this example, you have an interface pizza and a plain dough. The decorator then adds the desired toppings to the pizza.

 

Conclusion

I chose this particular topic since we are creating a simple web app for scheduling classes. I thought that it was helpful since we might be adding pop up windows to our web app.

The Decorator Pattern is useful when you see yourself making something that is extensible and where you can interchangeably choose which components/functions you want on your object.  I think that with the decorator pattern, there is a lot of potential when using it. You could create something that has many functionality and is still easily changeable.

source: decorator pattern

Advertisements

Observer Pattern

The Observer Pattern is an example of a behavioral pattern. In object oriented programming, which most of the application nowadays are built of, you cannot talk about it without considering the state of objects. Object oriented programming is all about object interactions. There are cases where objects needs to be informed about the changes of other objects are often. If you want to have a good design, you would want to have to decouple the objects as much as possible for modularity. The observer pattern might be the best pattern for that job.

The Observer Pattern can be used whenever a “subject” needs to be observed by the concrete objects.

Intent:

  • Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

How to Implement Observer Pattern:

  • Observable – interface or abstract class defining the operations for attaching and de-attaching observers to the client. In the GOF book this class/interface is known as Subject.
  • ConcreteObservable – concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
  • Observer – interface or abstract class defining the operations to be used to notify this object.
  • ConcreteObserver concrete Observer implementations

It is pretty simple how it works. After creating your subject class, it will then instantiate your ConcreteObservable class and set the states of the objects. Then the Observer class checks if there are any update or notifications from the subject and then update is  called on to the ConcreteObservers.

 

The observer pattern is used when:

  • the changes in one object also happens in other objects without keeping the object tightly coupled.
  • or when our design needs to be enhanced in the future with new observers with minimal changes.

Common example of Observer Pattern:

  • Model View Controller Pattern – the observer pattern is used in the model view controller(MVC) architectural pattern. In MVC the observer pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.

Observer Pattern in UML Diagram:

observerpatternuml

 

I selected this topic because I have read many articles and tutorials about this subject, and since I was making a tutorial about it, I might as well write about it in this blog.

The observer pattern is an exceptional pattern to learn in object oriented design in my opinion. Since, most of the programs written these days are object oriented, it is a good resource to know that when you have a one-to-many dependency between objects, it is useful to use the observer pattern. You can use this pattern to create a notification system for your application.

Reference:

Observer Pattern by OODesign

Builder Design Pattern

Builder Design Pattern is an example of a creational pattern. Creational design patterns solves the problem/complexity of object creation in a design by somehow controlling the objects creation.

Builder design pattern is used to create objects that are made from a bunch of other objects. You use the builder design pattern when you want to build an object made out of other objects. Use it when you want the creation of these parts to be independent from the parent object. Hide creation of the parts from the client. Only the builder knows the specifics of the object and nobody else.

Intent of Builder design pattern.

  • To separate the construction of a complex object from its parent object so that the same construction process can be created differently in representations.
  • Create one of several targets

In a builder design pattern, we have the “director” which invokes the “builder” services as it interprets the external format. The “builder” then creates the object each time it is called. Then, when the product is finished, the client retrieves the results from the “builder”.

1aa5ab128c99a174fc628835260d7aeb

Example:

Say the client wants a new remote for your TV, but you know that you’ve already made a remote before and the client wants the same thing but calls it the “remoteX”. You can use your old remote object to pass it in a director to create remoteX by passing it to the remote builder without changing anything from the old remote set up.

 

Other Useful things to consider:

  • Builder can use one of the other patterns to implement which components get built. i.e Abstract Factory, Builder, and Prototype can use Singleton for implementation.
  • Builder focuses on constructing the complex object step by step.
  • Builder often builds a Composite.

 

The builder design pattern is really helpful when you are creating objects that are made out of other objects. Just like creating a menu, most menus have a drink, appetizers, and a dessert associated with the meal. You can also use other patterns to implement which components will be built.

I selected this topic because it is one of the main design patterns that is discussed in the Gang Of Four book. It is also pretty simple to understand. The builder design pattern is also a good pattern to have under your belt, since it seems like in the real world we are creating the same objects and upgrading it much more often than creating a new one.

I really think that learning the main or fundamental design patterns is beneficial when creating an application. It just always seem to pop up. Like for our final project, we were thinking of building a class schedule maker, but you can also make the class schedule maker just a regular schedule maker say for appointments or meetings.

 

https://sourcemaking.com/design_patterns/builder

Command Design Pattern

In today’s blog, I will be discussing about a design pattern called the Command Design Pattern.

What is a Command Design Pattern?

Command Design Pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to perform an action or trigger and event at a later time.

How does it work?

The requests are wrapped as commands and passed to invoker object. The invoker object then looks for the appropriate object which can handle this command and gives the command to the corresponding object that will execute this command. The base class contains an execute() method that simply calls the action on the reciever.

A command class includes some of the following: an object, the method to be applied to the object, and the arguments to be passed when the method is applied.

Command Design Pattern allows you to store lists of code that is executed at a later time or many times. Client do not know what the encapsulated objects are, they just call the Command to run when execute is called.  An object called the Invoker transfers this command to another object called the receiver to execute the right code.

How to Implement the Command Pattern?

 

First of, you have to create an interface that acts as a command.  Command object knows about the receiver and invokes a method of the receiver.

Second, create your objects(client) that will serve as requests.  The client decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker.

Third, create concrete command classes(also known as the receiver) that implements the command interface which will do the actual work when the execute() method in command is called.

Lastly, create an invoker object to identify which object will execute which command based on the type of command.  The invoker object does not know anything about the concrete command, it only knows the command interface.

Command

I selected this post because I wanted to learn more about different patterns that is not covered in class. This post shows you what the Command Pattern is and how it works. It also shows you the different steps and an example code on how to use the command design. The diagram above is from the post.

The Command Pattern seems to be very useful when you found yourself using code that looks like:

if (…..)

do();

else if(……)

do();

else if(……)

do();

else if

……..

I think Command pattern is very useful when you are creating an interface where objects are waiting to be executed, just like the menu interface.

https://www.tutorialspoint.com/design_pattern/command_pattern.htm

The Importance of the Fundamentals of Design Patterns

For this blog, I am choosing one from Uncle Bob’s website, the Clean Coder Blog. Almost all of Uncle Bob’s blog are set up like a conversation. Uncle Bob writes questions that the readers might ask, and also answer them for the readers. It is really fun to read his blogs, it is usually short, and might answer some of your questions and give you more insight on the topic that he is writes about.

In his blog called “A Little About Patterns”, Uncle Bob talked a little bit about Design Patterns. In this blog, there were a lot of questions about why we still use Design Patterns that were made from the 90’s. It was mainly about the Design Patterns by the GOF(Gang of Four) book that was made popular in 1995. In the blog, Uncle Bob asked if the “person” could name a design pattern. He then pointed out the book GOF. The person then replied ” But isn’t that kind of old now and outdated?”. Uncle Bob then responded with “Indeed there are many newer books on the topic, and some are quite good; but none are quite so impactful and insightful as the original.”

Throughout the blog, Uncle Bob was just proving that, even though the GOF book was written 20 years ago, it still stands as the best book. He noted that “The Design Patterns book is one of the most important books, if not THE most important book, written about software within the last 20 years. In fact, the fundamentals of software have changed very little in the last four decades.” This just tells us that, even though it might seem like these designs are old, they are still the fundamental of Design Patterns.

Uncle Bob then said that most of the idea of the newer frameworks are old. That they are just Design Patterns. Then he gave this “person” the meaning of a design pattern. “A Design Pattern is a named canonical form for a combination of software structures and procedures that have proven to be useful over the years.”

The blog introduces a couple of newer Design Patterns like Model-View-Controller(MVC) which is a software architectural pattern for implementing user interfaces on computers, and how you can just say this is dependency injection and everybody will understand it in a way.

I chose this blog because it talked about design patterns and how the fundamentals which we are learning in class even if they were written from 20 years ago, are still the very core of Design Patterns. I think that to learn the proper way of using Design Patterns, we should learn about its fundamentals first.

The Importance Of Clean Architecture

In Episode 68 of the CodingBlocks podcast,  they talked about the latest book, Clean Architecture by Robert Martin (colloquially known as Uncle Bob).  In the podcast, they explained the benefits of a clean architecture and why it matters. They said that the benefits of a clean architecture is that it can minimize efforts when it comes to adding features to the program.  Their functionality is maximized and changes are easy. It can reduce the number of people needed to write the software and adding features. They also added that there is no difference in design and architecture when it comes to a program. That the architecture should be incorporated into the design as well.  Throughout the podcast, they keep using the analogy of the Turtle and the Hare. They quoted that in the book, Uncle Bob added that “the only way to go fast, is to go well”. I think that this is a really good quote. Often we are bounded by the due date or time. In the podcast,

Also, in the podcast, they also said that “coding is easy, but managing our code when new features are added is the real challenge”. They said that maintaining cleanliness is better than cleaning it after the problems are piled up. Michael also talked about how sometimes, they say that the developers are not working. Which isn’t really the case. The problem lies in the architecture of the product since it does not support the changes that the product manager or client wants. They also talked about how sometimes company X comes to the market first but company Y is more successful because they were able to add more features faster than company X.

They also tackled the problem of rewriting the code, which most of us think would be the solution to the architectural problems. They said that rewriting is not the answer. Most of the time, we would rewrite the program to fix the problem. You will feel good about yourself when rewriting it since you are doing it really fast. But still not thinking about how to solve the architectural problem of your program. They said that the quality of your products should be taken seriously. Since developers are constrained by time most of the time, they forget the risk that are involved by being “fast”. Sometimes unit tests are not done and the code is not reusable anymore.

I chose to listen to this podcast because I wanted to learn more about Software Architecture and what are the benefits of having a good architecture versus just having a code that works. I  actually questioned Dr. Wurst about this, having done his first assignment for us. I asked him why we needed a better architecture even if the amount of classes in the program looks like a cluster. After listening to this podcast, it finally makes sense to me now. A product that have a better architecture is easier to change or add programs. In the long run, a better structured program is better and would be easier to manage than a program that is done “fast but not well”.

UML Diagrams

 

In this blog, Mohamed Elgendy talked about why do we use model and some of the different kinds of diagrams used in UML.  Mohamed started off by explaining what UML is. He said that “UML is a set of standardized (Unified) diagrams, just like construction has front elevation, electrical diagram, floor plan, etc., UML offers different views of the same system.”. Which basically means that  UML is just a blueprint. In software development, we use this blueprint to better communicate with other people rather than software developers  in a way that they could understand.

In the blog, Mohamed explained different type and use of each diagrams and which team members are responsible for creating the diagram.

Class Diagram describes the structure of a system by showing the system’s classes, their attributes and the relationships among these classes. It display what interacts but not what happens when they interact.  The Class Diagrams are created by the Architects or the Technical Leads.

Component Diagram  are composed of one or more classes or interfaces. It is used to depict how various components of a system show dependencies. The Component Diagrams are used during the technical design and is also created by the Architect or the Technical Leads.

Deploying Diagram shows the physical relationship among the software and the hardware components in the system. In many cases, the component and deployment diagrams are combined in a single diagram. This is also created by the Architect or the Technical Leads.

Package Diagram shows the group of classes called “package”. Similar classes are grouped together if they do the same thing. Sometimes developers choose to display individual classes inside the package for better clarification. The Package Diagrams are created by the Architect or the Deployment Specialists.

Statechart Diagram describes the behavior of a system where  it shows the possible states  an object can be. It is typically drawn for objects that typically have a lot of dynamic behavior.  Statechart Diagrams are created by the Architect.

Object Diagram depicts a complete or partial view of the system at a specific time. Object Diagrams are created by the Developer.

Sequence  Diagram displays the sequence of events between entities of the system to show the dynamic view of the system. It is executed line by line showing the time ordering of messages.

Activity Diagrams describe the sequencing of actions and system’s logic. The starting point of this diagram is indicated by a large black dot and uses arrows to point to the order of actions.  Activity Diagram is typically used for objects are more complex that you would like to present clearly.

I selected this particular blog since we are using UML in Software Construction, Development, and Architecture class. I was actually a bit confused about how we used the diagrams in class. I was thinking that diagrams are just one program like we did in class, but diagrams are actually made to connect with other diagrams to explain how they interact with each other. In this blog, Mohamed added which team members are responsible for each diagrams. After reading this blog it is clear to me now that there are different responsibilities and types of people in a team. I thought that a team would be composed of all software developers, but in reality, some modeling diagrams are done by other professionals.