Software Design Patterns (2) four commonly used design patterns using php (singleton, factory, adapter & decorator)

Slides:



Advertisements
Similar presentations
Systems Architecture Use Case Diagram, System Overview, Class Diagram Design Patterns (weve used) Refactorings (weve used) Table of Contents.
Advertisements

Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Written by: Dr. JJ Shepherd
Copyright W. Howden1 Singleton, Wrapper, and Facade Patterns CSE 111.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Object-Oriented PHP (1)
March R McFadyen1 GoF (Gang of Four): Gamma, Johnson, Helm & Vlissides Book: Design Patterns: Elements of Reusable Object-Oriented Software.
1 Design patterns Lecture 4. 2 Three Important skills Understanding OO methodology Mastering Java language constructs Recognizing common problems and.
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Design Patterns.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
CSSE 374: Introduction to Gang of Four Design Patterns
Software Engineering 1 Object-oriented Analysis and Design Applying UML and Patterns An Introduction to Object-oriented Analysis and Design and Iterative.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
CPSC 372 John D. McGregor Module 4 Session 1 Design Patterns.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
CDP-1 9. Creational Pattern. CDP-2 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are –created –composed.
Creational Patterns
July 28, 2015IAT 2651 Design Patterns. “Gang of Four” July 28, 2015IAT 2652.
Singleton Duchenchuk Volodymyr Oksana Protsyk. 2 /48.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Object Oriented Programming
Design Patterns: Elements of Reusable Object- Orientated Software Gamma, Helm, Johnson, Vlissides Presented By: David Williams.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Design Patterns. 1 Paradigm4 Concepts 9 Principles23 Patterns.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns Introduction
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
CS 325: Software Engineering March 19, 2015 Applying Patterns (Part B) Code Smells The Decorator Pattern The Observer Pattern The Template Method Pattern.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
OOP Basics Classes & Methods (c) IDMS/SQL News
PROTOTYPE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Object-Oriented Concepts
Web Technology Solutions
GoF Patterns (GoF) popo.
MPCS – Advanced java Programming
Design Patterns – Chocolate Factory (from Head First Design Patterns)
Creational Pattern: Prototype
Chapter 11 Developing Object-Oriented PHP PHP Programming with MySQL Revised by A. Philipp – Spring 2010 (Rev SP’11)
CS240: Advanced Programming Concepts
Design Patterns in Game Design
null, true, and false are also reserved.
08/15/09 Design Patterns James Brucker.
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton design pattern
Singleton …there can be only one….
OO Design with Inheritance
CS 350 – Software Design Singleton – Chapter 21
Software Design Patterns (2)
Adapter Design Pattern
Design Patterns Imran Rashid CTO at ManiWeber Technologies.
CS 325: Software Engineering
Chapter 8 Class Inheritance and Interfaces
SPL – PS3 C++ Classes.
Presentation transcript:

Software Design Patterns (2) four commonly used design patterns using php (singleton, factory, adapter & decorator)

the singleton pattern (1) o when only one object needs to be responsible for a particular task. o exclusive resource with only one type of this resource. o most commonly used in PHP to limit connections to the database throughout the codebase. o singleton pattern considered a responsibility pattern because it delegates control for creation to a single point. o All singleton patterns have at least three common elements: - they must have a constructor, and it must be marked private - they contain a static member variable that will hold an instance of the class - they contain a public static method to access the instance

