Translate

Monday, September 23, 2013

Design Pattern Notes

I have been going through the Design Patterns Library course hosted by Pluralsight. Below is a small descriptions and a note to understand various patterns.

I hope that I should be able to cover all the patterns as the list of patterns are quite extensive and I recommend all of you to get a license of Pluralsight so that you can be exposed to the sea of courses they have. 
(Excuse me upfront for the typos as the notes were taken in notepad++ while I was going through the patterns, once I finish the important patterns I intent to reformat this post and make it more pleasant for all of us)



Adapter Pattern: 
--------------------------------------
- The Adapter Pattern is used to wrap a needed class with one that implements a required interface. 
- By writing client classes so that they depend on adapters, we future proof these classes, ensuring 
they can be made to work with as-yet-unwritten implementation libraries. 

Related PAtterns to the AdapterPattern: 
- Repository Pattern
- The repository pattern is a verfy common use of Adapter Pattern
- Strategy Pattern
- The adapter pattern is often passsed into a class that depends on it, thus implementing the strategy pattern.
- Facade Pattern
- Adapter and facade pattern are both wrappers. The facade pattern attempts to simplyfy the interface and often wraps many classes, while the Adapter 

typically wraps a single Adaptee, and is not generally concerned with simplyfying the interface.

Bridge Pattern: 
--------------------------------------
DEcouple an abstraction from its implementation so that 2 can vary independently. Abstractions and implemenation are decoupled. 

Abstract one more level of interface so that 1st level of abstraction is dependent on the 2nd level of abstraction 

This abstraction is going to use one more level of Abstraction as its implementation.\

Abstraction -> Abstraction -> Implementation 

For one level of abstraction there's no need of Bridge pattern. 
Common usgaes of bridge pattern: 
- User Interfaqce 
- Neat explanantion of the pattern is also given at: http://www.oodesign.com/bridge-pattern.html

Builder Pattern: 
--------------------------------------
Problem 1: too Many paramteres
Problem 2: Order Dependent
Problem 3: Different Constructions

Spearates the construction of a complex object from its representation so that same construction process can create different representations. 
Construction of the object is a process OR logic.
Representation of the object is data. 

Separate logic from data, reuse the logic to produce different data. 

Instead of telling the subway guy on what all you need after asking for each ingredient you are going to give him an list of ingredients so that the conversation is 

much shorter. 

Chain of Responsibility Pattern: 
--------------------------------------
Provides a simple mechanism of decoupling the sender of the message from the receiver 
Ordered list of methods 

Sender --> Receiver1 --> Receiver2 --> Receiver3 

Lets say in the above scenario the message sent by the sender is handled by the Receiver2 and so the receiver 3 is not needed.
Sender only is exposed to the Receiver1 and so is the Receiver2 knows only about Receiver3. This brings us to the traits of Chain of Responsibility. 

- Sender is aware of only one receiver 
- Each receiver is only aware of the next receiver
- Receivers process the message or just send it down the chain
- The sender does not know who received the message.
- The first receiver to handler the message terminates the chain
- The orcer of the receiver list matters


Command Pattern: 
--------------------------------------

- A command line order management system
- A system in which you pass in a command to be done. 
- In such systems we should be wary of a very big switch case statements which decide what to do based on the input passed.

Intent of the PAttern: 
- Represent an action (piece of logic) as an object
- DEcouples the clients that execute command from the details and dependencies of the command logic
- Enables delayed execution 
- Can queue command for later execution 
- If command objects are also persistent, can delay acrosds the process restarts

Also knows as Action OR Transaction PAttern
Applicable on 
- Logging the actions 
- Validation 
- Undo functionality in the website 

Client --> Command { Validate(), Execute(), Undo()} --> (dependencies)
  --> (dependencies)

- Key notion of command pattern is that somebody can call a method without dealing with any extra data.
- There is no parameter to be passed which makes it different from the Strategy pattern (here execution path is defined based on the parameter passed)
- COmmands must be completely self contained 
- The client does not pass in any argumemnts, the context from the caller is not required 
- Easy to add new commands (open/closed principal)

Related Patterns: 
- Factory pattern : Factories are ofyten useful to construct the command objects 
- Null Objects: Often times returning a "null command" can be useful instead of retuning a null
- Composite Command: Command with child commands

http://www.oodesign.com/command-pattern.html


Composite Pattern: 
--------------------------------------
- Compose objects into tree structures to represent part-whole hierarchies. 
- Composite lets clients treat indivisual objects and compositions of objects uniformly. (GOF)
- If you are sending emails to individuals instead of using the group aliases then you need to apply composite pattern to your life. 
- Using group aliases is the live example of using the composite pattern, the sends just sends an email to the group and the e-mail has the logic to iterate over the 

members of group and make sure that email is individually sent to each of the member.
When to Use Composite Pattern: 
- When you have groups and collections 
- Can you add an Interface
- trees
- Distribution 

Basic is to define an interface (component) and have a leaf (simple object implement it) and then create a composite object which implements the interface and also has 

a property which is of the type of component.



