A random collection

Archive for the ‘design-patterns’ Category

TECH: Head First DP

Design Toolbox

OO Basics
  1. Abstraction
  2. Encapsulation
  3. Polymorphism
  4. Inheritance
OO Principles
  1. Encapsulate what varies
  2. Favor composition over inheritance
  3. Program to interfaces, not implementations
OO Patterns
  1. Strategy – defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it

Good Design

Encapsulate to Handle Change
Independent parts
Loose coupling
Information Hiding
Design by Contract
Open/Closed Principle (OCP) – open for extension, but closed for modification
SOLID principles: (SRP, OCP, LSP, ISP, DIP)
Single Responsibility Principle (SRP)
Liskov substitution principle (LSP)
Interface segregation principle (ISP)
Dependency inversion principle (DIP)
  1. Intro to Design Patterns (Strategy Pattern)
    • Starts with designing a Duck class hierarchy with
    • Need to add a “fly” feature to some ducks. Puts it in base class, Duck, but that leads to all Duck subtypes getting the behavior.

      Lesson: A localized update to the code caused a non-local side effect (flying rubber ducks)
    • Take out “Flyable” and “Quackable” into separate interfaces, subtypes implement these interfaces. Since these are interfaces, each subclass implementing these interface need to provide implementation of “fly()”, “quack()” methods – no reuse of code. There may be different types of “fly(), quack()” behaviors, causing us to create a separate subclass that implements the behavior differently (will need many combinations of subclasses)

      Lesson: Inheritance is not solving the problem. No reuse with interface approach – Will need to implement the interface functions in all the subclasses that implement it.

    • Design Principle: Identify the aspects of your application that vary and separate them from what stays the same.

      Take what varies/changes and “encapsulate” it so it won’t affect the rest of the code when you later alter/extend the varying parts. Fewer unintended consequences from code changes, more flexibility in the systems.

    • “fly()”, “quack()” are the varying parts of the Duck class that vary across ducks. Separate these behaviors into a new set of base classes – FlyingBehavior, QuackingBehavior
    • Design Principle: Program to an interface (supertype), not an implementation
    • Design Principle: Favor Composition over Inheritance

      Composition gives you more flexibility. It lets you encapsulate a family of algorithms into their own set of classes, but it also lets change behavior at run time (example by setting/changing the flyBehavior object).

    • Add 2 instance variables “flyBehavior, quackBehavior” to Duck and delegate its “performFly(), performQuack()”. Set the “flyBehavior, quackBehavior” variables to concrete objects in the constructors of Duck subclasses to get desired behavior for the subclass, and add setter methods for setting them.

      Lesson: Now it is a lot easier to add new Duck subclasses (example ModelDuck) and new Fly behavior (say RocketPoweredFly)

    • Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
    • I created this broadcast class. It keeps track of all the objects listening to it and anytime a new piece of data comes along it sends a message to each listener. The listeners can join the broadcast at any time or they can even remove themselves. It is really dynamic and loosely coupled. Sounds like Observer Pattern
  2. Keeping your objects in the know (Observer Pattern)
    • Design Principle: Strive for loosely coupled designs between objects that interact
    • Observer defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  3. Decorating Objects
    • Design Principle: Classes should be open for extension but closed for modification – Open-Closed principle
    • Decorator – attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality
  4. Baking with OO Goodness – Abstract Factory, Factory Methods
  5. One of a Kind Objects – Singleton
  6. Encapsulating Invocation – Command Pattern
  7. Being Adaptive – the Adapter and Facade Patterns
  8. Encapsulating Algorithms – the Template Method
  9. Well Managed Collections – Iterator, Composite Patterns
  10. State of Things – State Pattern
  11. Controlling Object Access – Proxy Pattern
  12. Pattern of patterns – Compound Patterns
  13. Patterns in real world
  14. Leftover patterns – Bridge, Builder, Chain of Responsibility, Flyweight, Interpreter, Mediator, Memento, Prototype, Visitor

Written by curious

July 22, 2010 at 11:13 am

Posted in design-patterns

TECH: Design Patterns Analyzed


  1. Vince Huston on Design Patterns

Wrappers: Adapter, Facade, Proxy


  1. Adapter: different interface
  2. Adapter: Provides a different interface to its “subject” object. It makes 2 existing interfaces work together.
  3. Adapter: Intent
    • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces
    • Wrap an existing class with a new interface
    • match an old component to a new system


  1. Facade: simplified interface
  2. Facade: Wrap a complicated system with an object that provides a simple interface


  1. Proxy: same interface
  2. Proxy: Provides the same interface to its “subject” object.
  3. Proxy: Intent
    • Provide a surrogate or placeholder for another object to control access to it
    • Use an extra level of indirection to support distributed, controlled, or intelligent access
    • Add a wrapper and delegation to protect the real component from undue complexity
  4. Proxy: Benefits –
    1. Placeholder for an expensive to create object – only create real object on first access/request
    2. Local representative of a remote object – stub code for CORBA etc
    3. Protective proxy – check caller has access permissions before forwarding request
    4. Smart proxy – additional actions like reference counting, delayed load from persistent store, ensure real object locked before access

