Tuesday, November 10, 2015

HeadFirst Design Pattern

 Ch1 Strategy Pattern


we start by a simple program which is a Duck,


all ducks can swim and quack(),
the ducks override the display() method to draw something on the screen

New requirement is to add fly capability to the duck.

we added fly() to the Duck super class.
this will create an issue, as we added fly() to the Duck class, it means that all sub classes will inherit this behavior, but some ducks cannot fly like RubberDuck


you may say it is easy to fix this issue, simply override the fly() method in the RubberDuck class


ok this is good, but you have to do that for all sub classes similar to RubberDuck, and in the future if you add a new class like WoodenDuck, you should override it again

you may think of a different solution, as the fly() method is making trouble in Duck class, lets take it out of this class, and put it in an Interface, and let everyone subclass implement this interface (same for quack() method, as also not all ducks quack)


but now you should implement fly() in each subclass, eventhough some subclasses share the same flying behaviour

this will lead us to the first design principle identify the aspects of your application that vary and separate them from what stays the same

so in our case we have 2 aspects the flying and quacking, we will take them out of the Duck class but not like the way we did in the previous image,
we will define an interface which is FlyBehaviour, and we will define some classes that implement this interface and define some flying behavior 



now the Duck class will have an Instance of FlyBehaviour and QuackBehavior


as you can see we defined a method performQuack() which calls the quack() method.

the full picture will be like this, and this is the Strategy Pattern we separate the behavior that change a alot.


what is nice in this implementation that you can change the behavior of the class at run time, so you can start by fly behavior and change it later.



as you can see we used setFlyBehavoir to change the fly behaviour at run time

OO Principles:
Always Encapsulate what varies

Always prefer composition over inheritance, with inheritance you are stucked with the inherited class, with composition you can attach yourself to any class you want, in addition composition allows you to change the class at runtime.

Program to Interface not Implementation so you can get benefit of polyomorphism 



Ch2 Observer Pattern


Nothing special here just an example about the Observer (publish subscribe) pattern,

So as we know, the publisher is called a Subject.

We should have a Subject Interface and an Observer Interface

the example was about WeatherData, the WeatherData will be updated and other Observers are interested in this update

here is the general picture of the observer pattern 


and the Wheather Example is Like this




the Display interface in the picture above is some extra functionality required by the observers, but sure it is not related to the observer patterns


and the code is

1- the interface definition



2- implementing the Subject interface
3- implementing the Observer interface


4- The main




Java and Observer Pattern
another thing that you should know is that java has an already built in Observer and Subject classes, you can use them to build your observer patterns the classes are java.util.Observable (The subject) and java.util.Observer (the observer)

The only problem is that Observable is not an interface, it is a class.


OO Principle
Strive for loosely coupled objects: The observer pattern is an example, the subject and observer are loosly coupled.


CH3 Decorator Pattern 


simple example is a coffee shop, you want to order coffee then add some topping like chocolate, milk and so on ...

the best way is to use the Decorator Pattern,
the solution looks like this:


1- you have the main interface Beverage, all drinks implements this interface (e.g. Espresso, Decaf ...) 
now all the Topping (e.g. Milk, Mocha, ...) also implement the Beverage interface but through the Decorator interface. as you can see the Docarator interface has an instance from Beverage (so you can use it to say add Topping on this Beverage).

the code looks like this:

1- the Beverage and Decorator:

as you can see here the CondimentDeocrator redifined getDescription() as abstract to force all the topping to override it.

2- The Drink classes
3- the Topping classes

as you can see the Topping (e.g Mocha) has a Beverage, and when you ask for the cost(), we will add the cost of Mocha to the Drink cost.

4- the Main

as you can see, we wrap the drink and topping together.

Java and Decorator
this behaviour is implemented everywhere in Java, specially in I/O

Undecorate
you may ask, what if i want to remove topping after adding it, well maybe Decorator is not the good pattern for that, think maybe about Chain of Responsibility for example.
however you can define this method in Topping classes 
public Beverage undecorate() {
          return this.beverage;
}
this method will returnthe actual drink without topping.


CH4: Factory and Abstract Factory Patterns

 in this chapter we talk about Factory Pattern and Abstract Factory Pattern.  we will not use the examples given in this chapter, we will just write some notes from it
 

 The idea here that creating object should be a responsibility of a single class,  we dont wanna see new() statments everywhere.
  they talked here about Dependency Inversion Principle, in order to achieve it you should always try to follow this:
  1- you should never have a variable that has a reference to a concrete class (if you use new(), it means that you are
  using a reference to a concrete class, get around that by using the Factory pattern)
  2- you should never have a class that extends a concrete class( only extend from abstract class or implement an interface)
  3- No method should override an implemented method of any of its base classes(if you override an implemented method, then your base
  class wasnt really an abstraction to start with)
 
In Factory Pattern, we will have a class with a specific method to create objects, for example lets consider the following:


