Skip to main content

Factory Method Pattern

Official definition :

Defines an interface for creating an object, but lets subclass decide which class to instantiate. Factory method lets a class defer instantiation to subclass.

So factory method pattern is a pattern that manipulate the product functionality but not instantiate the product object, a subclass take decision to make which class it instantiate by extend or implement the abstract creator class. Abstract creator class has no knowledge of the actual product that will be created.Object creation is totally depend on subclass.

For example


abstract class  PizzaStore
{
    public function orderPizza($type) {

        $piza = null;
        $piza = $this->createPizza($type);

        $piza->prepare();
        $piza->bake();
        $piza->cut();
        $piza->box();
        return $piza;

    }

    abstract function createPizza($type);
}

Here PizzaStore our main AbstractCreator class which extent by Concrete Subclass NyStylePizzaStore. And NyStylePizzaStore class take decision to make which class it will instantiate.


class NyStylePizzaStore extends PizzaStore
{

    function createPizza($type)
    {
        if ($type == "chesse") {
            return new NyStyleChessePizza();
        } else if ($type == "peporoni") {
            return new NyStylePeporoniPizza();
        } else if ($type == "clam") {
            return new NyStyleClamPizza();
        } else if ($type == "veggie") {
            return new NyStyleVeggiePizza();
        } else {
            return null;
        }
    }
}





class NyStyleClamPizza extends Pizza
{

    public function __construct()
    {
        $this->storeName = "NyStyle";
    }
}

/**
 * Pizza File
 *
 * @author Md.Atiqul haque <md_atiqulhaque@yahoo.com>
 */




abstract class Pizza implements Store
{
    protected $storeName;

    public function bake()
    {
        echo  "----" . "Baking....<br>";
    }

    public function prepare()
    {
        echo "----" . "Preparing piza for {$this->storeName}...<br>";
    }

    public function cut()
    {
        echo "----" . "Cutting...<br>";
    }

    public function box()
    {
        echo  "----" . "Boxing...<br>";
    }

    public function getName()
    {
        return $this->storeName;
    }
}


/**
 * Store File
 *
 * @author Md.Atiqul haque <md_atiqulhaque@yahoo.com>
 */




interface Store
{
    public function bake();

    public function prepare();

    public function cut();

    public function box();
}

$pizaStore = new NyStylePizzaStore();

$pizaStore->orderPizza('clam');

Out put will be
—-Preparing piza for NyStyle…
—-Baking….
—-Cutting…
—-Boxing…

SOLID design principle

SOLID is an acronym. which full meaning is

S – Single-responsibility principle
O – Open-closed principle
L – Liskov substitution principle
I – Interface segregation principle
D – Dependency Inversion Principle

When a developer develop a software if he flows this principle it is easy to maintenance and reuse and test his module. let see what is S.O.L.I.D is.

Understanding “S”- SRP (Single responsibility principle)

A class should have one and only one reason to change, meaning that a class should have only one job.

For example Student class represent student

Understanding “O” – Open closed principle

Objects or entities should be open for extension, but closed for modification.

Understanding “L”- LSP (Liskov substitution principle)

Every subclass/derived class should be substitutable for their base/parent class.

Understanding “I” – ISP (Interface Segregation principle)

A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.

Understanding “D”- Dependency inversion principle

Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.

Implement BinarySearch with php


class BinarySearch
{
    private $start              = null;
    private $end                = null;
    private $calculatedLength   = null;
    private $elements           = array();
    private $searchingEliment   = null;



    /**
     * @param $searchEliment
     * @param array $eliments
     * @return int
     */
    public function search($searchEliment, array $eliments = array())
    {
        $this->searchingEliment = (int) $searchEliment;
        $this->elements         = $eliments;
        $totalElement           = count($this->elements);
        $currentElement         = current($this->elements);
        $this->start            = 0;
        $this->end              = $totalElement - 1;

        if (($totalElement == 0) || ($totalElement == 1
                && $currentElement != $this->searchingEliment))
            return -1;

        if ($totalElement == 1 && $currentElement == $this->searchingEliment)
            return $this->start;

        while (true) {

            $this->calculatedLength = $this->start + $this->end;

            if ($this->calculatedLength == 1) {
                if ($this->elements[$this->start] == $this->searchingEliment) {
                    return $this->start;
                } else if ($this->elements[$this->end] == $this->searchingEliment) {
                    return $this->end;
                } else {
                    return -1;
                }
            }

            $mid = ceil($this->calculatedLength / 2);

            if ($this->elements[$mid] == $this->searchingEliment)
                return $mid;

            if ($this->end == $mid)
                return -1;

            if ($this->elements[$mid] < $this->searchingEliment)
                $this->start = $mid;

            if ($this->elements[$mid] > $this->searchingEliment)
                $this->end = $mid;
        }

    }
}





class BinarySearchTest extends PHPUnit_Framework_TestCase
{