Decorator Pattern: 
--------------------------------------

Structural Pattern : DEcorator object is used without touching the existing class. 

Small Pizza company: Large, Medium and Small Pizza deriving from Base class Pizza. 

Problem is when toppings are introduced: Cheese, Ham and Peppers

Now with 3 Pizzas we have 3 toppings each combination is a unique pizza. 
This will result in class explosion and will become very hard to maintain. 


Intent: 
- Add functionality to existing objects dynamically at runtime without effecting the other classes. 
- Alternative approach to sub classing 
- Inheritance based design leads to an explosion of the classes.
- Flexible design 
- Support Open Close Principle --> Open for extension but closed for modification 

Applicability
- Legacy systems 
- Add functionality to controls. 
- Sealed Classs

IExtenderProvider interface uses decorator pattern, for more info on the interface below are the links: 
http://www.codeproject.com/aspnet/FixingIExtenderProvider.asp 
http://www.codeproject.com/aspnet/ExtenderProviderComponent.asp

How does it work: 
- It wraps the object -- Also known as wrapper object 


Lazy LOad Pattern: 
--------------------------------------

Lazy Initialization Pattern : 

- Simplest approach 
- Every property checks to see if its backing firlds has been initialized 
- If so it calculates or fetches the value for the field before retunung.
- Violates don't repeat yourself principle 
- Requires all access to tge value ti go through the property
- Within the class nothing but the property should access the field. 
- Requires knowledge of whether the fields has been calculated
- Typically check if the field is null
- If null is a legal value then another approach is required, like using the flag if the value is populated or not. 



Virtual Proxy Pattern: 
- Proxy looks like real object
- Creates Indentity problem in the application 
- Proxy isn't the real object 
- OverRide the equality method (Equals)
- Proxy Design PAttern
- May need to create many virtual proxies
- Best done via some kind of code generation 
- MAny OR/M tools create dynamic proxies at runtime (nHibernate, Entity Framework)

Virtual Proxy Consequences: 
- Managing Identities can present Challenges --> Overriding GetEquals and GetHashCode 
- Need to create many virtual proxies, one for each class that is proxied
- Above stated points are not present for collections: 
- Collections are value objects and do not have an identity.
- Typically there are fewer collections than objects 
- Collections typically provide largest performance benefit from the lazy loading. 

Value Holder LAzy Load PAttern: 
--> No need to use this if we are using .Net 4.0 if .Net 4.0 is in use then directly use Lazy
-  Provides lazy load functionality without encapsulation which means the client knows about the lazy loading. 
- Calling code knows it is working with a Value Holder  type 
- Requires creating several new Types: 
- Value Holder 
- IValueHolder 
- Factory or MapperClasses
- Value Holder uses IValueHolder via Strategy Pattern to load value when accessed.
- ValueHolder and IValueHolder are resuable
- ValueHolder is similar to Lazy and IValueHolder is similar to the lambda expression which is passed which knows how to load the lazy type. 
- ValueHolder and IValueLoader are resuable.

Ghosts Pattern: 

- A ghost is a real object in a partial state.
- An object which knows about its own state. 
- Intially ghost contains its Id.
- Whenever any property is accessed, the ghost class loads all of its state from persistence. 
- Essentially, the object is its  own virtual proxy
- Avoids identity concerns of its own virtual proxy,
- This violates the Single responsibility cause the object is needed for self loading and plus loading the state of its own properties. 


Mediator PAttern: 
--------------------------------------
Motivating Example
- When you have many objects of a similar typpe that need to communicate with each other 
- The communication between objects is complex
Definition: 
- Define an object that encapsulates how a set of objects interacts. Mediator promotes loose coupling by keeping objects from referring to each other explicitly,
and it lets you vary their interaction independently. 

Components in Mediator Pattern: 
- Colleagues 
- Individual compnents that need to communicate with each other Airbus, Fighter 
- Implement the same base type(abstract class or interface)
- HAve a knowledge of the Mediator component rather than knowing of each other. 
- Mediator 
- Single centralized component that managed communication between the colleague components
- abstraction of mediator is necessary so that the colleagues work with the abstracted mediator rather than concrete one. 

Advantages: 
- Hides all the coordination between colleagues 
- Decoupled colleagues 
- Mediator's one to many relationship with colleague is preferred to colleagues relating in a many-to-many fashion.

Disadvantage: 
- The mediator can become very large and very complicated as more colleagues are handled. 

Overall mediator enhances decoupling 


Memento Pattern: 
--------------------------------------

Undo and Redo functionality 
Motivating Example: 
- It would be useful to rollback one or more objects within your application to previous state(for example, to implement Undo)
- Providing undo functionality within one or more calsses would violate the single responsibility principle 
- Providing full access to objects internal state violates the encapsulation principle
- The Memento pattern describes a way to capture the objects internal state without violating encapsulation or SRP. 

Intent: 
- Without violating the encapsulation, capture and externalize an objects internal state so that the object can be restored to this state later. 
- The memento pattern involves 2 objects : originator and caretaker. Thr originator represents object whose state is being tracked.
The care taker performs the operation on the originator but needs to be able to undo operations. 