Written by curious

July 22, 2010 at 10:47 am

Posted in design-patterns

OO: Basics

  1. Abstract Data Type
  2. Abstraction
  3. Information Hiding
  4. Composition/Aggregation/Containment
  5. Association
  6. Inheritance
  7. Encapsulation – private, protected, public
  8. Polymorphism – derived classes/inheritance – virtual functions, overloading
  9. Open-Closed Principle – Open for Extension, but Closed for Modification
    Single Choice Principle – Whenever a software system must support a set of alternatives, ideally only one class in the system knows the entire set of alternatives
  10. Liskov Substitution Principle (LSP) – Callers of base class method should be able to use any subclass/derived class without knowing it
    Design-by-contract – a) A sub class should Honor the contracts made by it parent classes; b) Pre-conditions can only get weaker; c) Post-conditions can only get stronger
  11. Coupling – degree of interdependence – low coupling is better
  12. Cohesion
  13. Reuse – higher re-usability is better
  14. Accessor/Mutator – Use Accessors, Mutators instead of accessing member variables directly – easier to change internal detail, easier to execute additional side-effect of mutator
  15. Relations – “IS-A” “IS-A-KIND-OF”, “HAS-A”, “IMPLEMENTED-IN-TERMS-OF”, “USES”
  16. Interface – a set of methods that can be invoked on an object
  17. Program to an interface not an implementation – GoF(Ch1,p18)

    • clients remain unaware of the specific types of objects they use, as long as the object adheres to the interface
    • clients remain unaware of the classes that implement these objects; clients only know about the abstract class(es) defining the interface
  18. Composition vs Inheritance – Favor Composition over Inheritance (GoF,Ch1,p20)
    • In Inheritance, internals of parent classes are often visible to subclasses – breaks encapsulation
    • But with composition, no internal details of composed objects need be visible in the code using them
    • Using inheritance is recommended mainly when adding to the functionality of existing components, reusing most of the old code and adding relatively small amounts of new code.
  19. Implementation Inheritance – class inheritance – describes one object’s implementation in terms of another
  20. Interface Inheritance – subtyping – one object can be used in place of another
  21. Bad – Rigid, Fragile, Immobile, High Coupling
  22. Dependency Inversion Principle – a) high level modules should not depend upon low level modules, both should depend upon abstractions; b) abstractions should not depend upon details, details should depend upon abstractions
  23. Dependency Injection – a class does not instantiate (create object of a class) any other classes. Instead, it depends on the classes that are “somehow” injected (using setter method or passing as argument in the constructor) into it.
  24. Inversion of Control – an object that wants some functionality from another “provider” object, gets called by the provider; rather than the usual flow of logic where the object calls the provider when it needs it.
  25. Law of Demeter – Only talk to your immediate friends
  26. Interface Segregation Principle – Many client specific interfaces are better than one general purpose interface; Clients should not be forced to depend upon interfaces they don’t use
  27. Single Responsibility Principle

Written by curious

July 14, 2010 at 9:21 am

Posted in design-patterns

TECH: Gang of Four (23 design patterns)

Creational Patterns (ABFPS)

  1. Abstract Factory Creates an instance of several families of classes
  2. Builder Separates object construction from its representation
  3. Factory Method Creates an instance of several derived classes (aka Virtual Constructor)
  4. Prototype A fully initialized instance to be copied or cloned
  5. Singleton A class of which only a single instance can exist

Structural Patterns (ABCDFFP)

  1. Adapter Match interfaces of different classes
  2. Bridge Separates an object’s interface from its implementation
  3. Composite A tree structure of simple and composite objects
  4. Decorator Add responsibilities to objects dynamically
  5. Facade A single class that represents an entire subsystem
  6. Flyweight A fine-grained instance used for efficient sharing
  7. Proxy An object representing another object. Delegate to the “real” object.

Behavioral Patterns (CCIIMMOSSTV)

  1. Chain of Resp. A way of passing a request between a chain of objects
  2. Command Encapsulate a command request as an object
  3. Interpreter A way to include language elements in a program
  4. Iterator Sequentially access the elements of a collection
  5. Mediator Defines simplified communication between classes
  6. Memento Capture and restore an object’s internal state
  7. Observer A way of notifying change to a number of classes
  8. State Alter an object’s behavior when its state changes
  9. Strategy Encapsulates an algorithm inside a class
  10. Template Method Defer the exact steps of an algorithm to a subclass
  11. Visitor Defines a new operation to a class without change

Written by curious

May 17, 2010 at 3:09 pm

Posted in design-patterns