5 Design Patterns Explained

33
Design Patterns Design Patterns Introduction and Overview

Transcript of 5 Design Patterns Explained

Page 1: 5 Design Patterns Explained

Design Patterns

Design PatternsIntroduction and Overview

Page 2: 5 Design Patterns Explained

Introduction to Design Patterns : What are they? Types of Patterns Examples : Commonly used patterns

Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming – specifically pattern languages – and presented their results at the OOPSLA conference that year. In the following years, Beck, Cunningham and others followed up on this work.

Design Patterns

Page 3: 5 Design Patterns Explained

What are they? Idea originated from Christopher Wolfgang

Alexander (Austria). Architect It was initially applied for architecture for buildings

and towns, But not computer programming for writing software.

"Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the

same way twice”

Design Patterns

Page 4: 5 Design Patterns Explained

Even through he was talking about patterns in buildings and towns, What he says is true about object-oriented design patterns.

Solutions are expressed in terms of objects and interfaces instead of walls and doors.

At core both patterns is a solution to a problem in a context.

Simply, design patterns help a designer to get a right design faster

Design Patterns

Page 5: 5 Design Patterns Explained

Describes a design pattern as a three-part rule 1.) Description of a context 2.) A problem 3.) A solution

This is modified for software design patterns which consists of four parts : Pattern name

A handle to briefly describe the design problem,but more importantly to provide a common vocabulary for software designers to use.

Problem A description of the problem that the design pattern is intended to solve.

Design Patterns

Page 6: 5 Design Patterns Explained

Solution Describes what elements are required to make up

the design, their relationships and its context. Consequences

What are the results and trade offs by applying the design pattern.

Allows comparison between different design patterns, to see if there is a better fit for the actual problem.

Design Patterns

Page 7: 5 Design Patterns Explained

Types Of Patterns : Creational:

Concerned with everything about the creation of objects

Structural: Concerned with how classes and objects are composed

to form larger structures

Behavioral Concerned with algorithms and the assignment of

responsibilities between objects.

Design Patterns

Page 8: 5 Design Patterns Explained

Creational: Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case. Abstract Factory:

Groups object factories that have a common theme.

Builder constructs: Complex objects by separating construction and representation.

Factory Method: Creates objects without specifying the exact class to create.

Prototype: Creates objects by cloning an existing object.

Singleton : Restricts object creation for a class to only one instance.

Design Patterns

Page 9: 5 Design Patterns Explained

Structural Patterns: These concern class and object composition.They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality. Adapter:

Allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.

Bridge: Decouples an abstraction from its implementation so that the two can vary independently.

Composite: Composes zero-or-more similar objects so that they can be manipulated as one object.

Decorator: Dynamically adds/overrides behavior in an existing method of an object.

Facade: Provides a simplified interface to a large body of code.

Flyweight: Reduces the cost of creating and manipulating a large number of similar objects.

Proxy: Provides a placeholder for another object to control access, reduce cost, and reduce complexity.

Design Patterns

Page 10: 5 Design Patterns Explained

Behavioral Patterns: Most of these design patterns are specifically concerned with communication between objects. Chain of responsibility:

Delegates commands to a chain of processing objects.

Command: Creates objects which encapsulate actions and parameters.

Interpreter: Implements a specialized language.

Iterator : Accesses the elements of an object sequentially without exposing its underlying representation.

Mediator: Allows loose coupling between classes by being the only class that has detailed knowledge of their methods.

Memento: Provides the ability to restore an object to its previous state (undo).

Observer: Is a publish/subscribe pattern which allows a number of observer objects to see an event.

State : Allows an object to alter its behavior when its internal state changes.

Strategy: Allows one of a family of algorithms to be selected on-the-fly at runtime.

Design Patterns

Page 11: 5 Design Patterns Explained

Design Patterns

Architectural Pattern : MVC Pattern

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user

“Trygve Reenskaug introduced MVC into Smalltalk-76 while visiting Xerox Parc in the 1970s. In the 1980s, Jim Althoff and others implemented a version of MVC for the Smalltalk-80 class library. It was only later, in a 1988 article in The Journal of Object Technology, that MVC was expressed as a general concept.”

Page 12: 5 Design Patterns Explained

Design Patterns

Architectural Pattern : MVC Pattern

