Skip to content

Instantly share code, notes, and snippets.

@amitt001
Created June 22, 2016 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitt001/a75733865ebff3dcebc1e0bd81391569 to your computer and use it in GitHub Desktop.
Save amitt001/a75733865ebff3dcebc1e0bd81391569 to your computer and use it in GitHub Desktop.

OOP and Design Pattern:

Association, Aggregation and Composition:

The distinction between aggregation and composition goes to old times for language like C++ where there is manual memory management. For languages with dynamic memory management everything is compositon.

Association: Multiple objects have their own life cycle and there is no owner. Ex teacher and student, independent life cycle.

Aggregation: A specialzed form of assocation relation, objects with their own life cycle but there is ownership. A weaker "has a" relation. Ex car and tire. Car has tires but tires can exist even when car doesn't exists.

Compostion: A specialzed form of aggregaton relation where object has owner ship on other object and lifetime is also dependent. A strong "has a" relationship. For Ex: Building has room and if rooms are destroyed building is destroyed and vice-versa.

Singleton

Important Points:

  • Singleton pattern is mechanism of controlling the number of instances(usually one).
  • Use static varibale to to store instance of singleton class.
  • When ever class constructure is caled chekc if the static variable is already initialized , yes return instance else initiate class and asssign to static variable.
  • Ignore singleton, pass instance when the code needs access to another object.

Problems:

  • Singleton pattern in multi-threaded environment. For ex: two threads T1 & T2. T1 check if instance==NULL and cpu switches control to T2 now T2 checks if instance==NULL-> you just got 2 instance.

    Solution: 1. put getInstance() method as syncronzed or 2. early create an instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment