Category Archives: SOFTWARE DESIGN PATTERN

State Pattern – Design Pattern

The state pattern allows an object to alter its behavior. When its internal states changes, the object itself will appear to change its class

This pattern encapsulates states in to separate classes and delegate to the object representing current state.

Change in class is done by using composition over the base class (in our example Context Class’s property currentState)

Here, what we are trying to do is that attaching a subclass behavior based on previous actions performed on that object (In our case it will be Context class’s currentState property object assigned, that we will see in our example ).

<?php

// class being called to test our program
class Test
{
    public $context ;
    
    
    public function testnow()
    {
        $this->context = new Context;

        $this->context->requestOne();    // Could be any methods
        $this->context->requestTwo();

        print_r($this->context);
        $this->context->requestOne();    // Could be any methods

        // here you may see the changes in underlying classes on execution of any mathod 
        // if it tries to change it's current state, and change in state of current object will be responsible for changing the underlying state class.
        
    }
    
}


//Context   -- main class being called

Class Context {
    
    public State $StateA;
    public State $StateB;
    public State $StateC;
    public State ... ;// More state classes may involve depend on the behavior of game.

    public State $currentState; // depicting the current state of a Game
    
    public function __construct()
    {
         $this->StateA = new StateA($this);
         $this->StateB = new StateB($this);
         $this->StateC = new StateC($this);
         ...

         $this->currentState = new StateA($this); // suppose default state initailly
    }
    
    function requestOne()
    {
        ...
        $this->currentState->requestOne(); // will be calling the methods of 'currentState' assigned class, may be any of state classes.
    }

    function requestTwo()
    {
        ...
        $this->currentState->requestTwo(); // will be calling the methods of 'currentState' assigned class, may be any of state classes.
    }

    function requestThree()
    {
        ...
        $this->currentState->requestThree(); // will be calling the methods of 'currentState' assigned class, may be any of state classes.

    }

}



interface State
{
    // All these methods needs to be implemented by the class
    public function requestOne();
    public function requestTwo();
    public function requestThree();
} 


//Whenever there is a request made using class Context, its request mthod delegate(propagetes) to state subclass (e.g. StateA) , to handle the behavior of object.


class StateA implements State {

    public function requestOne()
    {
        ...
        ...
        //changing state classes if there needed
    }


    public function handleTwo()
    {
        ...
        ...
        //changing state classes if there needed
    }


    public function handelThree()
    {
        ...
        ...
        //changing state classes if there needed
    }

}

//Similarly for other classes like StateB, StateC, and so on..


class StateB implements State 
{
    
    // All methods similar to method StateA class methods
    // and additional methods may exist there too.
}

This kind of a pattern can be useful in designing Games especially, where an object behavior changes based on its previous operations.

Hope that make a little bit clear.

Composite Pattern – Design Pattern

Composite-pattern

Composite-pattern

Consider Iterator Pattern, this behaves very well if all items in a collection are equal kind, But it lacks when it comes to iterate over such a collection where all items or a few can contain a nested structure(Tree structure).

To traverse a tree, We need to visit every node(may contain further node or leaf) and leaf. So here we come of with another pattern named Composite Pattern. That works perfectly with Iterator pattern to make the job of Iteration simple for a client without knowing about underlying structure of every object in collection(Aggregate), whether it’s node or a leaf. In simple terms we can say that it will help to provide the interface that will be common for both nodes as well as leaf items, client has not to worry about object structure, that is being passed.

The Composite pattern allows you to compose objects into tree structure,to represent part-whole hierarchies. Composite lets treat individual objects and compositions of objects uniformly.

Here part-whole term is referring to each node(either a leaf or a node connected with other nodes as a parent)

Using composite structure, we can apply the same operation over both Composites(here NODEs) and individual(here LEAF) objects.

In short we are ignoring the difference between Composites(NODE) and individual(LEAF).

Iterator Pattern – Design Pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

The iterator pattern allows traversal of elements of an aggregate without exposing the underlying implementation.

It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation, and places the responsibility where it should be.

one thing to notice here