Components : The central component of MVC, the model, captures the behavior of the application in terms of its problem domain, independent of the user interface. The model directly manages the data, logic and rules of the application. A view can be any output representation of information, such as a chart or a diagram; multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. The third part, the controller, accepts input and converts it to commands for the model or view.

Page 13: 5 Design Patterns Explained

Design Patterns

Interactions :

In addition to dividing the application into three kinds of components, the model–view–controller design defines the interactions between them.

A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).

A model stores data that is retrieved to the controller and displayed in the view. Whenever there is a change to the data it is updated by the controller.

A view requests information from the model that it uses to generate an output representation to the user.

Page 14: 5 Design Patterns Explained

Design Patterns

Page 15: 5 Design Patterns Explained

Singleton Pattern : Creational In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

Before:: Index.php

include 'connection.php';

$object = new Connection();

$object2 = new Connection();

$object3 = new Connection();

connection.phpclass Connection

{

public function __construct()

{

echo 'This created a new object! <br />';

}

}

Design Patterns

Page 16: 5 Design Patterns Explained

Singleton Pattern After :: connection.php

class Connection

{

private function __construct()

{

echo 'This created a new object! <br />';

}

public static function getInstance()

{

static $instance = null;

if (null === $instance) {

$instance = new static();

} else {

echo 'This used the same object as before! <br />';

}

return $instance;

}

}

Design Patterns

Page 17: 5 Design Patterns Explained

Factory Pattern In object-oriented programming, a factory is an object for creating other objects – formally a

factory is simply an object that returns an object from some method call, which is assumed to be "new". More broadly, a subroutine that returns a "new" object may be referred to as a "factory", as in factory method or factory function. This is a basic concept in OOP, and forms the basis for a number of related software design patterns.

Before :: Index.php

include_once 'vehicle.php';

$car = new Car(4);

echo $car->getType();

echo '<br />';

$truck = new Truck(18);

echo $truck->getType();

Design Patterns

Page 18: 5 Design Patterns Explained

Before:: vehicle.php

class Vehicle

{

public function __construct($wheels = 0)

{

$this->wheels = $wheels;

}

public function getType()

{

return get_class($this);

}

}

class Car extends Vehicle { }

class Truck extends Vehicle { }

Design Patterns

Page 19: 5 Design Patterns Explained

After :: index.php

include_once 'vehicle.php';

$car = Vehicle::create('car', 4);

echo $car->getType();

echo '<br />';

$truck = Vehicle::create('truck', 18);

echo $truck->getType();

Design Patterns

Page 20: 5 Design Patterns Explained

After :: vehicle.php

class Vehicle

{

public static function create($type, $wheels)

{

switch($type) {

case 'car':

return new Car($wheels);

case 'truck':

return new Truck($wheels);

default:

return new stdClass();

}

}

public function getType()

{

return get_class($this);

}

}

class Car extends Vehicle { }

class Truck extends Vehicle { }

Design Patterns

Page 21: 5 Design Patterns Explained

