142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Head-First-Design-Patterns-PHP
2 |
3 | ## Head First Design Patterns : A Brain-Friendly Guide book examples code in PHP
4 |
5 | ---
6 |
7 | **The original code in the book is in java.**
8 |
9 | **I chose this book because it has a really unique way of describing things and making them easy to understand maybe somebody else will find it useful.**
10 |
11 | ---
12 |
13 | ## Run the code
14 |
15 | First you have to generate the auto loader with composer
16 |
17 | note: __*Do this step for each folder that have composer.json within*__
18 |
19 | > *All examples are tested with php7.2*
20 |
21 | ``` bash
22 | $ composer dump-autoload
23 | $ php index.php
24 | ```
25 |
26 | e.g: if we want to run the `simUDuck` example of chapter 1 `ch01` then
27 |
28 | ``` bash
29 | 1. $ cd /ch01/simUDuck
30 | 2. $ composer dump-autoload
31 | 3. $ php index.php
32 |
33 | ```
34 |
35 | ---
36 |
37 | ## Notes index
38 |
39 | * [chapter 1 : Strategy Pattern](#ch1)
40 |
41 | * [chapter 2 : Observer Pattern](#ch2)
42 |
43 | * [chapter 3 : Decorator Pattern (Design Eye for The Inheritance Guy)](#ch3)
44 |
45 | * [chapter 4 : Factory method , Abstract factory , Dependency Inversion](#ch4)
46 |
47 | * [chapter 5 : Singleton](#ch5)
48 |
49 | * [chapter 6 : Command pattern](#ch6)
50 |
51 | * [chapter 7 : The Adapter and The Facade Patterns](#ch7)
52 |
53 | * [chapter 8 : Template Method Pattern [Encapsulating Algorithms]](#ch8)
54 |
55 | * [chapter 9 : The Iterator and Composite Patterns **Well-Managed Collection**](#ch9)
56 |
57 | * [chapter 10 : The State Pattern *The State of Things* ](#ch10)
58 |
59 | * [chapter 11 : The Proxy Pattern *Controlling Object Access* ](#ch11)
60 |
61 | ---
62 |
63 | # MY-NOTES
64 |
65 | ---
66 |
67 |
68 |
chapter 1: Strategy Pattern
69 |
70 | `aka Policy Pattern`
71 |
72 | > Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior.
73 |
74 | __more formal definition:__
75 |
76 | > The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.
77 | > Strategy lets the algorithm vary independently from
78 | clients that use it.
79 |
80 | ## Strategy pattern used when
81 |
82 | Strategy pattern is used when we have multiple algorithms for specific task and the client decides the actual implementation to be used at runtime.
83 |
84 | ### Notes
85 |
86 | * `CHANGE` is the one constant in software development.
87 |
88 | * The Example in the book shows that when inheritance hasn’t worked out very well, since the behavior keeps changing across the subclasses and it's not appropriate for all subclasses to have those behaviors, The interface solution sounds promising and can be done in PHP using [Traits](https://www.php.net/manual/en/language.oop5.traits.php) but cant be done in java because java have no code reuse so in java if there's a change you have to track down all the subclasses where that behavior is defined *probably introducing new bugs along the way!*
89 |
90 | > 1.Design Principle **Enacapsulate** :
91 | > Identify the aspects of your application that vary and separate them from what stays the same.
92 | > Another way to think about this principle:
93 | > take the parts that vary and encapsulate them, so that later you can alter or > extend the parts that vary without affecting those that don’t.
94 |
95 | * Encapsulate what change and you will have flexible system.
96 |
97 | * Separate the code that will be changed.
98 |
99 | * When you have subclasses that differ in a behavior(s) pull out what varies and (encapsulate) create new set of classes to represent each behavior.
100 |
101 | > 2.Design Principle :
102 | > Program to an **interface** not an implementation
103 | > *An interface in this context could also refers to an abstract class or class that implements particular behavior*
104 |
105 |
106 | * Use an interface to represent each behavior and Each implementation of a *behavior* will implement one of those interface.
107 |
108 | * if you can add more behaviors without modifying any of the existing behavior classes or touching any of the superclasses we've achieved a good strategy design pattern.
109 |
110 | * Represent the behavior of things and not the thing. themselves
111 |
112 | * Think of *set of behaviors* as a *set of algorithms*.
113 |
114 | > 3.Design Principle :
115 | > Favor composition over inheritance
116 |
117 | * creating systems using composition gives you a lot more flexibility. it lets you encapsulate a family of algorithms into their own set of classes, and lets you change behavior at runtime as long as the object you’re composing with implements the correct behavior interface.
118 |
119 | * The principles and patterns can be applied at any stage of the
120 | development lifecycle.
121 |
122 | * Design patterns don’t go directly into your code, they fi rst go into your BRAIN.
123 |
124 | 
125 |
126 | * The secrets to creating maintainable OO systems is thinking about how they might change in the future.
127 |
128 | ---
129 | Strategy Pattern examples:
130 |
131 | * SimUDuck app
132 |
133 | * Bounce+ **ShoppingCart example is not from the book**
134 |
135 | ---
136 |
137 |
138 |
chapter 2: Observer Pattern
139 |
140 | `aka Pub/Sub`
141 |
142 |
143 | According to GoF, observer design pattern intent is;
144 |
145 |
146 | > Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
147 |
148 | ### Observer used when
149 |
150 | State changes in one or more objects should trigger behavior in other object
151 | one-to-many relationship between objects so that when one object changes state all it's dependents are notified and updated automatically.
152 |
153 | PHP provides Stander PHP Library (SPL) Observer Pattern through [SplObserver interface](http://php.net/manual/en/class.splobserver.php) and [SplSubject interface](http://php.net/manual/en/class.splsubject.php)
154 |
155 | Model-View-Controller (MVC) frameworks also use Observer pattern where _Model_ is the __Subject__ and _Views_ are __observers__ that can register to get notified of any change to the model.
156 |
157 | ### The Power of Loos Coupling
158 |
159 | When two objects are loosely coupled, the can interact, but have very little knowledge of each other.
160 |
161 | The Observer Pattern provides an object design where subject and observers are loosely coupled.
162 |
163 | >4. Design Principle :
164 | > STRIVE FOR LOOSELY COUPLE DESIGN BETWEEN OBJECT THAT INTERACT
165 |
166 | * best usage when there's single source of truth one object with many unknown dependents.
167 |
168 | * This single source of truth is an Object's state that's many objects care of knowing it.
169 |
170 | * defines one-to-many relationship between objects.
171 |
172 | * the Publisher aka the **Subject** updates the observer using common interface.
173 |
174 | * the Subscribers aka the **Observers** are loosely coupled and the subject no nothing about then except that they are implement the observer interface.
175 |
176 | ---
177 |
178 |
179 |
chapter 3 : Decorator Pattern (Design Eye for The Inheritance Guy)
180 |
181 | > Attaches additional responsibilities to an object dynamically.
182 |
183 | > Decorators provide a flexible alternative to sub-classing for existing functionality.
184 |
185 |
186 | Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors.
187 |
188 | >5. Design Principle : (The Open-Closed Principle) :
189 | > Classes should be open for extensions, but closed for modifications.
190 |
191 |
192 | ### Decorator used when
193 |
194 | Decorator pattern is best used when we introduced to existing code that we want to extend its functionality, Or when we want to extend the functionality for the clients without exposing the code.
195 |
196 | Since Decorators are basically wrappers around objects PHP I/O classes same as Java I/O uses decorator pattern to add more functionality to the stream. read more on [Wrappers in php](http://php.net/manual/en/wrappers.php) and you can register a custom wrapper (decorators) to add your own filter/wrapper to I/O stream. @see [this example](https://github.com/LionRoar/Head-First-Design-Patterns-PHP/tree/master/ch03/PHP_IO_DECORATOR) on chapter 03.
197 |
198 | * Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.
199 |
200 | * Inheritance makes static behavior but Composition make the behavior dynamic and it can change at runtime .
201 |
202 | * Decorator gives the object new responsibility/functionality dynamically at runtime by using composition.
203 |
204 | * It's Vital for Decorators to have the same type (superclass/interface) as the objects the are going to decorate/wrap.
205 |
206 | * Decorator reduce the chance of bugs and side effects in legacy code.
207 |
208 | * General speaking design patterns add abstraction level that's in result adds some level of complexity to the code, that's why we should always use it on the parts that changes and don't overusing it.
209 |
210 | * Decorators can result in many small objects in our design, and overuse can be complex.
211 |
212 | * Introducing Decorators can increase the complexity of the code; because not only you need to instantiate the component, but also wrap it with (n) number of decorators this can be tackled by using `Factory` and `Builder` Patterns.
213 |
214 | ---
215 |
216 |
217 |
chapter 4 : The Factory Pattern
218 |
219 | `Factory method , Abstract factory , Dependency Inversion ?`
220 |
221 | ## Contents
222 | 1. Factory Method Pattern.
223 | 2. Abstract Factory Pattern.
224 |
225 | There's more to making objects than just using the `new` operator, instantiation is an activity that shouldn't always done in public and can often lead to `coupling problems`.
226 |
227 | The Problem : When you have a code that requires you to make a lot of concrete classes this code probably will need to add new classes and thus will NOT be `Closed for Modification`.
228 |
229 | All Factory Patterns encapsulate object creation.
230 |
231 | ## The Factory Method Pattern
232 |
233 | > The Factory Method Patter defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
234 |
235 | The Factory Method Pattern encapsulates object creation by letting subclasses decide what objects to create.
236 |
237 | A Factory Method handles the object creation and encapsulates it in a subclass.
238 |
239 | 
240 |
241 | ```php
242 |
243 | +----------------------+
244 | | PizzaStore | <- [abstract creator]
245 | +----------------------+ <- abstract class defines
246 | | | abstract factory method `createPizza()`
247 | |abstract createPizza()| that the sub-class implements to produce product.
248 | | |
249 | | orderPizza() |
250 | | | +-------+
251 | +-----^--------------^-+ | Pizza |<-------+
252 | | | +-^-----+ |
253 | | | | |
254 | | |_______ | |
255 | | | | |
256 | | | | |
257 | [concrete creator] [concrete creator] | |
258 | +---------+------+ +------------------+ +------------------+ |
259 | | NYPizzaStore | |ChicagoPizzaStore | |ChicagoCheesePizza| |
260 | +----------------+ +------------------+ +--------^---------+ |
261 | | createPizza() | | createPizza() | | |
262 | | | | +--[creates]->>-+ |
263 | +-------------+--+ +------------------+ |
264 | [creator] | [creator] +-------------+ |
265 | +---------------------[creates]--->>|NYCheesePizza|---------+
266 | +-------------+
267 |
268 | ```
269 |
270 | ### Factory Method Pattern used when
271 |
272 | When there's a need to make a lot of concrete classes or a desire to add new concrete classes in the future we isolate the creation of the classes to an abstract method in an abstract class to obligate the creation to the subclasses.
273 |
274 | In other words it's used to decouple your client code from the concrete classes you need to instantiate, or if you don’t know ahead of time all the concrete classes you are going to need
275 |
276 | ---
277 |
278 | >6. Design Principle : The Dependency Inversion Principle
279 | > Depend upon abstraction. Do not depend upon concrete classes.
280 |
281 | #### **Dependency Inversion Principle**
282 |
283 | `Depend upon abstractions. Do not depend upon concrete classes.`
284 |
285 | * High-level components should not depend on low-level components; rather, they should _both_ depend on abstractions.
286 |
287 | * Instantiation is an activity that should not be in public and can often lead to coupling problems.
288 |
289 | * `new` keyword __===__ an Implementation _(not an Interface)_.
290 |
291 |
292 | * Factory method lets subclasses decide what class instantiate not because it allows rather than it does not know the product .
293 |
294 | * **Strive for guidelines** `The following guidelines can help you avoid OO designs that violate the Dependency Inversion Principle` :
295 |
296 | 1. **No variable should hold reference for a concrete class.** If you use `new` you’ll be holding a reference to a concrete class, Use a factory to get around that
297 |
298 | 1. **No class should derive form concrete class.** If you derive from a concrete class, you’re depending on a concrete class. Derive from an abstraction, like an interface or an abstract class.
299 |
300 | 1. **No method should override method on base class.** if so then the base class not really an abstraction. If you override an implemented method, then your base class wasn’t really an abstraction to start with. Those methods implemented in the base class are meant to be shared by all your subclasses.
301 |
302 | ---
303 |
304 | ## Abstract Factory Pattern
305 |
306 | Abstract Factory encapsulates the creation of a `family` of products by providing an interface for the product creation.
307 |
308 | > Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
309 |
310 | 
311 |
312 | 
313 |
314 | The methods of an Abstract Factory are implemented as **factory methods**.
315 |
316 | ### Abstract Factory Pattern used when
317 |
318 | it's used to construct objects such that they can be decoupled from the implementing system.
319 | The pattern is best utilized when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.
320 |
321 | whenever you have families of products you need to create and you want to make sure your clients create products that belong together.
322 |
323 | * The methods of the **Abstract Factory** are often **Factory Methods**.
324 |
325 |
326 | ---
327 |
328 | * The job of an Abstract Factory is to define an interface for creating a set of products.
329 |
330 | * Both the **Abstract factory** and **Factory method** are great in terms of decoupling application from specific implementations.
331 |
332 | * **Factory method** create objects using (inheritance), while **Abstract Factory** creates objects using (composition). that means to create object using Factory method you need to *extend* class and override a factory method, and for the Abstract Factory it provides an abstract type for creating family of products subclasses define how those products are created and to use the factory you instantiate it and inject it to code written against the abstract type.
333 |
334 | ---
335 |
336 |
337 |
chapter 5 : Singleton
338 |
339 | > The singleton pattern ensures a class has only one instance and provide global access to it .
340 |
341 | The one, only and unique object.
342 |
343 | * The Singleton Pattern ensures you have at most one instance of a class in your application.
344 |
345 | * The Singleton Pattern also provides a global access point to that instance.
346 |
347 | ### Singleton Pattern used when
348 |
349 | When we only need one object such as: thread pools, caches, dialog boxes, objects that handle
350 | preferences and registry settings, objects used for logging, and objects that act as device drivers to devices like printers and graphics cards, for many of these types of objects, if we were to instantiate more than one we’d run into all sorts of problems like incorrect program behavior, overuse of resources, or inconsistent results.
351 |
352 | We use the singleton pattern in order to restrict the number of instances that can be created from a resource consuming class to only one.
353 |
354 | Resource consuming classes are classes that might slow down our website or cost money. For example:
355 |
356 | Some external service providers (APIs) charge money per each use.
357 | Some classes that detect mobile devices might slow down our website.
358 | Establishing a connection with a database is time consuming and slows down our app.
359 |
360 | ### Singleton **violates** the *Single Responsibility Principle* “One Class, One Responsibility”
361 |
362 | ```
363 |
364 | The singleton pattern is probably the most infamous pattern to exist, and is considered an anti-pattern because it creates global variables that can be accessed and changed from anywhere in the code.
365 |
366 | Yet, The use of the singleton pattern is justified in those cases where we want to restrict the number of instances that we create from a class in order to save the system resources. Such cases include data base connections as well as external APIs that devour our system resources.
367 |
368 | ```
369 |
370 | I encourage you to read more about the Singleton pattern [in this article by Joseph Benharosh](https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php)
371 |
372 | ---
373 |
374 |
chapter 6 : Command Pattern
375 |
376 | ```also sometimes called the Action Pattern or Transaction Pattern```
377 |
378 | > Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
379 |
380 | * Decouples the requester of an action from the object that preform that action.
381 | * Encapsulates the requests as an object `(command object)`.
382 | * A Command object is at the center of this decoupling and encapsulates a receiver with its action `method` (or set of actions).
383 |
384 | ### The command pattern used when
385 |
386 | It's used for history tracking, to implement logging and transactional systems, also used to Simplify Distributed System [Read more](https://docs.microsoft.com/en-us/archive/msdn-magazine/2004/september/distributed-system-design-using-command-pattern-msmq-and-net)
387 |
388 | Also The Command Pattern has evolved with alternative designs,`Architectural Patterns` such as `CQS` [(Command-query Separation)](https://martinfowler.com/bliki/CommandQuerySeparation.html) and `CQRS` [(Command Query Responsibility Segregation)](https://martinfowler.com/bliki/CQRS.html) and in their context the command basically a message and the new pattern called called `Command Bus` / `Simple Bus` [Read more](https://matthiasnoback.nl/2015/01/a-wave-of-command-buses/)
389 |
390 |
391 | * BOUNCE Example: Using command in transactional manner **The `BankTransaction` example is not from the book**
392 |
393 | * Extra Tips : A `NULL Object` is an object that implements an interface to do nothing, is useful when you don't have meaningful object to `return` and yet you want to remove the responsibility of handling `NULL` from the client.
394 |
395 | ---
396 |
397 |
The Adapter and The Facade Patterns
398 |
399 |
400 | ## Adapter Pattern
401 |
402 | `aka Wrapper Pattern`
403 |
404 | > **The Adapter Pattern** converts the interface of a class into another interface the client expects. Adapters lets classes work together that couldn't otherwise because of incompatible interfaces.
405 |
406 | ### Adapter Pattern used when
407 |
408 | When a class that you need to use doesn't meet the requirements of an interface.
409 | Exposed to legacy code may encounter an old interface needs to be converted to match new client code *Adapters* allows programming components to work together that otherwise wouldn't because of mismatched interfaces.
410 |
411 | Adapter pattern motivation is that we can reuse existing software if we can modify the interface.
412 |
413 | #### There are two kinds of Adapters
414 |
415 | 1. **Class Adapter**
416 | *uses `inheritance`* [multiple inheritance] *not supported in *java* nor *php*.
417 | can only wrap a class It cannot wrap an interface since by definition it must derive from some base class.
418 |
419 | 1. **Object Adapter**
420 | *uses `Object composition`* composition and can wrap classes or interfaces, or both. It can do this since it contains, as a private, encapsulated member,the class or interface object instance it wraps.
421 |
422 | > "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)
423 |
424 | * DON'T MIX _DECORATORS_ WITH _ADAPTERS_ THEY'RE BOTH WRAPPERS BUT
425 | _DECORATORS_ ADD NEW RESPONSIBILITIES WHILE _ADAPTERS_ CONVERT AN INTERFACE.
426 |
427 | ---
428 |
429 | ## Facade Pattern
430 |
431 | > The Facade Pattern provides a unified interface to a set of interfaces in subsystem. Facade defines a higher-level interface that make the subsystem easier to use.
432 |
433 | ### Facade used when
434 |
435 | when you want to simplify a complex system.
436 |
437 | * Facades don't encapsulate .
438 | * Facade Pattern allows to avoid tight coupling between client and subsystem.
439 |
440 | * **Design Principle**
441 | Principle of Least Knowledge - talk only to your immediate friends.
442 | `{Least Knowledge principle} aka Law of Demeter`
443 |
444 | Least Knowledge principle guidelines :
445 | * take any object.
446 | * from any method on that object we should only instantiate :
447 | * The object itself.
448 | * Objects passed as a parameter to the method.
449 | * Any object the method creates or instantiate.
450 | * Any components of the object *by instance variable **has-A-relationship***.
451 | * NOT TO CALL METHODS ON OBJECTS THAT WERE RETURNED FROM ANOTHER METHODS!.
452 |
453 |
454 | ```PHP
455 |
456 | $Q = "What’s the harm in calling the method of an object we get back from another call?"
457 |
458 | $A = "if we were to do that, then we’d be making a request
459 | of another object’s subpart (and increasing the number of objects
460 | we directly know). In such cases, the principle forces us to ask
461 | the object to make the request for us; that way we don’t have
462 | to know about its component objects
463 | (and we keep our circle of friends small)."
464 |
465 | ```
466 |
467 | Without the principle
468 |
469 | ```PHP
470 |
471 | public function getTemp() : float {
472 | $thermometer = $this->station->getThermometer();
473 | //we get thermometer OBJECT for
474 | //the station then we call get temperature
475 | return $thermometer->getTemperature();
476 | }
477 |
478 | ```
479 |
480 | With Least Knowledge principle
481 |
482 | ```PHP
483 |
484 | public function getTemp() : float {
485 | //we add a method to the station class with
486 | //that we reduce the number of classes we're dependent on
487 | return $this->station->getTemperature();
488 | }
489 |
490 | ```
491 |
492 | ### Wrappers
493 |
494 | PATTERN | INTENT
495 | ---------|---------
496 | Decorator|Doesn't alter the interface but adds responsibilities.
497 | Adapter |converts one interface to another.
498 | Facade |Makes an interface simpler.
499 |
500 |
501 | ---
502 |
503 |
504 |
505 |
506 |
507 | ### Template Method Pattern
508 |
509 | `aka Hollywood pattern`
510 |
511 | > The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
512 |
513 |
514 |
515 | It's all about creating `Template` form an `Algorithm`
516 |
517 | ```PHP
518 |
519 | $q = "What's a `Template` ?"
520 |
521 | $a = "it's just a method that defines an algorithm as steps"
522 |
523 | ```
524 |
525 |
526 | ### Hooked on Template
527 |
528 | A **Hook** is a method that declared in the abstract class but given an empty on default implementation ; giving the subclass the ability to `hook into` _override_ the algorithm on various points.
529 |
530 | When to use what ?
531 | `abstract methods` _VS_`hooks.`
532 | use __abstract methods__ when the implementation is a __MUST__ in the subclass.
533 | for the __hooks__ it's optional for the subclass.
534 |
535 |
536 | ### Hollywood Principle
537 |
538 | > Don't call us, we'll call you.
539 |
540 | * **Hollywood principle** helps prevents `Dependency rot`. huh ..what!?
541 |
542 | * **Dependency rot:** it's bad and a mess !
543 | it's when high-level components depending on low-level components depending on high-level components ...and so on.
544 | it's hard to understand system with such a flaw.
545 |
546 |
547 | * **Hollywood principle :** is a `Technique` for building frameworks or components so that low-level components can be `Hooked` into the computation without creating dependency between the low-level components and high-level components.
548 |
549 | * **Hollywood principle** guides us to put `decision-making` in high-level modules that can decide how and when to call low level modules.
550 |
551 | * **The Factory Method is a specialization of Template Method**
552 |
553 | ### Who does what ?
554 |
555 | Pattern | Description
556 | ----------------|-------------
557 | Template Method | Subclasses decide how to implement steps in an algorithm.
558 | Strategy | Encapsulate interchangeable behavior and use delegation to decide which behavior to use.
559 | Factory Method | Subclasses decide which concrete classes to create.
560 |
561 | #### Bounce
562 |
563 | another great example from [journaldev](https://www.journaldev.com/1763/template-method-design-pattern-in-java)
564 |
565 | to understand the method template pattern
566 |
567 | > suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. The important point is that the **we can’t change the order of execution** because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.
568 |
569 |
570 | ### Template Method Pattern used when
571 |
572 | * Template Methods are frequently used in general purpose frameworks or libraries that will be used by other developer.
573 | * When the behavior of an algorithm can vary but not the order.
574 | * When there's a code duplication *this is always gives a clear sign of bad design decisions and there's always room for improvement*.
575 |
576 |
577 | ---
578 |
579 |
580 |
The Iterator and Composite Patterns [Well-Managed Collection]
581 |
582 | ## Iterator Pattern
583 |
584 | > The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
585 |
586 | * Iterator provide a standard way *common interface* to traverse through a group of Objects *aggregate*.
587 | * Iterator allows access to an aggregate's elements without exposing its internal structure.
588 | ### checkout iterator branch for iterator implementation
589 |
590 | ```bash
591 |
592 | $ git checkout iteratorPattern
593 | Switched to branch 'iteratorPattern'
594 |
595 | ```
596 |
597 | 
598 |
599 | * The **Aggregate** defines an interface for the creation of the Iterator object.
600 | * The **ConcreteAggregate** implements this interface, and returns an instance of the ConcreteIterator.
601 | * The **Iterator** defines the interface for access and traversal of the elements, and the **ConcreteIterator** implements this interface while keeping track of the current position in the traversal of the Aggregate.
602 |
603 | ### Iterator used when
604 |
605 | * When you need access to elements in a set without access to the entire representation.
606 | * When you need a uniform traversal interface, and multiple traversals may happen across elements.
607 |
608 |
609 | ---
610 |
611 | ### implementations notes
612 |
613 | Unlike java , PHP Array can be treated as an array, list, hash-table, stack, queue, dictionary, collection,...and probably more.
614 |
615 | The original example uses both Java Array and ArrayList.
616 |
617 | #### PHP implementation specifics
618 |
619 | For the sake of **`Objectville`** example :
620 | * I will use [SplFixedArray](http://php.net/manual/en/class.splfixedarray.php) to mimic (static)fixed size arrays.
621 | * We will ignore the fact that both **normal php `array`** and **`SplFixedArray`** implement the [Traversable *interface*](http://php.net/manual/en/class.traversable.php)
622 | and that both can be easily traversed using a [`foreach`](http://php.net/manual/en/control-structures.foreach.php).
623 | * You cannot implement `Traversable` interface it's an abstract base interface, you can't implement it alone but you can implement interfaces called [`Iterator`](http://php.net/manual/en/class.iterator.php) or [`IteratorAggregate`](http://php.net/manual/en/class.iteratoraggregate.php) By implementing either of these interfaces you make a class `iterable` and `traversable` using `foreach`
624 | * For the sake of this example we're going to make our own interface and we call it `IteratorInterface`.
625 |
626 | ---
627 |
628 | ### Single Responsibility Principle (**S**OLID)
629 |
630 | > A Class should have only one reason to change.
631 |
632 | Separating responsibilities in design is one of the most difficult things to do, to succeed is to be diligent in examining your designs and watchout for signals that a class is changing in more than one way as your system grows.
633 |
634 | `We should strive to assign only one responsibility to each class.`
635 |
636 | ---
637 |
638 |
639 | ## The Composite Pattern
640 |
641 | > The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
642 |
643 | 
644 |
645 | ```
646 |
647 | The << Component >> abstract class define all objects in composed system.
648 | The Leaf has no children.
649 | The Composite contains components.
650 |
651 | ```
652 |
653 | * Composite pattern comes into play when developing a system where a component could either be an individual object or a representation of a collection of objects.
654 |
655 | * Composite pattern provides a structure to hold both individual objects an composites.
656 |
657 | * A **Component** is any object in a **Composite structure**.
658 |
659 | * **Components** may be other *composites* or *leaf* nodes.
660 |
661 | * Remember to balance `transparency` and `safety`.
662 |
663 |
664 | ## Is `Composite Pattern` really follow the single responsibility principle
665 |
666 | The Composite Pattern
667 |
668 | 1. manages a hierarchy
669 |
670 | 1. performs operations related to Menus
671 |
672 | that's __2__ responsibilities.
673 |
674 | The Composite Pattern trades **Single Responsibility Principle** for *transparency*
675 |
676 | Transparency: Since the Composite interface contain child management operations and the leaf _(items non iterable)_ operations The client can treat both the composites and leaf nodes uniformly, both are _transparent_ to the client.
677 |
678 | Having both operations in the Component class will cause a bit loss of *safety* because the client might try to do Composite related operation e.g _add_ to a leaf _item_ which is invalid.
679 |
680 |
681 | ## Composite Pattern used when
682 |
683 | * Graphics frameworks are the most common use of this pattern.
684 | * The Composite pattern is frequently used for abstract syntax tree representations.
685 | * when dealing with tree structures *Anything that can be modelled as a tree structure can be considered an example of Composite*.
686 | * when you have collection of objects with whole-part relationships and you want to be able to treat those objects uniformly.
687 |
688 | ### `what's whole-part relationships ?`
689 |
690 | also known as `aggregation relationship` it's a relationship between two classes in which one represent the larger class (whole) that consists of smaller classes (parts)
691 |
692 | ---
693 |
694 | * We call components that contain other components `composite objects` and components that don't contain other components `leaf objects`.
695 |
696 | * By treating objects uniformly that means there's a common methods can be called on both `composite` or `leaf` that implies that both must have the same `interface`.
697 |
698 | ---
699 |
700 | ### Who does what ?
701 |
702 | Pattern | Description
703 | ----------------|-------------
704 | Strategy | Encapsulate interchangeable behavior and use delegation to decide which behavior to use.
705 | Adapter | Changes the interface of one or more classes.
706 | Iterator | Provides a way to traverse a collection of objects without exposing the collection's implementation.
707 | Facade | Simplifies the interface of a group of classes.
708 | Composite | Clients treat collections of objects and individual objects uniformly.
709 | Observer | Allow a group of objects to be notified when some state changes.
710 |
711 | ---
712 |
713 |
chapter 10: The State Pattern *The State of Things*
714 |
715 | > Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.
716 |
717 | ---
718 |
719 | 
720 |
721 | * The **Context** have number of internal states.
722 | * The **State** << interface >> defines a common interface for all concrete states.
723 | * Each *Behavior* correspond with **ConcreteState** implements its own logic for the request.
724 | * When **Context** changes state a different **ConcreteState** associate with it.
725 | * Simply change the state object in context to change the behavior.
726 |
727 | This is similar to **Strategy Pattern** except changes happens internally rather than the client deciding the strategy.
728 |
729 | key-points:
730 | Think of Strategy Pattern as a flexible alternative to sub-classing.
731 | Think of State Pattern as an alternative to putting lots of conditionals.
732 |
733 | ## State Pattern used when
734 |
735 | * You need a class to behave differently based on some condition.
736 | * If you are using *if-else* condition block to perform different actions based on the state.
737 |
738 | ### Who does what ?
739 |
740 | Pattern | Description
741 | ----------------|-------------
742 | State | Encapsulate state-based behavior and delegate behavior to the current state.
743 | Strategy | Encapsulate interchangeable behavior and use delegation to decide which behavior to use.
744 | Template Method | Subclasses decide how to implement steps in an algorithm.
745 |
746 | ---
747 |
748 |