# Object Orient Programming-Course2 Week2 ###### tags: `OOP` `Coursera` <style> .red { color: red; } </style> <style> .blue { color: blue; } </style> <style> .green { color: green; } </style> ## Behavioral design pattern1-Template Method Pattern The <span class ="red"> Template Method</span> defines algorithm's steps generally, **deferring the implementation of some steps to subclasses**. It is a behavioral design pattern and is concerned with the assignment of responsibilities. ### Example for an algorithm: 1. **"Drive To Destination" for vehicles** ```graphviz digraph obj{ node[shape=record]; rankdir="LR"; Accerlerating [label = "{<f0> Accerlerating}"]; Steering [label = "{<f0> Steering}"]; Breaking [label = "{<f0> Breaking }"]; CheckIfReachedDestination [label = "{<f0> CheckIfReachedDestination| }"]; Accerlerating->Steering [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal",headlabel=" ",taillabel=" "]; Steering->Breaking [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal",headlabel=" ",taillabel=" "]; Breaking->CheckIfReachedDestination[style="normal,"dir="forward",arrowhead="vee",arrowtail="normal",headlabel=" ",taillabel=" "]; } ``` 2. **"Make Recipe" for Pasta Dish** ```graphviz digraph obj{ node[shape=record]; rankdir="LR"; BoilWater [label = "{<f0> BoilWater}"]; AddPasta [label = "{<f0> AddPasta}"]; CookPasta [label = "{<f0> CookPasta }"]; DrainAndPlate [label = "{<f0> DrainAndPlate }"]; AddSauce [label = "{<f0> AddSauce }"]; AddProtein [label = "{<f0> AddProtein }"]; AddGarnish [label = "{<f0> AddGarnish| }"]; BoilWater->AddPasta [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal",headlabel=" ",taillabel=" "]; AddPasta->CookPasta [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal",headlabel=" ",taillabel=" "]; CookPasta->DrainAndPlate[style="normal,"dir="forward",arrowhead="vee",arrowtail="normal",headlabel=" ",taillabel=" "]; DrainAndPlate->AddSauce AddSauce->AddProtein AddProtein->AddGarnish } ``` ### About template method Due to the fact that all these method should be called in any subclasses, <span class = "green">calls to all of these methods will be laid out inside the template method.</span> Therefore, these steps(in algorithm) would be called the same way in all subclasses though some of the methods would <span class = "red">be implemented differently</span> in each subclasses. For instance, in algorithm "Drive To Destination", how you steer a car is different from how you steer a motorcycle. In algorithm "Make Recipe", how you AddProtein in Seafood with garlic pasta is different from how you AddProtein in meatball and tomato pasta. The <span class = "green">template method</span> is best used when you can <span class = "red">generalize</span> between <span class = "green">two classes(or more) into a new super class</span>. By <span class = "green">generalization</span>, you can more effectively <span class = "blue">reuse objects</span>. <span class = "green">Using inheritance</span>, you can <span class = "blue">share the functionality</span> between classes and allow for <span class = "blue">clearer and more self-explanatory code</span>. ### UML for template method pattern ```graphviz digraph obj{ node[shape=record]; rankdir="BT"; AbstractClass [label = "{<f0> AbstractClass|<f1>Template Methods... \n Premitive Operations... }"]; ConcreteClass1 [label = "{<f0> ConcreteClass1|<f1>Premitive Operations...\n }"]; ConcreteClass2 [label = "{<f0> ConcreteClass2|<F1>Premitive Operations...\n}"]; ConcreteClass1->AbstractClass [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "]; ConcreteClass2->AbstractClass [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "] } ``` ### UML for template method pattern in example #### **"Make Recipe" for Pasta Dish** ```graphviz digraph obj{ node[shape=record]; rankdir="BT"; AbstractClass [label = "{<f0> AbstractClass|<f1>+makeRecipe():void \n -boilWater():void\n-cookPasta():void\n-drainAndPlate():void\n#addPasta():void\n#addSauce():void\n#addProtein():void\n#addGarnish():void}"]; ConcreteClass1 [label = "{<f0> ConcreteClass1|<f1>+addPasta():void\n+addSauce():void\n+addProtein():void\n+addGarnish():void\n }"]; ConcreteClass2 [label = "{<f0> ConcreteClass2|+addPasta():void\n+addSauce():void\n+addProtein():void\n+addGarnish():void\n}"]; ConcreteClass1->AbstractClass [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "]; ConcreteClass2->AbstractClass [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "] } ``` #### **"Drive To Destination" for vehicles** ```graphviz digraph obj{ node[shape=record]; rankdir="BT"; AbstractClass [label = "{<f0> SelfDrivingVechicle|<f1>+driveToDestination():void \n -CheckIfReachedDestination():void\n#Steering():void\n#Breaking():void\n#Accerlerating():void}"]; ConcreteClass1 [label = "{<f0> SelfDrivingCar|<f1>+Steering():void\n+Breaking():void\n+Accerlerating():void}"]; ConcreteClass2 [label = "{<f0> SelfDrivingMotorcycle|+Steering():void\n+Breaking():void\n+Accerlerating():void}"]; ConcreteClass1->AbstractClass [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "]; ConcreteClass2->AbstractClass [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "] } ``` ## Chain of Responsibility Pattern ### What is Chain of Responsibility Pattern In software engineering ## Command Pattern ### What is a Command Pattern The <span class = "red">Command Pattern</span> encapsulate the request as an object of its own. Usually, when an object makes an request for the second object to do something, it will call a method of the second object and the second object will complete the task. ```graphviz digraph obj{ node[shape=record]; rankdir="LR"; Sender [label = "{<f0> Sender}"]; Receiver [label = "{<f0> Receiver}"]; Sender->Receiver [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal", label="request",taillabel=" "]; } ``` In **Command Pattern**, instead of having Sender communicate with Receiver directly, the command pattern creates a command object in between the sender and receiver. This way, the sender doesn't need to know about the receiver and the methods to call.(Decoupling, Information hiding) ```graphviz digraph obj{ node[shape=record]; rankdir="LR"; Sender [label = "{<f0> Sender}"]; Command [label = "{<f0> Command}"] Receiver [label = "{<f0> Receiver}"]; Sender->Command [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal", label="Create",taillabel=" "]; Command->Receiver [style="normal,"dir="forward",arrowhead="vee",arrowtail="normal", label="Call methods",taillabel=" "]; } ``` what actually makes the command object do what it's supposed to do and invoke the specific receiver object to complete the task? Ans: <span class = "green">**Invoker**</span> Turning the different requests in your software into command objects can allow you to treat them as the way you would treat other objects. You can store these command objects into lists, you can manipulate them before they are completed, or you can put them onto a queue so that you can schedule different commands to be completed at different times. ### UML for Command Pattern ```graphviz digraph obj{ node[shape=record]; rankdir="BT"; Command [label = "{<f0> Command||+execute():void\n+unexecute():void\n+isReversible():bool}"]; ConcreteCommand [label = "{<f0> ConcreteCommand||+execute():void\n+unexecute():void\n+isReversible():bool}"]; Receiver [label = "{<f0> Receiver| }"]; Invoker [label = "{<f0> Invoker||+action():void }"]; Command->Invoker [style="normal,"dir="forward",arrowhead="odiamond",arrowtail="odiamond",headlabel=" ",taillabel=" "]; ConcreteCommand->Command [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "] Receiver->ConcreteCommand[style="normal,"dir="forward",arrowhead="odiamond",arrowtail="normal",headlabel=" ",taillabel=" "]; } ``` ### Example for Command Pattern: CopyPaste Command Code for Concrete Command ```java= public class PasteCommand extends Command{ private Document mDocument; // a receiver private int mPosition; private String mText; ... public PasteCommand(Document _document, int _position, int _text){ this.mDocument = _document; this.mPosition = _position; this.mText = _text; } public void execute() { document.insertText(position, mText) } public void unexecute(){ document.deleteText(position, mText.length()); } public boolean isReversible(){ return true; } } ``` Usage for Invoker ```java= CommandManager myCommandManager; //Invoker Command newCommand = new PasteCommand(document, position, text); myCommandManager.invokeCommand(newCommand); ``` ### When to use? Benefits? Conclusions **When?** 1. store and schedule different requests. 2. Manipulate command before they are completed 3. Put them onto a queue so that you can schedule different commands to be completed at different times 4. Undo and Redo a command or mentioning reversibility. 5. .etc **Why Better?** 1. Allows you to manipulate Commands as Objects(what method can't do) 2. Adding **Undo/Redo and reversibility** or put Command to queue(As Object) 3. Decouples the objects in the software(Sender and Receiver) 4. Sender do not need to concern which receiver should handle the command. ## Observer pattern When you are interested in a blog, you have to view the blog multiple times a day to check for new posts. There must be a better way than continuing this routine. Instead of checking the blog periodically, you can subscribe the blog and let the blog notify you when something new has been introduced. This method is called **Observer Pattern**. This way, you would be notified of the new content when it is created, rather than having to pull for this information at some interval. ### How blogs and subscibers interact with each other ![](https://i.imgur.com/DO2sXgi.png) In order to form the Subject and Observer relationship, a Subscriber must subscribe to the blog. Next, the blog needs to be able to notify its subscribers that a change has happened. After that, the subscribers have to get the state of the blog through a get state call. It's up to the blog to make sure its subscribers get the latest information. If the subscriber does not end up enjoying the content of the blog, they would need a way to unsubscribe. ### UML for Observer pattern ```graphviz digraph obj{ node[shape=record]; rankdir="BT"; Subject [label = "{<f0> Subject|<f1>+registerObserver(Observer):void \n +unRegisterObserver(Observer):void\n+notify():void}"]; Observer [label = "{<f0> \<\<interface\>\>\nObserver|<f1>+update():void}"]; Blog [label = "{<f0> Blog|-state:String|<f1>+getState():String}"]; Subscriber [label = "{<f0> Subscriber|<f1>+update():void}"]; Blog->Subject [style="normal",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "]; Subscriber->Observer [style="dashed",dir="forward",arrowhead="onormal",arrowtail="normal",headlabel=" ",taillabel=" "] Observer->Subject [style="normal",dir="forward",arrowhead="odiamond",arrowtail="normal",headlabel=" ",taillabel="0...* "] } ``` ### Example code for Oberser Pattern ```java= public class Subject{ private ArrayList<Observer> subscribedObservers; public void registerObserver(Observer _obs){ subscribedObservers.add(_obs); } public void unregisterObserver(Observer _obs){ subscribedObservers.revome(_obs); } public notify(){ for(Observer obs : subscribedObservers) { obs.update(); } } } public class Blog extends Subjects{ private String state; public String getState(){ return state; } //blog responsibility //...... } public interface Observer { public void update(); //this method is called when the blog notify that the // blog has changed. } public class Subscriber implements Observer{ public void update(){ //ex:get the blog channel... } } ``` If many objects rely on a certain state or the rely relation may change through time, then the value of the Observer pattern becomes more pronounced.