Aggregate or Collection means just a group of objects, they might be stored in very different data structures like lists, arrays, hashmaps, vectors etc.

This pattern comes in the scenario when we have a different kind of collections, and we need to traverse over them in a different class, class separate from implementing collections data.

below is diagram explaining iterator pattern.

iterator-pattern

iterator-pattern

Facade Pattern – Design Pattern

facade

Intent of facade is to provide the ease of use to any library(subsystem) through a an interface/class.

The Facade Pattern provides a unifide interface to a set of Interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.

Here We can take example of a complex theater system. For playing a movie we may need to set a different programs of each subsystem, Now We can look at facade is some thing like that reduces steps in performing a task, rather than tuning each individual program to work.

In below example TheaterFacade object makes easier to operate programs.

<?php
class TheaterFacade {
    public $dvd, $music, $movie, $player;

    public function TheaterFacade(DVD $dvd, Music $music, Movie $movie, Player $player)
    {
        $this->dvd = $dvd;
        $this->music = $music;
        $this->movie = $movie;
        $this->player = $player;
    }

    public function playMovie($movieName)
    {
        $this->music->setMusic(7);
        $this->movie->setMovie($movieName);
        $this->player->play();
        ...
        ...
    }

    public function stopMovie()
    {
        $this->music->stopMusic();
        $this->player->stop();
        ...
        ...
    }

}

class Music {
    
    public function setMusic($volume)
    {
      //setting volume function
    }

    public function stopMusic()
    {
      //stop function
    }
}

class Player {
    public function play(){
       //play function
    }

    public function stop(){
       //stop player function
    }

}

class Movie {

    public function setMovie ($movie) {
        //set movie to play
    }
}

Adapter pattern – Design Pattern

adapter pattern

Lets Have a Look at adapter pattern definition, that states clearly about its use case.

The Adapter pattern converts the interface of a class into another Interface that client expect. Adapter lets classes work together that could not just because of incompatible interfaces

lets have a look at below code that will give you a better idea.

<?php

class ENumeration Implements Iterator {

    protected $enumobj; // will hold the Adaptee class instance

    public function ENumertion(Enum enumObject)
    {
        $this->enumobj = enumObject;
    }

    public function hasNext()
    {
        return $this->enumobj->hasNextElement();

        //NOTE here hasNextElement method is lying in Enum class, call to hasNext() is being tranfered to Enum class objects hasNextElement() method.
    }

    public function next()
    {
        return $this->enumobj->getNextElement();
        
        //NOTE here getNextElement method is lying in Enum class, call to next() is being tranfered to Enum class object's getNextElement() method.
    }

}

Now any call using Enumeration class object will be calling Enum class methods, so acting as an adapter to Enum class, caller class doesnot know that it call is being transfered to Enum class.

Hope above example make sense, although if you have any query you can connect with me over comments or by any means.

Command Pattern – Design Pattern

Commands gives us a way to package a piece of computation(a receiver and a set of actions) and pass it around as a first-class object.
Now, computation may be invoked long after some client application creates the command object.

The process of invoking a command may be done by a different thread. We can take this scenario and apply it to many useful applications such as schedulers, thread pools, and job queues etc.

For understanding command object, Let’s have a example of queue system in Laravel( A php framework ), Queues come to picture when you need to perform a task in background, without affecting the end user experience like as sending a bulk e-mail, or preparing a file to download that will be available after few minutes based on request of end user. In this case we just take the input from end user, what it wishes to do and without completing that request we just intimate to user that specific response will be available or done after a few minutes, mean while what application does, it stores Jobs( implementing queue system methods) or command object, in a database or some other structures depending on your driver configured for queue system.
and then in background we have set some threads that picks the command objects(JOBS) from its pool and gets executed its handle method. As all commands have implemented the Interface that is having handle method, and at time of calling its execute method it calls handle on the command object(JOB class).

We can summarize command pattern as below.

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable(undo) operations.

It enables encapsulating a request by binding together a set of actions on a specific receiver.

Singleton Pattern – Design Pattern

A Singleton pattern ensures a class has only instance, and provides a global point access to it.