basic form: class Singleton { private static $instance = null; private static function __construct() { } public static function getInstance() { if(empty(self::$instance) { self::$instance = new Singleton(); } return self::$instance; } the singleton pattern (2)

the singleton pattern (3) class Database { private $_db; static $_instance; private function __construct() { $this->_db = mysql_connect('localhost', 'root', ''); mysql_select_db('phobias'); } private function __clone() {} public static function getInstance() { if(!(self::$_instance instanceof self)) { self::$_instance = new self(); } return self::$_instance; } public function query($sql) { return mysql_query($sql, $this->_db); }

$db = Database::getInstance(); $result = $db->query("SELECT * FROM phobias WHERE def LIKE '%pain%'"); while ($row = mysql_fetch_assoc($result)) { echo $row["term"].' : '. $row["def"].' '; } test singleton: run testview code the singleton pattern (4)

the factory pattern (1) o the factory pattern is a class that creates objects. o a factory is typically used to return different classes that conform to a similar interface. o usually, a factory pattern has one key ingredient: a static method, which is by convention named “factory”. o the static method may take any number of arguments and must return an object. o factories are critically important to the practice of polymorphic programming.

the factory pattern (2) basic form: class Driver { # The parameterized factory method public static function factory($type) { if (include_once 'Drivers/'. $type. '.php') { $classname = 'Driver_'. $type; return new $classname; } else { throw new Exception('Driver not found'); } # Load a MySQL Driver $mysql = Driver::factory('MySQL'); # Load an SQLite Driver $sqlite = Driver::factory('SQLite');

the factory pattern (3) interface DB { public function connect(); public function query(); public function disconnect(); } class DBmysql implements DB { public function connect() { //database connection stuff } public function query() { //perform database query stuff } public function disconnect() { //disconnect database } } class DBoracle implements DB { public function connect() { //database connection stuff } public function query() { //perform database query stuff } public function disconnect() { //disconnect database } }

the factory pattern (4) class DBfactory { public static $_DB; public static function &factory($szType = "") { if(!is_object(self::$_DB)) { switch($szType) { case 'mysql': self::$_DB = new DBmysql; break; case ‘oracle': self::$_DB = new DBoracle; break; default: self::$_DB = new DBmysql; break; } return self::$_DB; }

the factory pattern (5) db = DBfactory::factory("mysql"); $db->query(".."); DBfactory::factory()->query(".."); factory can now create different driver objects (default mysql):

aside : Type Hinting the factory pattern (6)

the adapter pattern (1) o the adapter pattern simply converts the interface of one class to what another class expects. o for this reason, it is often referred to as a "wrapper" pattern. o adapters are helpful when a class doesn't have quite the exact methods needed, and its not possible to change the original class. o the adapter can take the methods accessible in the original class, and adapt them into the methods needed.

the adapter pattern (2) class SimpleBook { private $author; private $title; function __construct($author_in, $title_in) { $this->author = $author_in; $this->title = $title_in; } function getAuthor() { return $this->author; } function getTitle() { return $this->title; }

the adapter pattern (3) class BookAdapter { private $book; function __construct(SimpleBook $book_in) { $this->book = $book_in; } function getAuthorAndTitle() { return $this->book->getTitle(). ' by '. $this->book->getAuthor(); } $book = new SimpleBook("Gamma, Helm, Johnson, and Vlissides", "Design Patterns"); $bookAdapter = new BookAdapter($book); echo 'Author and Title: '.$bookAdapter->getAuthorAndTitle(); run testview code

the decorator pattern (1) o the point of the decorator pattern is to enhance an object with some functionality without modifying the structure of the original object. o the decorator pattern is often used an example of the principle of preferring "composition over inheritance"

class Cupcake { public $Toppings = array('sprinkles' => 0, 'frosting' => 'none'); public function __construct($int, $str) { $this->Toppings['sprinkles'] = $int; $this->Toppings['frosting'] = $str; } abstract class Decorator_Wrapper { abstract function Add($mixed); abstract function Remove($mixed); } the decorator pattern (2)

class Sprinkle_Decorator extends Decorator_Wrapper { public function __construct(Cupcake $c) { $this->Cupcake = $c; } public function Add($int) { $this->Cupcake->Toppings['sprinkles'] += $int; } public function Remove($int) { $this->Cupcake->Toppings['sprinkles'] -= $int; } the decorator pattern (3)

the decorator pattern (4) class Frosting_Decorator extends Decorator_Wrapper { public function __construct(Cupcake $c) { $this->Cupcake = $c; } public function Add($str) { $this->Cupcake->Toppings['frosting'] = $str; } public function Remove($str) { echo "Hrmm.. We cant seem to remove your $str, it's stuck on the muffin!"; }

# Test the decorator pattern echo ' Make a new cupcake! '; $cupcake = new Cupcake(5, 'none'); print_r($cupcake->Toppings); echo ' Add more sprinkles! ' ; $sprinkle = new Sprinkle_Decorator($cupcake); $sprinkle->Add('55'); print_r($cupcake->Toppings); echo ' Remove 25 sprinkles! ' ; $sprinkle->Remove('25'); print_r($cupcake->Toppings); echo ' Add some frosting :) '; $frosting = new Frosting_Decorator($cupcake); $frosting->Add('Chocolate');print_r($cupcake->Toppings); the decorator pattern (5) run testview code