    public function testBinarySearchReturnIndex()
    {
        $binarySearch = new RequiresiveBinarySearch();
        $this->assertEquals($binarySearch->search(2, array(1, 2)), 1);


        $this->assertEquals($binarySearch->search(3, array()), -1);
        $this->assertEquals($binarySearch->search(3, array()), -1);

        $this->assertEquals(-1, $binarySearch->search(3, [1]));
        $this->assertEquals(0,  $binarySearch->search(1, [1]));

        $this->assertEquals(0,  $binarySearch->search(1, [1, 3, 5]));
        $this->assertEquals(1,  $binarySearch->search(3, [1, 3, 5]));
        $this->assertEquals(2,  $binarySearch->search(5, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(0, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(2, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(4, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(6, [1, 3, 5]));

        $this->assertEquals(0,  $binarySearch->search(1, [1, 3, 5, 7]));
        $this->assertEquals(1,  $binarySearch->search(3, [1, 3, 5, 7]));
        $this->assertEquals(2,  $binarySearch->search(5, [1, 3, 5, 7]));
        $this->assertEquals(3,  $binarySearch->search(7, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(0, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(2, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(4, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(6, [1, 3, 5, 7]));
        $this->assertEquals(4, $binarySearch->search(67, [1, 3, 5, 7, 67]));
        $this->assertEquals(-1, $binarySearch->search(8, [1, 3, 5, 7]));

    }


}

DecoratorPattern


interface DecoratorInterface
{
    /**
     * @return mixed
     */
    public function render();
}






class HTMLDecorator implements DecoratorInterface
{
    protected $book = null;

    public function __construct($book_object)
    {
        $this->book = $book_object;
    }

    public function render()
    {
        $properties = get_object_vars($this->book);

        echo '<ul>';
        foreach($properties as $key => $value) {
            echo '<li>' . $key . ' -- ' . $value . '</li>';
        }
        echo '</ul>';
    }
}




class JSONDecorator implements DecoratorInterface
{
    protected $book = null;

    public function __construct($book_object)
    {
        $this->book = $book_object;
    }

    public function render()
    {
        echo json_encode($this->book);
    }
}






class PatternTest {

    public $decorator;

    public function __construct(DecoratorInterface $decorator)
    {
        $this->decorator = $decorator;
    }
}


$book = new stdClass();
$book->title = "Patterns of Enterprise Application Architecture";
$book->author_first_name = "Martin";
$book->author_last_name = "Fowler";

echo '<h1>HTML Decorator</h1>';

$htmlDecorator = new HTMLDecorator($book);
$htmlDecorator->render();

echo '<h1>JSON Decorator</h1>';

$jsonDecorator = new JSONDecorator($book);
$jsonDecorator->render();



Problem solution of CodeWare

function createFebonacci(nth){  
  return Math.round((Math.pow(1.6180339, nth))/Math.sqrt(5));  
}

function createEvenFebonacci() {
  var nth = 0;
  var febo = 0;
  var result = 0
  var suquence = [];
  while(1) {
    febo = createFebonacci(nth++);
    console.log(febo);
    if (febo % 2 == 0) {
      suquence.push(febo);
    }
    if (febo > 4000000) {
      console.log(suquence);
	for (var i = 0; i < suquence.length; i++) {
	    result += sesuquence[i];				
	}	
      break;
    }
  }
   console.log(result);
}
createEvenFebonacci();



var capitals = function (word) {
	var indexs = [];
  for (i = 0; i < word.length; i++ ) {
    var charcter = word[i];
    if (charcter == word[i].toUpperCase()) {
      indexs.push(i);
    }
  }
  return indexs;
};






function Counter(){
  this.value = 0;
}

Counter.prototype.incr = function() {
  this.value++;
}

Counter.prototype.toString = function() {
  return this.value;
}



function isIsogram(str) {
  var charcters = [];
  for (var i = 0; i < str.length; i++) {
    if (typeof charcters[str.toUpperCase().charCodeAt(i)] == 'undefined')
        charcters[str.toUpperCase().charCodeAt(i)] = str[i]
    else 
      return false;        
  }
  return true;  
}



Implement function createTemplate which takes string with tags wrapped in {{brackets}}
as input and returns closure, which can fill string with data (flat object, where keys are tag names).

let personTmpl = createTemplate("{{name}} likes {{animalType}}");
personTmpl({ name: "John", animalType: "dogs" }); // John likes dogs

function createTemplate(template) {     
  
  return function(obj) {

    for (attr in obj) {      
      var pattern = new RegExp('{{' + attr + '}}', "g");      
      var matchText = pattern.test(template) ? obj[attr] : '' ;
      console.log(matchText);
      template = template.replace(pattern,matchText );             
    }        
    
    return template;
  }
}

var personTmpl = createTemplate("{{name}} likes {{animalType}}");
personTmpl({ names: "John", animalType: "dogs" }); // John likes dogs

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.


//an = a1 + (n - 1)d
//Sn = (n/2)(a1 + an)

function solution(number){  
    return getSum(3, number -1 ) + getSum(5, number- 1) + getSum(15, number- 1);
}
    
function getSum(difference,number) {  
  var frequency = Math.floor(number / difference);  
  var lastNumber = difference + (frequency - 1) * difference;
  return (frequency/ 2) * (difference + lastNumber);
}    

solution(19)

Law of demeter

Law of demeter Rules:(Method of an object is allowed to interact with )
1. Others method on its object
2. Method on propertise of the object
3. Method on arguments passed into the method
4. Method on instance of new objects created inside of the method

Function borrowing and currying

Function borrowing…..

var person = {
	firstName : "atik",
	lastName : 'haque'
	getName : function (){
		return this.fristName + "" + this.lastName;
	}
}

var newPerson = {
	firstName : 'kamal',
	lastName : 'khan' 
}

person.getName.call(newPerson);

Function currying…..

function MultipleBy(a,b) {
	return a * b;
}

var multipleByThree = MultipleBy.bind(this,3);
multipleByThree(5);

In javascript Creation phase and Execution phase

In javascript Creation phase and Execution phase. First phase is Creation phase.

In that phase create memory space for every variable and function that you write in your code.
So when the execution phase will run it can find it in memory.

And when the execution phase run it compile line by line and execute the code.Execution phase run single threaded Synchronous manner that means always execute single line at a time in order.