Thursday, March 17, 2016

Head First Design Pattern Appendix: Leftover Patterns

Bridge Pattern

http://simpleprogrammer.com/2015/06/08/design-patterns-simplified-the-bridge-pattern/ 

bridge pattern says: “Decouples an abstraction from its implementation so that the two can vary independently.”

to say it in other words, Bridge Pattern basically abstract the abstraction.

for example: the steering wheel in the car is an abstraction, we dont care what is happening behind the hood.
this is a nice abstraction for the car, however the steering wheel is used also in ships, in airplanes ....

what we need to do is to abstract the steering wheel, and this is what the Bridge pattern does.



as you can see, we have an abstraction which is SteeringWheel, and this abstraction has an implementation which is SteeringSystem.

another example,
imagine that you want to build a web application framework which will let you build blogs stores ...


and now you have a new idea which is adding Themes to the system, for example light,dark theme, if you want to implement that without Bridge pattern you would have "Blog Light" "Blog Dark" .... and thousands of classes.


to fix this issue we use bridge Pattern


NOTE: bridge and strategy has the same structure, the difference is that strategy is for behaviour and bridge is for the structure of class

///////////////////////////////////////////////////////


Builder Pattern
builder pattern allows you to encapsulate the construction of a product in addition to building the product in steps.

for example:
when you build a vacation, you build the day then the hotel the dinner and so on:


in this case you can use a builder,



another example

lets say we have a
class Person{firstName; lastname; Phone; Age ....}

if you want to make a constructor with all these fields you will have Public Person(firstname, lastName, Phone, Age ...) it will be a big constructor

you can define a Public PersonBuilder { //put all the fields inside
protected String firstname
protected String lastName
protected String age
...}

and add set for all the fields

public void setFirstName(String fName ) {
this.firstName = fname;
return this
}

and add a method which is Build()

public Person Build() {
return new Person(this.firstName, this.lastName ...)
}

now to create a new person
PersonBuilder x = new PersonBuilder().setFname("asdfasfd").setLastName("asdfasdf")....
Person y = x.build();

the idea why dont you do this in the Person Class, we dont we define the set method in the Person class.
The thing is the object will be in Inconsistent State which means what you will do
Person x = new Person()
and then you start setting the field
x.setFName()
x.setLName()

as you can see the object was created then the fields was set, this is inconsistent
/////////////////////////////////////////

Chain of Responsibility Pattern

it is like define a chain in Struts, so you have the request object, each handler in the chain will check the object, if it has to do anything it does, if not it passes to the next one:

for example in email chain of responsibility we will check if it is spam (do this) if it is fan email then do this if complain then do this ....

With the Chain of Responsibility Pattern, you create a chain of objects that examine a request. Each object in turn examines the request and handles it, or passes it on to the next object in the chain.
ofcourse many handler can handle the request





NTOE: you can define your chain of responsibility as an arrayList
/////////////////////////////////////////////////////////
Flyweight Pattern
we know that this pattern is about not creating a  lot of objects and use the ones that were created before.

an example could be like this

in the ShapeFactory, we have a HashMap to keep the created Shape objects, if the requested Shape was created before there is no need to create a new one , you can return it from the Map



///////////////////////////////////////
Mediator Pattern
Use the Mediator Pattern to centralize complex communications and control between related objects.

for example if you have a program where if an alarm rings the coffee maker will work and the shower will do something.
and at the same time if the coffee works something else will happen


as you can see alot of communicaiton.

in order to solve this use the mediator pattern


Mediator pattern is very similar to the observer, however usually here we care about the execution order of the event, we save this order in the Mediator class.
////////////////////////////////////

Memento Pattern
use it when you want to return an object to one of its previous states, for instance, when user requests an undo.


/////////////////////////////////////////////////////
Visitor Pattern

example from uncle bob:
http://butunclebob.com/ArticleS.UncleBob.IuseVisitor 

lets say you want to print this employee report



Emp#NameQTD-hoursQTD-pay
1429Bob Martin432$22,576
1532James Grenning490$28,776
...

you can write this code


public class Employee {
  public abstract String reportQtdHoursAndPay();
}

public class HourlyEmployee extends Employee {
  public String reportQtdHoursAndPay() {
    //generate the line for this hourly employee  }
}

public class SalariedEmployee extends Employee {
  public String reportQtdHoursAndPay() {} // do nothing
}

now you can iterate over an array of employees and call reportQtdHoursAndPay().
the thing is, here you put the report formating logic in the Employee class which actually breaks the single responsibility principle.

in order to fix this you can use the Visitor pattern, where you can remove the formating logic to a different class and iterate over the employees to get just the information


public class Employee {
  public abstract void accept(EmployeeVisitor v);
}

public class HourlyEmployee extends Employee {
  public void accept(EmployeeVisitor v) {
    v.visit(this);
  }
}

interface EmployeeVisitor {
  public void visit(HourlyEmployee he);
  public void visit(SalariedEmployee se);
}

public class QtdHoursAndPayReport implements EmployeeVisitor {
  public void visit(HourlyEmployee he) {
    // generate the line of the report.
  }
  public void visit(SalariedEmployee se) {} // do nothing
}


to generate the report


  QtdHoursAndPayReport v = new QtdHoursAndPayReport();
  for (...) // each employee e
  {
    e.accept(v);
  }

in this case we define an EmployeeVisitor interface, this interface just have a visit() method with all types of employees as parameters.

in adition we add the method accept() to employee class

so now when we iterate over the employees we call the method accept().
after that method accept() will call the method visit() and pass the object this.

now we are in method visit() inside QtdHoursAndPayReport, and we have access to the employee object, you can print the format you want here and get whatever information you want from the employee class.

/////////////////////////////////////////////////////

Prototype Pattern
Prototype is simply cloning objects.


/////////////////////////////////////////

Interpreter Patter
use this pattern to build an interpreter for a language.
we will not write anything about it here, it is not used that often.

No comments:

Post a Comment