Design Patterns

35
1 Design Patterns Daniel Waligóra Wrocław 09/01/2012

description

The presentation was created in the Apple Pages, and then converted to a MS PowerPoint format, due to that, on some slides may apper poor quality and ugly look.

Transcript of Design Patterns

Page 1: Design Patterns

1

Design Patterns

Daniel WaligóraWrocław 09/01/2012

Page 2: Design Patterns

2

Bibliography• Martin Fowler,Patterns of Enterprise Appication

Architecture

• Matt Zandstra , PHP5 Objects, Patters, and Practice

• http://www.ustream.tv - New York PHP channel

• Symfony Live Berlin 2012 - https://joind.in/event/view/1114

• http://scholar.google.pl

• http://pzielinski.com

Page 3: Design Patterns

3

Gang of Four

Page 4: Design Patterns

4

Breakdown Design Patterns by GoF

Design Design PatternsPatterns

creationcreationalal

structurstructuralal

behaviorbehavioralal

- abstract factory- builder- prototype

- decorator

- facade- composite

- observer

- strategy- command

Page 5: Design Patterns

5

Page 6: Design Patterns

6

Page 7: Design Patterns

7

Implementation related to the

contextprogrammiprogrammi

ng ng languagelanguage

scalabilityscalability

modularitymodularitytestable testable

(integration (integration test)test)

time-time-consumingconsuming

size of size of projectproject

Page 8: Design Patterns

8

Context Context ISIS related to the related to the programming programming

languagelanguage

Design Design patterns patterns IS IS NOTNOT related related

to the to the programminprogramming languageg language

Page 9: Design Patterns

9

Transaction Script1. class Hotel  2. {   3. private 4. $_gateway;

5.     public function __construct(Data_Access_Gateway $gateway)    6.     {    7.         $this->_gateway = $gateway;    8.     }    9.   10.     public function bookRoom($userId, $fromDate, $toDate)    11.     {    12.         $roomId = $this->_gateway->_getRoomIdBetweenDates($fromDate, $toDate);    13.   14.         if (!$roomId) {    15.             return false;    16.         }    17.   18.         $days = $this->_getAmountOfDays($fromDate, $toDate);    19.   20.         if ($days < = 7) {  21.             $price = $days * 100;  22.         } else {   23.             $price = $days * 80;  24.         }  25.           26.         $data = array(  27.             'userId' => $userId,    28.             'roomId' => $roomId,  29.             'fromDate' => $fromDate,    30.             'toDate' => $toDate,    31.             'price' => $price,    32.         );    33.   34.         $bookingId = $this->_gateway->insert('bookings', $data);    35.   36.         return $bookingId;    37.     }    38. } 

Page 10: Design Patterns

10

Transaction Script

• simple procedural model

•works well with a simple data access layer

• easy implementation of use cases

• difficult to maintenance

• code duplication

Disadvantages:Advantages:

Page 11: Design Patterns

11

Table Module #11. class Hotel  2. {    3.     public function __construct(Data_Access_Gateway $gateway, Booking $booking)    •     {    •         $this->_gateway = $gateway;  •         $this->_booking = $booking;  •     }    •   •     public function bookRoom($userId, $fromDate, $toDate)    •     {    •         $roomId = $this->_booking->getRoomBetweenDates($fromDate, $toDate);  •   •         if (!$roomId) {    •             return false;    •         }    •   •         $days = $this->_getAmountOfDays($fromDate, $toDate);    •   •         if ($days < = 7) {  •             $price = $days * 100;  •         } else {   •             $price = $days * 80;  •         }  •           •         $bookingId = $this->_booking-

>addBooking($userId, $roomId, $fromDate, $toDate, $price);    •   •         return $bookingId;    •     }    • }  •   

Page 12: Design Patterns

12

Table Module #21. class Booking  2. {    3.     public function __construct(Data_Access_Gateway $gateway)    4.     {    5.         $this->_gateway = $gateway;    6.     }  7.       8.     public function getRoomBetweenDates($dateFrom, $dateTo)  9.     {  10.        return $this->_gateway->getRoomBetweenDates($dateFrom, $dateTo);  11.    }  12.      13.    public function addBooking($userId, $roomId, $fromDate, $toDate, $price)    14.    {    15.        $data = array(  16.            'userId' => $userId,    17.            'roomId' => $roomId,  18.            'fromDate' => $fromDate,    19.            'toDate' => $toDate,    20.            'price' => $price,    21.        );    22.  23.        $bookingId = $this->_gateway->insert('bookings', $data);    24.  25.        return $bookingId;    26.    }    27.}  

Page 13: Design Patterns

13

Table Module vs Transaction Script

• less duplication

• encapsulation

•more organized and structured code

• easy implementation by technology support

•weak support for polymorphism

• no support ORM

Disadvantages:Advantages:

Page 14: Design Patterns

14

