Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Design patterns - Common Solutions to Common Problems - Brad Wood

189 vues

Publié le

How unique is the problem you’re coding for right now? What’s the chance it’s been solved hundreds, maybe thousands of times? Is your solution the best way? You’ve no doubt heard other developers talk about using “design patterns”. These are reusable solutions to the problems that we all face as developers. The best thing is that most patterns can carry over from one language to another. It’s a great idea to familiarize yourself with these common solutions so you identify them and know when you plug them into your apps.

Let’s take a pragmatic look at exactly what design pattern are – and aren’t! The more you learn, the bigger toolbox you’re building that you can dip into to solve problems. You’ll also start to notice these familiar designs in frameworks and other people’s apps. Learning to recognize common patterns, their names, and when to use them will grow you as a developer, stretch your thinking outside the box, and make you better at what you do. A solid OO background will really help you, and most of what we cover will be generic to any language. Expect to cover some of the most common design patterns along with examples and their pros and cons with examples in CFML.

Publié dans : Technologie
  • Soyez le premier à commenter

Design patterns - Common Solutions to Common Problems - Brad Wood

  1. 1. Design Patterns COMMON SOLUTIONS TO COMMON PROBLEMS Brad Wood @bdw429s Ortus Solutions
  2. 2. Me ● Work for Ortus Solutions ● Developer Advocate ● Love rewriting Node code in CFML ● Lead developer of CommandBox CLI ● Live in Kansas City ● Musician ● 3 Ridiculously cute daughters ● Like eating spicy foods
  3. 3. Design Patterns
  4. 4. Software Craftsmanship
  5. 5. Design Patterns Christopher Alexander, architect Born in Vienna in the 30’s
  6. 6. Architectural Design Patterns
  7. 7. A Pattern Language 1977 book on architecture, urban design, and community livability The book creates a new language, what the authors call a pattern language derived from timeless entities called patterns. Patterns describe a problem and then offer a solution. (253 patterns)
  8. 8. What is a Pattern? “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.” Christopher Alexander
  9. 9. A Pattern Language 37 HOUSE CLUSTER 76 HOUSE FOR A SMALL FAMILY 159 LIGHT ON TWO SIDES OF EVERY ROOM
  10. 10. Gang of Four (GoF)
  11. 11. Design Patterns: Elements of Reusable Object-Oriented Software Inspired by Christopher’s work 23 programming patterns Written by the “Gang of Four” in 1994 ● Erich Gamma ● Richard Helm ● Ralph Johnson ● John Vlissides
  12. 12. Design Patterns: Elements of Reusable Object-Oriented Software Creational Patterns ● Abstract Factory ● Prototype ● Singleton
  13. 13. Design Patterns: Elements of Reusable Object-Oriented Software Structural Patterns ● Composite ● Decorator ● Facade
  14. 14. Design Patterns: Elements of Reusable Object-Oriented Software Behavioural Patterns ● Chain of Responsibility ● Iterator ● Strategy
  15. 15. Inspiration, not copy/paste examples “The examples are there for inspiration and explanation of the ideas in the patterns. They aren't canned solutions; in all cases you'll need to do a fair bit of work to fit them into your application.” Martin Fowler
  16. 16. Let’s look at some examples
  17. 17. Object Factory https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)
  18. 18. Object Factory ● An object that creates other objects ● Abstracts details of how the final objects are created ● Removes creation code from inside object to separate concerns ● Often used with the dependency injection pattern ● CFML Examples are WireBox or DI/1
  19. 19. Object Factory component { function buildDog() { var oDog = new Dog(); oDog.setBreed( ‘Mutt’ ); return oDog; } } DogFactory.cfc
  20. 20. Object Factory var rover = dogFactory.buildDog();
  21. 21. Singleton https://sourcemaking.com/design_patterns/singleton
  22. 22. Singleton ● Ensure class only has one instance ● Provide global access to this instance ● Just-in-time initialization ● Often times doesn’t hold state ● Object must be thread safe!
  23. 23. Singleton function onApplicationStart() { application.myService = new models.myService(); }
  24. 24. Strategy https://sourcemaking.com/design_patterns/strategy
  25. 25. Strategy ● Define a family of algorithms ● Each one is encapsulated and interchangeable ● Often times each strategy implements an interface ● Each implementation can be different ● Strategies can be chosen at runtime ● Strategy in use is invisible to the program
  26. 26. Strategy logger.setAppender( new fileAppender() ); logger.logMessage( ‘This is my message’ ); logger.setAppender( new dbAppender() ); logger.logMessage( ‘This is my message’ );
  27. 27. Decorator https://sourcemaking.com/design_patterns/decorator
  28. 28. Decorator ● Add responsibilities to a class dynamically ● Alternative to subclassing (not really an “is-a”) ● Decorator wraps original class ● Wrapping can be recursive ● Can be applied at runtime ● User of class does not know (or care) if it’s been decorated
  29. 29. iceCream = new iceCream(); iceCream.make(); sprinkledIceCream = new sprinklesDecorator( iceCream ); sprinkledIceCream.make(); Decorator
  30. 30. Adapter https://sourcemaking.com/design_patterns/adapter
  31. 31. Adapter ● Modify the API of a class to be different ● Can “adapt” a class to work in another system ● Wraps the original class with a new interface ● Allows greater reuse ● Doesn’t modify original class
  32. 32. Adapter oldCache = new oldCacheEngine(); oldCache.retrieve( ‘item’ ); adaptedCache = new cacheAdapter( oldCache ); adaptedCache.get( ‘item’ );
  33. 33. Front Controller https://en.wikipedia.org/wiki/Front_controller
  34. 34. Front Controller ● A single point of entry for a web app ● Simplifies URL routing ● Makes global concerns like security checks easier ● Utilizes a controller to dispatch to the appropriate handler ● Usually index.cfm in CFML apps
  35. 35. Front Controller yoursite.com/index.cfm?event=main.index
  36. 36. Chain of Responsibility https://sourcemaking.com/design_patterns/chain_of_responsibility
  37. 37. Chain of Responsibility ● You have a large or dynamic list of handlers that need to respond to a request ● You don’t want to couple the sender to the responders ● Creates a pipeline of linked handlers ● Each handler calls the next link in the chain ● A handler can abort the chain by not calling the next handler
  38. 38. Chain of Responsibility function securityHandler( request ) { if( !request.params.authenticated ){ throw ‘Not logged in’! } // Pass control to the next link in the chain request.proceed(); }
  39. 39. Memento https://sourcemaking.com/design_patterns/memento
  40. 40. Memento ● Capture and externalize an object's internal state ● Can be used to “snapshot” an object ● Can be used to restore an object to a previous state ● Great for serialization ● Can include composed objects
  41. 41. Memento oUser = userService.loadUser( id=123 ); currentUserState = oUser.getMemento(); // Later on... oUser.setMemento( previousUserState );
  42. 42. Observer (publish/subscribe) https://sourcemaking.com/design_patterns/observer
  43. 43. Observer (publish/subscribe) ● Defines “events” that are broadcast ● Defines zero or more observers who are listening to those events ● Promotes decoupling of a large system ● Listener can receive data about the event that has happened ● Bind listeners at runtime for dynamic behaviors ● Don’t call us, we’ll call you!
  44. 44. Observer (publish/subscribe) $.ajax({ url: "test.html", context: document.body }).done(function() { $( this ).addClass( "done" ); });
  45. 45. Double Checked Locking https://en.wikipedia.org/wiki/Double-checked_locking
  46. 46. Double Checked Locking ● Protects creation of a shared resource with multithreading ● Reduces overhead of acquiring exclusive locks by first performing a read-only check ● If creation is required, only then is an exclusive lock acquired ● Once a thread has the exclusive lock, the check is performed a second time to ensure another thread hasn’t completed it ● Ensures thread safety without excessive locking
  47. 47. Double Checked Locking if( isDefined( 'data' ) ){ return data; } lock name="generateData" type="exclusive" timeout=60 { if( isDefined( 'data' ) ){ return data; } data = produceData(); return data; }
  48. 48. Anti-patterns (Avoid these!)
  49. 49. Anemic Domain Model https://en.wikipedia.org/wiki/Anemic_domain_model
  50. 50. Anemic Domain Model ● When domain model is too “thin” and lacks any behavior ● Beans are only value objects with no behavior present ● Services are empty, meaning business logic has probably ended up in your controllers or views ● Creates excessive classes ● Bloats application code
  51. 51. Anemic Domain Model component accessors=true { property name=’name’; property name=’age’; property name=’department’; }
  52. 52. God Object https://sourcemaking.com/antipatterns/the-blob
  53. 53. God Object ● A class with too much responsibility ● API is watered down with many unrelated methods ● Usually happens over time as code is added and never refactored ● Hard to maintain and test ● Lazy domain design and lack of planning
  54. 54. God Object util = new generalControllerUtil(); util.createOrder(); util.addUser(); util.login(); util.runScheduledTasks(); util.orderPizza();
  55. 55. Premature Optimization https://shreevatsa.wordpress.com/2008/05/16/premature-optimization-is-the-root-of-all-evil/
  56. 56. Premature Optimization ● Coding early-on for perceived efficiency ● Sacrificing good design, maintainability ● Often times overstating a negligible speed improvement ● Sometimes “proven” by a flawed “loop test” ● The “root of all evil” -- Donald Knuth
  57. 57. Improbability Factor https://en.wikipedia.org/wiki/Improbability_factor
  58. 58. Improbability Factor ● Leaving known bugs in your system because they’re “not likely to happen” ● Gambling with fate to save time and be lazy ● This is just inviting Murphy’s Law to come into full effect ● Can bite you later at the worst possible time
  59. 59. Improbability Factor reportService.runAsyncReport(); // Meh, this should be enough sleep( 5000 ); fileRead( ‘/reports/sales.pdf’ );
  60. 60. Honorable Mentions
  61. 61. Law of Demeter https://en.wikipedia.org/wiki/Law_of_Demeter
  62. 62. Law of Demeter ● Principle of least knowledge ● A unit of software should have limited knowledge about the other units ● Software units should talk to friends and not to strangers ● Keeps low coupling between systems ● Rule of thumb: be careful accessing methods on objects obtained from other objects (the “dot” rule)
  63. 63. Law of Demeter orderCity = cart .getOrder() .getOrderDetails() .getUser() .getAddress() .getCity() .getName();
  64. 64. Law of Demeter orderTaxRate = cart.getOrderTaxRate();
  65. 65. Principle of Least Astonishment https://en.wikipedia.org/wiki/Principle_of_least_astonishment
  66. 66. Principle of Least Astonishment (POLA) ● Applies to UI and software design ● "If a necessary feature has a high astonishment factor, it may be necessary to redesign the feature” ● User controls should have a consistent behavior ● Predictable software is easier to use ● Basically, don’t make your users go “WTF!?”
  67. 67. Principle of Least Astonishment (POLA) // Has side effect of removing all login history user.getAPIKey();
  68. 68. Brook’s Law https://en.wikipedia.org/wiki/Brooks%27s_law
  69. 69. Brook’s Law ● “Adding manpower to a late software project makes it later" ● Coined by Fred Brooks in his 1975 book The Mythical Man-Month ● Software development is knowledge work, and not fungible ● Throwing devs at a project will slow it down at first ● A larger team has more points of contact ● If 1 woman can have a baby in 9 months, it doesn’t mean 9 women can have a baby in 1 month
  70. 70. Resources
  71. 71. Head First Design Patterns: A Brain-Friendly Guide
  72. 72. Software Architecture Design Patterns in Java
  73. 73. https://sourcemaking.com/design_patterns
  74. 74. Thanks for coming! Contact me ● brad@bradwood.com ● www.codersrevolution.com ● @bdw429s ● Ortus Solutions

×