we have different shapes here, we will add a Factory to create shapes
as you can see the creation of Shapes is totally seperated from their behaviour, they dont even know how they are created.

ShapeFactory class looks like this:

and if you wanna create a shape you write this.


as you can see the Factory Pattern creates an object of a single class (you will have a Factory class for each Interface), however sometimes you need to create multiple related object together. For example, lets say we have the following:


as you can see we have IProcessor and IRam interfaces,

we have 2 factories one to create a fast computer and another one to create slow computer, as you can see creating a computer means creating ram and processor.

FastComputerFactory knows that it should create CoreI7 processor and DDR3 ram
SlowComputerFactory will create CoreI3 and DDR1.

The AbstractComputerFactory has 2 methods one to getProcessor() and another one to getRam()

The code looks like this:


public interface IProcessor {void PerformOperation();}
public class CoreI7 : IProcessor
{
    public void PerformOperation()
    {
        Console.WriteLine("Operation will perform quickly");
    }
}
public class CoreI3 : IProcessor
{
    public void PerformOperation()
    {
        Console.WriteLine("Operation will perform Slowly");
    }
}


public interface IRam { void StoreData(); }
public class DDR3 : IRam 
{
    public void StoreData()
    {
        Console.WriteLine("Data will take less time to store");
    }
}
public class DDR1: IRam 
{
    public void StoreData()
    {
        Console.WriteLine("Data will take more time to store");
    }
}

public interface AbstractComputerFacotry
{
    IProcessor getProcessor();
    IRam getRam();
}
public class FastComputerFactory : AbstractComputerFacotry
{
    public  IProcessor getProcessor() { return new CoreI7(); }
    public IRam getRam() { return new DDR3(); }
}
public class SlowComputerFactory : AbstractComputerFacotry
{
    public  IProcessor getProcessor() { return new CoreI3(); }
    public IRam getRam() { return new DDR1(); }
}

As you can see in the picture we have a FactoryProducer, basically this is a producer of slow or fast computer