Domain Model #11. class Hotel  2. {    3.     protected $_hotelId;  4.     protected $_rooms;  5.       6.     public function bookRoom(User $user, $fromDate, $toDate)    7.     {    8.         $room = $this->_getRoomBetweenDates($fromDate, $toDate);  9.   10.         if (is_null($room)) {    11.             return false;    12.         }    13.   14.         $booking = $room->bookRoom(User $user, $fromDate, $toDate);  15.   16.         return $booking;    17.     }  18. }  19.   20. class Room  21. {  22.     protected $_roomId;  23.     protected $_bookings = array();  24.       25.     public function bookRoom(User $user, $fromDate, $toDate)  26.     {  27.         $days = $this->_getAmountOfDays($fromDate, $toDate);  28.           29.         if ($days < = 7) {  30.             $booking = new Booking($user, new ShortBookingStrategy($user, $days));  31.         } else {   32.             $booking = new Booking($user, new NormalBookingStrategy($user, $days));  33.         }  34.           35.         return $booking;  36.     }  37. } 

Page 15: Design Patterns

15

Domain Model #21. class NormalBookingPriceStrategy extends BookingPriceStrategy  2. {  3.     public function getPrice()  4.     {  5.         $price = $this->_days * 80;  6.           7.         if ($this->_user->isLoyal()) {  8.             $price = $price / 2;  9.         }  10.          11.        return $price;  12.    }  13.}  14.  15.class ShortBookingPriceStrategy extends BookingPriceStrategy  16.{    17.    public function getPrice()  18.    {  19.        return $this->_days * 100;  20.    }  21.}

Page 16: Design Patterns

16

Domain Model vs Procedural Pattern

• prevents logic duplication

•more code readability

• independence from the data source

•much easier to unit test

• time-consuming implementation

• additional patterns

- ORM

- data source

Disadvantages:Advantages:

Page 17: Design Patterns

17

SUMMARYprogrammiprogrammi

ng ng languagelanguage

scalabilityscalability

modularitymodularity

testable testable (integration (integration

test)test)

time-time-consumingconsuming

size of size of projectproject

skill of the developers

Page 18: Design Patterns

18

Don’t be STUPID,GRASP SOLID!

Page 19: Design Patterns

19

Sorry, but your code is STUPID!

Page 20: Design Patterns

20

1.class DB 2.{  3.    private static $instance;

4.  public static function getInstance()5.    {  6.        if(!isset(self::$instance)) {  7.            self::$instance = new self;  8.        }  9.          10.        return self::$instance;  11.    }  12.}  

•Singleton

21

Dupleton ?

Page 21: Design Patterns

21

•Singleton (ctd)1. class DB 2.{  3.    private static $instance;

•   public static function getInstance()•     {  •         if(!isset(self::$instance)) {  •             self::$instance = new self;  •         }  •           •         return self::$instance;  •     }  • }  

• class Order • {  •     protected $db;

•   public function __construct()•     {  •         $this->db = DB::getInstance();           •     }  • }

Page 22: Design Patterns

22

•Singleton (ctd)

1. class DB 2.{3. //body4.}

5. class Order 6.{  •     protected $db;

•   public function __construct(DB $db)•     {  •         $this->db = $db;           •     }  • }

Page 23: Design Patterns

23

•Tight Coupling

1.Order::buy();

1. class House 2.{3. public function __construct()• {• $this->door = new Door();• $this->window = new Window();• }• }

1. class House 2.{3. public function __construct(Door $door, Window

$window)• {• $this->door = $door;• $this->window = $window;• }• }

Page 24: Design Patterns

24

•Untestable Code

I donI don’’t t have a have a time!time!

Page 25: Design Patterns

25

Never Make CodeFaster Than Necessary,Something Important Is

Always Lost When You Do

•Premature Optimization

Page 26: Design Patterns

26

•Premature Optimization (ctd)

Performance Performance problemsproblems 20%20% of code of code

Page 27: Design Patterns

27

•Indescriptive Naming

char * strpbrk ( const char *, const char * );

??

Page 28: Design Patterns

28

•Indescriptive Naming (ctd)

Code is Read Far More Often Than Written

Page 29: Design Patterns

29

DRY (Don’t Repeat Yourself!)

KISS (Keep It Smile, Stupid!)

•Duplication

Page 30: Design Patterns

30

•Singleton

•Tight Coupling

•Untestable Code

•Premature Optimization

•Indescriptive Naming

•Duplication

Page 31: Design Patterns

31

•Single Responsibility Principle

•Open/Closed Principle

•Liskov Substitution Principle

•Interface Segregation Principle

•Dependency Inversion Principle

•Single Responsibility Principle

•Open/Closed Principle

•Liskov Substitution Principle

•Interface Segregation Principle

•Dependency Inversion Principle

Page 32: Design Patterns

32

Page 33: Design Patterns

33

Test Driven-Development

Page 34: Design Patterns

34

Advantages of Design Pattern?

•speed up the development process,

•helps to prevent issues that can cause major problems,

•patterns allow developers to communicate using well-known, well understood names for software interactions

Page 35: Design Patterns

35

EoTThank You