Chapter 7 Review:

• What is a design pattern? What are the four components of a design pattern definition? (See page 214.)

Design patterns are abstract concepts of OOP that describe broad methodologies for dealing with class structure to suit a particular scenario. The four components are:

  1. Name (23 kinds - we looked at Singleton, Composite, Factory, Strategy).
  2. Discussion of the problem. The circumstances that might apply to a pattern.
  3. Solution - note the code, but enough structure and key methods that help implement usable code).
  4. Consequences: Pros and Cons of using a particular pattern.

• What is the GoF? (See page 215.)

The Gang of Four is a group of folks who wrote the seminal book on using design patterns in programming. The godfathers of OOP?

• What is the Singleton pattern? Under what circumstances is it useful? How does the Singleton pattern ensure a single instance of a class type? (See pages 216 and 217.)

A Singleton pattern is where only one instance of an object is needed. Thus, the "single" part of Singleton. It is useful for things like config files and database connections. It "checks" to see if an instance is created, and if so then uses the current instance, and if not, creates one.

• What is the Factory pattern? Under what circumstances is it useful? How does the Factory pattern generate new objects? (See page 220.)

A Factory pattern will create new objects as necessary. Useful when it is not known at program creation time some of the future object creation needs. The syntax for generation new objects is via a static function that creates a new class within the static function based on some kind of validation or evaluation of the $type as per below. Thus,

class Factory {

static function Create($type, $attribs_or_array){

//code to validate and determine what $type should be, ie switch statement

return new SomeNewClassbasedon_$type($attribs_or_array);

}

• What is the Composite pattern? Under what circumstances is it useful? How do you design a Composite pattern? (See page 225.)

Composite pattern is structural in that it builds and adds functionality to potentially similar objects. The build/design example given is form fields, vs form. It builds from an abstract base class and then extends into other classes similar or same functionality (this may need some help...).

• What is the Strategy pattern? Under what circumstances is it useful? How do you design a Strategy pattern? (See page 233.)

The strategy pattern is designed to change an algorithm on the fly, versus the object type on the fly like a Factory/creation type. Could be useful for applying operations throughout a site where similar characteristics apply to different objects. The example given is string filtering. .

 

Toggle Sidebar