public class FactoryProducer {
   public static AbstractComputerFacotrygetFactory(String choice){
   
      if(choice.equalsIgnoreCase("Fast")){
         return new FastComputerFactory ();
         
      }else if(choice.equalsIgnoreCase("Slow")){
         return new SlowComputerFactory ();
      }
      
      return null;
   }
public class AbstractFactoryPatternDemo {
   public static void main(String[] args) {
      AbstractComputerFacotry computerFactory = FactoryProducer.getFactory("Fast");
      IProcessor processor = computerFactory.getProcessor();
      IRam ram = computerFactory.getRam();      
   }
}


CH5: Singelton Patterns


1- example of objects that could be singlton: Thread pool, cache, dialog boxes, logging,


this is a simple example, private constructor and getInstance() method

2- the previous example has concurrency issue, to fix it:

we made getInstance synchronized.

3- the previous example fixes the issue, however there is an overhead because of the synchronize, we every time the getInstance() is called we need extra resource to make it synchronize eventhough we need the syncronization only when we create the instance for the first time.

4- to fix the synchronization overheard, create the instance directly, JVM will be sure that the instance is created before any thread access it.


5- or you can synchronize the creation only


6- Be careful, if you have multiple class loaders then you can load the singleton class multiple times, which means you will have multiple instances of it.

7- as you can see the Singleton class actually does multiple things, it is responsible for its creation in addition to the actual behavior, it is OK, you can think of a solution like Singleton Factory:


8- forget about Singleton subclassing, the constructor is private so basically you cannot extend it, dont do a work around, think about your design again


CH6: Command Pattern



in case you see something like this

public void actionPerformed(ActionEvent e)
{
  Object o = e.getSource();
  if (o = fileNewMenuItem)
    doFileNewAction();
  else if (o = fileOpenMenuItem)
    doFileOpenAction();
  else if (o = fileOpenRecentMenuItem)
    doFileOpenRecentAction();
  else if (o = fileSaveMenuItem)
    doFileSaveAction();
  // and more ...
}

then sure there is a problem, as you can see you are checking the instance and then you call an action method, this means that all these instances should implement a single interface which is the Command interface

// the Command Pattern in Java
public interface Command
{
  public void execute();
}

this interface should be implemented by all the types mentioned in actionPerformed

public class FileOpenMenuItem extends JMenuItem implements Command
{
  public void execute()
  {
    // your business logic goes here
  }
}

now simply you can write actionPerformed like this


public void actionPerformed(ActionEvent e)
{
  Command command = (Command)e.getSource();
  command.execute();
}

sure you can extend this pattern to do something more, for example maybe e.getSource() returns a list, you can simple loop over the list and call execute()

also you can add undo() function to the command interface and implement this function.


CH7: Adapter and Facade Pattern and Principle of Least Knowledge


Adapter Pattern

lets say you have a Duck interface

and here is the implementation


also we have another interface which is Turkey 

as you can see in Turkey interface we have gobble() not quack.
here is the implementation.


the problem here, as WildTurkey and MallardDuck implement different interfaces you cannot use them interchangeably. 

in order to use them in a polymorphic style we should define an adapter to make the Turkey looks like Duck

the adapter looks like this


as you can see the Adapter implements the Duck interface, and it uses a Turkey instance.
the quack() method implementation is simple a call to the gobble() 

now to use the previous code


Facade Pattern
lets say that we have a home theater system 


as you can see, many classes are involved in this system, in order to watch a movie you should do all this:


which means if you want to use the system, you will make a lot of call, 

in case you have such a system, and you want to simplify the call you can define a Facade class, that simplify the call,
 

the Facade pattern hide all the internal complexity of a system, it is responsible for doing all the calls.



The Principle of Least Knowledge
it means that classes should not know much about each other.

in order to achieve that, each object can invoke only the following methods:

The Facade pattern is a good example of this Principle


CH8: Template Method Pattern and Hollywood Principle 


template method define the skeleton of algorithm in a method,
for example making coffee has the follwoing steps: 
1- boil water, 2- brewCoffeeGrinds 3- pourInCup, 4- addSugarAndMilk.

making tea has the following steps:
1- boil water, 2- steepTeaBag, 3- pourInCup, 4- addlemon

ass you can see that the method can be abstracted in a template method


as you can see we defined the template method prepareRecipe() as final.

brew() method, represent brewCoffeeGrinds and steepTeaBag, is defined as abstract so it can be implemented by the subclass.

same for addCondiments

now you can implement the class like this

in addition in template method you can use something called hook methods


hook methods has an empty implementation in the base class, the subclass can decide if it wants to implement it or not

OO Principle
Hollyowood Principle: dont call me i will call you. 
you can see it here in Template Method, the super class is calling the sub class when it needs anything.

Template Method vs Strategy Pattern
Notice the difference between Template Method and Strategy Pattern, 
1- Strategy Pattern depends on composition, here we have inheritance
2- In Strategy Pattern you can change the algorithm on runtime 
3- Template Method defines just the skeleton of the algorithm, Strategy Pattern is responsible for the algorithm itself.


Ch9: Iterator Pattern & Composite Pattern


Iterator pattern is easy, you hide your internal implementation and provide a global way to iterate over elements:


Composite Pattern
Composite pattern is used when you want to have a tree representation,
for example the relation between employee is like a tree, a manager and employee


the implementation and usage is simple:


the usage is like this:



Ch10: State Pattern


State pattern is about keeping state, It is very  similar to strategy pattern we will talk about that later.

we will start by an example to understand the problem that state patters solves

lets take an example of a Gum Ball machine. the gumball machine is a state machine which could have the one of the following states

you can represent these states in java by using final static vairables


the gumball machine has the following actions


now if you want to write code to implement this you will write something like this

as you can see a lot of else if, and if any change happens then we should change in many places.

the solution is to use the state pattern 


as you can see for each state you have a class and you do the implementation in that class.



as you can see above, an implementation for one of the states, also you can see that the state has a reference to the GumballMachine, and in insertQuarter() we change the state to something else.


as you can see above in GumballMachine, we have an instance of each state and we actually pass (this) to all these states.


Strategy Pattern vs State Pattern
in general they are similar, however we use them for different things, State pattern is like a state machines, so you define the way you move from one state to another. sure you can change the behaviour in Strategy Pattern but you change it in a different way.


Ch 11: Proxy Pattern


In this chapter we will talk about proxy pattern, the given example is not from the book

we have different types of proxy pattern,
Remote Proxy: you use this proxy to access remote objects, you define a stub and skeleton and start calling the remote object.

the other type is Virtual Proxy, in Virtual proxy you define as a proxy for another class, usually this class is expensive to create, so we use the proxy instead

example, an image class, the image needs to be loaded from the disk, this class will be considered as heavy, so we will define a proxy to be used instead of the class.


as you can see the RealImage class load the file from the disk

now we define a ProxyImage, which implements the same Image class.


The ProxyImage firstly load the image using RealImage object, after loading for the first time we start using this image through realImage.display().

now to use the code


NOTE: there is a difference between Facade and Proxy, in proxy you and the object has the same interface, however in facade you have totally a different interface.


CH12: MVC Pattern


We know the MVC Pattern

The Controller will receive the request, call the appropriate Model, then pass the control to the view.



an example could be

Here we have the Student Class as the Model


The view is defined like this


The Controller is defined like this



NOTE: in the previous example, the controller calls the Model, sometimes the Model might update the controller about its state.

NOTE: int the MVC, we can consider the Model as Observer Pattern, the Controller as Strategy Pattern (You can change the controller whenever you want) and the View as a Composite pattern (consider the view as a page with multiple elements inside)




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.