Applicability: When to use the Memento Pattern: 
- in case of an application whose state needs to be tracked, you need to be able to track the state of an object or your application and restire previous states as 

needed. 
- You want to abstract and reuse the Undo/Redo functionality
- Follow SRP and Don't repeat yourself
- You do not wish to break encapsulation and expose your classes internal state globally 

How the memento is used: 

- Memento itself holds the state of the originator 
- Ideally ony the originator should have access to the internal details of its state within the Memento
- The caretakers interface to Memento should not allow it to access the internal state of the Originator
- The originator can create Mementos or restore its given state given a Memento
- The care taker maintains the memento objects without operating on their contents. 

Common Usage of Memento is Undo and Redo functionality: 

- Multiple Undo/Redo is often implemented using a stack
- When a change is performed:
- A memento containing the current state is added to the Undo stack
- When an undo operation is performed: 
- the current state is replaced with the state of the memento removed from the Undo stack 
- If Redo is implemented, the current state is stored in a Redo stack.
- When a Redo operation is performed
- The current state is replaced with the state of the memento removed from the Redo stack
- The current state is stored in the Undo stack.

Collaboration: 

- Whenever a change is made from the requested state, A care taker requests a Memento from the Originator
- The caretaker stores one or more Mementos until they are needed. 
- If or when requred the Caretaker passes the Memento back to the originator
- It may be possible that Memento stored by caretaker may not be used if there is no redo or undo functionality 
- Mementos should be value objects, holding state but no behavior. 
- Only the originator which created a memento should be able to assign or retreive its state. 


Model View Presenter Pattern: 
--------------------------------------

Model View View Model Pattern:
--------------------------------------

- a set of guidelines to code for an application
- Where did MVVM come from?
- What is MVVM?
- Components of MVVM ?

History:
- 2004 Martin Fowler - Presentation Model
- Separates a view from it's state and behavior
- Not dependent on specific UI Framework
- 2005 John Gossman unveiled the MVVM pattern
- Tailored for WPF and Silverlight platforms

Intent:
- Separate Concerns
- View
- View's state and Behavior
- Data
- Unit testing and UI testing
- Maintenance
- Extensibility
- Enables designer/developer workflow
- Take advantage of WPF/silverlight databinding --> Also supports input validation

Structure:
- View
- ViewModel
- Model

- Model :
- HAs no reference to the View or ViewModel
- Model can be represented by Domain specific objects
- Model can be represented as Data centric object (model is XML or data access layer)
- Model's purpose is to represent Data points
- ITs single purpose is to represnt datapoint
- View :
- May or Maynot have a reference to the ViewModel
- Doesnot have a reference to the Model
- It consists of only visual elements of display like buttons windowns and everything
- Responsible for showing and collection data to and from user.
- in silver light the data bindings are specified but the details are hidden from the UI.
- Binding the viewModel set by DataContext
- The ViewModel:
- Has a reference to the Model
- May or may not have a reference to the view
- Contains properties and commands  and other abstratctions to make the communication easy between the view and the model.
- At minimum the view should implement the INotifyChanged interface because the ViewModel is bound to notify the view of a change.
- Although the ViewModel contains the state and the data for the UI is should have a UI control as a base object.


To Create the connection between the view and viewModel (Binding the view to ViewModel):
- Declaratively in XAML --> View first approach --> ViewModel as a resource --> Static resource on the View
- Cannot control instantiation
- Cannot pass parameter
- Imperatively in code
- The view model is assigned in the views code behing after the Initialization method
- View Model Locator --> Service Locator renamed for MVVM
- DataTemplates
- Inversion of Control
- Factory with Inversion of Control
- and more ..

Communication:
- Events
- Commands
- Execute
- CanExecute

Consequences
- Pro:
- Reduce Code behind
- Model doesnot need to change to support a view
- Designers design and coders code
- Reduces development time
- Multitargeting and project linking
-Con:
- Create more files
- Simple tasks can be complicated
- Lack of standardization
= Specific to WPF and Silverlight platforms 


Prototype Pattern:
--------------------------------------
- Overview of the Prototype PAttern
- SPecify the kinds of objects to create using a prototypical instance and create new objects by

copying this prototype --> Cloning or Making a copy instead of newing the object up
- Its easier to make a copy of the object than going through the whole construction process this is why

this pattern is used.
- Problem 1: COnstruction cost of an object is expensive
- Problem 2: State is important copy the state.
- Problem 3: Hiding the constructor
- Prototype design --> Just implement a Icloneable Interface and while implementing Clone method return

MemberwiseClone()
- You can do a deep copy and shallow copy --> MemberwiseClone does only shallow copy is specified only at one

level
- Examples are present in javascript, javascript is a prototypical language. --> Structuring Javascript is a

course on pluralsight.





Friday, September 13, 2013

String.Intern Method

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

Definition taken from: http://msdn.microsoft.com/en-us/library/system.string.intern.aspx