For detailed overview we can have a look at below code flow, We are having a Singleton class having private constructor, that can’t be instantiated directly by outsider class using new operator. For instantiating this class we need to call class’s method.

public function callProgram () {
    ....
    neededInstance = Singleton.getInsatnce(); // will be returning object of singleton class.
    ....
    ....
}


public class Singleton {
    
    private static Singleton uniqueInstance ;

    //constructor of a class
    private Singleton() {

    }

    public static Singleton getInsatnce() {
        if ( uniqueInstance == null) {
            synchronized (Singleton.class) {
                if ( uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }

        return uniqueInstance;
    }
}

Factory Pattern – Design Pattern

Factory Pattern Method encapsulates object creation. The factory method encapsulate object creation by letting subclasses decide what objects to create.


One thing to notice here, class being called(in our case concreteProduct) for instantiating the Object is independent of class that is calling, means to say both of them are unknown to each other, they know only the contract(in our case Product ), with which they will be interacting, Here product interface is contract that is known to both of them, but createrClass does not know that It is interacting with concreteProduct class object, it only know that object which it got from its subclass factory is of type Product, Rest information about object is encapsulated here.

<?php

class createrClass{
    
      function factoryMethod() ;  --> Abstract method
      
      function anOperation()
      {
          
      }
}

class concreteCreator extends createrClass{
        
    //implemented method (responsible for creating objects)
    function factoryMethod()
    {
    }

}

//Interface For concreteProduct class,
interface Product{

}


//class for Object being created by subclass(concreteCreator) method factoryMethod 
class concreteProduct implements Product{ 
 
}

All type of concreteProduct subclasses must implement this interface so that concreteCreator’s factoryMethod only has to know about Product interface type and no more info about subclass that is being instantiated to create Object of specific type

Hope it makes clear picture about factory pattern.

Decorator Pattern – Design Pattern

Today We will be discussing about decorator pattern. Question arises what is decorator pattern what is need of such pattern, where we can implement it.

Consider a Restaurant or simply coffee shop, where you have lot of menu items and some of items are customizable as per the need of customer. and prices varies as per the commodities involved in making it.

In this scenario we can not provide all price options just by inheriting a class, subclass each behavior and extending each class with some super class ? Why just due to commodity prices varies, and you can’t go every time to update it in code, and each customer may want different amount of commodities involved in making of that customized item(e. g. A coffee having high amount of coffee and involving no sugar, without milk)

In this scenario Decorator pattern comes to picture. Which allows us to attaches additional responsibilities to an object(In our case Coffee may be our object) dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The Decorator Pattern provides an alternative to subclassing for extending behavior. It involves a set of decorator classes that are used to wrap concrete components.

Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)

Decorator changes behavior by adding new functionality before and/or after (or even in place of) method calls to the component.

You can think of some kind like it works on chaining principle, that an object can be wrapped multiple time by Another object and vice versa, as both of then are using the Same parent type of object in there constructor.

 

What is design pattern and benefits of adopting it.

A design pattern comes in to picture, when you are designing a project that may come with vital changes(An obious nature of software projects) in your flow depending on customers needs.

Sometimes it’s easy a add a new feature in your application, and some time it becomes difficult due to its impact on the system to add a new feature changes, although it may be too small from a users point of view.

So main use of design pattern comes to picture in identifying how you will be designing your application of a specific domain, so that it can adopt changes(means to add a new features easily from programming point of view) easily to your application, without affecting previous functionalities.

So What comes main things while designing a software from a software architect point of view.

1- Identifying objects and there interactions.

2- How frequent the behavior is going to be changed for an object in your application.

3- How a new object may come in to picture (probably adding a new feature)

4- How it will be serving to end users(speed, accuracy, user traffic load etc.).

 

Above described parameters may help to any software architect/programmer to design a system that can easily incorporate changes as well.

It may look some time that a particular practice is not being followed in your project scenarios, that is ok, sometimes its your design patterns need, as your project design pattern have to be focused mainly on how well it can adopt changes as well as how it will be serving to end users.