Decorator : Structural Pattern In object-oriented programming, the decorator pattern (also known as

Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.

Before :: Index.php$book = new stdClass();

$book->title = "Patterns of Enterprise Application Architecture";

$book->author_first_name = "Martin";

$book->author_last_name = "Fowler";

echo $book->title . " is a book written by " . $book->author_first_name . " " . $book->author_last_name . "\n";

echo "But you will find the book under " . $book->author_last_name . ", " . $book->author_first_name . "\n";

Design Patterns

Page 22: 5 Design Patterns Explained

After : index.php

class PrettyPrint

{

protected $book = null;

public function __construct($book_object)

{

$this->book = $book_object;

}

public function getAuthor()

{

return $this->book->author_first_name . " " . $this->book->author_last_name;

}

public function getAuthorSortable()

{

return $this->book->author_last_name . ", " . $this->book->author_first_name;

}

}

Design Patterns

Page 23: 5 Design Patterns Explained

Index.php : contd...

$book = new stdClass();

$book->title = "Patterns of Enterprise Application Architecture";

$book->author_first_name = "Martin";

$book->author_last_name = "Fowler";

$bookFormatter = new PrettyPrint($book);

echo $book->title . " is a book written by " . $bookFormatter->getAuthor() . "\n";

echo "But you will find the book under " . $bookFormatter->getAuthorSortable() . "\n";

Design Patterns

Page 24: 5 Design Patterns Explained

Adaptor Pattern : In software engineering, the adapter pattern is a software design pattern that allows the interface of an

existing class to be used from another interface. It is often used to make existing classes work with others without modifying their source code.

Before :: index.php

require 'vendor/autoload.php';

$twilio = new Services_Twilio('fake username', 'fake password');

$message = $twilio->account->messages->sendMessage(

'+14085551234', // The number to send from, must be owned by your Twilio account

'+12125551234', // The number to send to

"Hello monkey!"

);

$sendgrid = new SendGrid('fake username2', 'fake password 2');

$email = new SendGrid\Email();

$email->addTo('[email protected]')->

setFrom('[email protected]')->

setSubject('My great subject line')->

setText('Hello World!')->

setHtml('<strong>Hello World!</strong>');

$sendgrid->send($email);

Design Patterns

Page 25: 5 Design Patterns Explained

After :: index.php

require 'vendor/autoload.php';

include_once 'notify.php';

$notify = new Notify('username', 'password');

$notify->send('17035551212', '15125551212', 'body of the message');

Design Patterns

Page 26: 5 Design Patterns Explained

After :: Notify.php

class Notify

{

protected $username = '' , $password = '';

public function __construct($username, $password) {

$this->username = $username;

$this->password = $password; }

public function send($to, $from, $body, $subject = '') {

if ('' == $subject) { // If there's no subject specified, let's assume we're sending a text message.

return $this->sendSMS($to, $from, $body);

} else {

return $this->sendEmail($to, $from, $body, $subject); } }

protected function sendSMS($to, $from, $body) {

$twilio = new Services_Twilio($this->username, $this->password);

$message = $twilio->account->messages->sendMessage( $from, $to, $body );

return $message; }

protected function sendEmail($to, $from, $body, $subject) {

$sendgrid = new SendGrid('fake username2', 'fake password 2');

$email = new SendGrid\Email($this->username, $this->password);

$email->addTo($to)->

setFrom($from)->

setSubject($subject)->

setText($body)->

setHtml($body);

return $sendgrid->send($email); } }

Design Patterns

Page 27: 5 Design Patterns Explained

Strategy Pattern : Behavioural Pattern In computer programming, the strategy pattern (also known

as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern

defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.

Strategy lets the algorithm vary independently from clients that use it. Strategy is one of the patterns included in the influential book Design Patterns by Gamma et al. that popularized the concept of using patterns in software design.

Design Patterns

Page 28: 5 Design Patterns Explained

Before :: Index.php include_once 'output.php';

$input = 10;

$output = new Output();

echo $output->square($input) . '<br />';

echo $output->cube($input) . '<br />';

echo $output->fourth($input) . '<br />'; Output.php

class Output

{

public function square($input)

{

return $input * $input;

}

public function cube($input)

{

return $input * $input * $input;

}

public function fourth($input)

{

return $input * $input * $input * $input;

}

}

Design Patterns

Page 29: 5 Design Patterns Explained

After :: Index.php

include_once 'output.php';

include_once 'square.php';

include_once 'cube.php';

include_once 'fourth.php';

$input = 10;

$output = new Output(new Square());

echo $output->display($input);

$output->setStrategy(new Cube());

echo $output->display($input);

$output->setStrategy(new Fourth());

echo $output->display($input);

Design Patterns

Page 30: 5 Design Patterns Explained

Output.php

class Output

{

protected $formatter = null;

public function __construct($formatter)

{

$this->formatter = $formatter;

}

public function setStrategy($formatter)

{

$this->formatter = $formatter;

}

public function display($input)

{

return $this->formatter->output($input);

}

}

Design Patterns

Page 31: 5 Design Patterns Explained

Design Patterns

Cube.php

class Cube

{

public function output($input)

{

return $input * $input * $input;

}

} Fourth.php

class Fourth

{

public function output($input)

{

return $input * $input * $input * $input;

}

}

Page 32: 5 Design Patterns Explained

Design Patterns

Square.php

class Square

{

public function output($input)

{

return $input * $input;

}

}

Page 33: 5 Design Patterns Explained