New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Implementing a strategy pattern

From: Object-Oriented Programming with PHP

Video: Implementing a strategy pattern

The final design pattern I'll demonstrate is the strategy pattern. A strategy pattern consists of a group of interchangeable algorithms that perform tasks, then a mechanism to choose which algorithm to use. That all sounds a bit complex, right? Let's apply it to an everyday task. When I get up in the morning, I need to decide what shirt I'm going to wear. I'll look at my stack of clothes. There is a RED SHIRT that's dirty and a BLUE SHIRT that's clean. For each shirt, I have to decide if it will work. I can't wear the RED SHIRT, because it's dirty, but I can wear the BLUE SHIRT, because it's clean.

Implementing a strategy pattern

The final design pattern I'll demonstrate is the strategy pattern. A strategy pattern consists of a group of interchangeable algorithms that perform tasks, then a mechanism to choose which algorithm to use. That all sounds a bit complex, right? Let's apply it to an everyday task. When I get up in the morning, I need to decide what shirt I'm going to wear. I'll look at my stack of clothes. There is a RED SHIRT that's dirty and a BLUE SHIRT that's clean. For each shirt, I have to decide if it will work. I can't wear the RED SHIRT, because it's dirty, but I can wear the BLUE SHIRT, because it's clean.

If both shirts are clean, I could prefer the RED SHIRT over the BLUE SHIRT. None are clean? I've run out of strategies, and now I am going to have to do laundry. In the Exercise Files, I've included an example of a strategy pattern for displaying an address. There are four files. First, the AddressDisplay class defines an interface with the methods that implementing classes must use for displaying an address. In particular, it has a Boolean method to determine if the strategy can be used, then the display method itself.

AddressDisplayNoCountry will cleanly render an address without a country. I am going to use this within other display classes. AddressDisplayFull builds upon the previous address, and displays a full address, including the country. This display method uses DisplayNoCountry to avoid duplicate code. Finally, AddressDisplayPark, which displays the address with a green background, with and without a country. I'm going to change the Address class to use the strategy pattern for display.

First, I need to add a constant for an error, in case there are no strategies available. Const ADDRESS_ERROR_NO_DISPLAY_STRATEGY = 1002. Then, after the property definitions, add a static property that will contain an array of class names of the display strategies. Order them by the least to most preferred. private static _display_strategies = array, AddressDisplayNoCountry, followed by AddressDisplayFull. And then, the most preferred.

AddressDisplayPark. After the display strategies, add a private property that will be used to store the last found display strategy. private _display_strategy. Next, go to the Display method, and remove the existing contents. Use the Lazy initialization Singleton pattern for determining which display strategy to use. If is_null this->_display_strategy foreach of the self _display_strategies as this strategy_class_name.

If the strategy is available, if strategy _class_name::isAvailable with a context of this, this->_display_ strategy = the strategy_class_name. If no strategies are available, throw an exception address using the error code defined earlier. throw new ExceptionAddress No display strategy found, followed by the error code. self::ADDRESS_ERROR_NO_DISPLAY_STRATEGY.

Finally, set a variable with the name of the display strategy, then call the static method for the display. return display_strategy::display $this. Save the Address class, then open the AddressPark class. Remove the overriding display method; it's no longer needed. Then, save AddressPark. Return to the browser, and refresh. Each address should display. Experiment with a demo by changing address types and data to see all the variations. In this chapter, I explored three different object-oriented design patterns that were used to build this application.

I started with a Singleton pattern, which limited the number of database connections, then moved on to the factory method pattern for creating addresses without having to know the subclass, and finally, the strategy pattern for intelligently choosing how to display an address. Of course, there are dozens of additional patterns that you can use. In the final chapter, I'm going to discuss some of the directions you can take in learning more about object- oriented PHP, which includes design patterns.

Show transcript

This video is part of

Image for Object-Oriented Programming with PHP
Object-Oriented Programming with PHP

37 video lessons · 17418 viewers

Jon Peck
Author

 
Expand all | Collapse all
  1. 4m 10s
    1. Welcome
      39s
    2. Exercise files
      2m 16s
    3. What you should know
      1m 15s
  2. 7m 47s
    1. What is an object?
      2m 6s
    2. What is a class?
      2m 7s
    3. Why should you use object-oriented programming?
      2m 14s
    4. The history of object-oriented PHP
      1m 20s
  3. 16m 40s
    1. Defining a class
      2m 58s
    2. Defining class properties
      3m 26s
    3. Creating a method and exploring object context with $this
      2m 50s
    4. Instantiating an object and accessing its contents
      3m 19s
    5. Specifying the visibility scope
      4m 7s
  4. 15m 51s
    1. What is a magic method, and do I need one?
      2m 23s
    2. Overloading property access
      6m 37s
    3. Customizing object construction
      4m 34s
    4. Standardizing object rendering as a string
      2m 17s
  5. 20m 54s
    1. Using the static keyword
      3m 36s
    2. Leveraging scope resolution operators
      1m 10s
    3. Setting constant values
      2m 47s
    4. Implementing static methods
      5m 43s
    5. Creating a database class
      7m 38s
  6. 26m 19s
    1. Extending your class
      6m 8s
    2. Abstracting classes
      5m 57s
    3. Sharing interfaces using polymorphism
      4m 39s
    4. Overriding methods, properties, and constants
      3m 25s
    5. Cloning and comparing objects
      2m 51s
    6. Referencing objects
      3m 19s
  7. 14m 52s
    1. Leveraging standard class objects
      2m 42s
    2. Retrieving objects from the database
      5m 41s
    3. Error handling with exceptions
      2m 6s
    4. Customizing PHP exceptions
      4m 23s
  8. 8m 2s
    1. Identifying the singleton pattern
      1m 42s
    2. Using the factory method pattern
      1m 51s
    3. Implementing a strategy pattern
      4m 29s
  9. 2m 57s
    1. Looking forward to namespaces
      47s
    2. Next steps
      1m 6s
    3. Goodbye
      1m 4s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.