Advanced Object-oriented Design Patterns Creational Design Patterns.
5 Design Patterns Explained
-
Upload
prabhjit-singh -
Category
Software
-
view
52 -
download
4
Transcript of 5 Design Patterns Explained
Design Patterns
Design PatternsIntroduction and Overview
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
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
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
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
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
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
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
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
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
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.”
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.
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.
Design Patterns
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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;
}
}
Design Patterns
Square.php
class Square
{
public function output($input)
{
return $input * $input;
}
}