0% found this document useful (0 votes)
62 views

Decorator Pattern

The Decorator design pattern is also known as the wrapper pattern. Wrapping allows one object to use another's characteristics without extending either the wrapped object or the object doing the wrapping. A subclass of a superclass may be unnecessarily burdened by unused functionality.

Uploaded by

Sanjay Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Decorator Pattern

The Decorator design pattern is also known as the wrapper pattern. Wrapping allows one object to use another's characteristics without extending either the wrapped object or the object doing the wrapping. A subclass of a superclass may be unnecessarily burdened by unused functionality.

Uploaded by

Sanjay Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

Decorator Pattern - Key OOP Concepts Used with the

Decorator Pattern
(Page 4 of 4 )

Sometimes when you think about key OOP concepts such as inheritance, you have to consider its larger
consequences. The upside of inheritance is that once a superclass has been established, all the subclasses inherit its
features. However, you may not want or need all the “stuff” for every subclass from a superclass. If you want to add
functionality to an object, subclassing may not be the way to go, because everything else subclassed from the same
superclass may be unnecessarily burdened by unused functionality.

Unwanted Inheritance

At the end of this chapter, you will see an example of a car dealership where users select models of cars with a
choice of options for those cars. If all the options were derived from a superclass, that would mean that every car
would have all the options, whether or not you wanted them. One option in the example is a rear view camera used
with minivans and large SUVs with limited rear vision. Such an option would be superfluous on a sports car such as
a Chevrolet Corvette, Morgan, or Ferrari. However, with subclassing, that’s exactly what would happen. Every
subclass gets everything from the superclass. So here’s a case where we’d have to look beyond simple inheritance.
Depending on how the application’s written, even the components would all have the same features. A pickup truck
would be subclassed from the same component as a luxury car—both inheriting features they don’t want and
wouldn’t use.

Wrapping Responsibilities

The Decorator design pattern is also known as the Wrapper pattern. The concept of “wrapping” is at the heart of the
Decorator design pattern. So what does it mean to “wrap” one object in another? One way to think about wrapping
is to imagine wrapping a gift. The wrapper transforms the gift, but the gift does not inherit the characteristics of the
wrapper—it only uses the wrapping. Unlike subclassing, which extends one class into another, wrapping allows one
object to use another’s characteristics without extending either the wrapped object or the object doing the wrapping.

The wrapping with which most ActionScript programmers are familiar is that used for transforming data types from
one type to another. For example, theNumberclass can wrap a string variable, and then that variable has the
characteristics of theNumber class. Figure4-3 illustrates a common wrapper function:

Figure 4-3. Number class wrapping String class

When we look at wrapping one object with another object, we can think of it
as a class intercepting API calls intended for a specific instance of another
class. The example in Figure 4-3 shows that theNumberclass is intercepting a
call to an instance of theStringclass. The result is that the 1variable, an
unsigned integer, is able to accept the assignment of thesvariable as a
number. That’s because thesvariable is wrapped in aNumberclass and treated as
a number.

Using the Decorator class, components are wrapped in decorators. The wrapping class is a concrete instance of a
decorator, and the wrapped class is an instance of the concrete component class. Thus, the concrete component now
“contains” the characteristics of the wrapper, but the characteristics are not inherited. Figure 4-4 shows an example.

Figure 4-4. Concrete decorator wrapping concrete component

The concrete component that’s wrapped by another class borrows characteristics of the wrapping class. When those
characteristics are not needed, the instance of the concrete class is simply instantiated without being wrapped.

Flexibility and Adaptability

One good OOP practice is to create your classes so that they can be extended but not changed. If a class is changed,
especially one with subclasses, you can quickly destroy an application. So the trick is to set up your classes so that
it’s easy to extend them, yet keep them safe from alteration.

The Decorator design pattern allows you to do this. The model is grounded in a single class that is the superclass to
all others. This core class is an abstract component class. An abstract decorator class is subclassed from this class,
re-implementing the core methods. (In the context of ActionScript 3.0, the abstract nature of the class is simulated
by using theoverridestatement when re-implementing methods in subclasses.) All the other concrete component
and decorator classes have the same root superclass, even though the decorator classes are subclassed from the
abstract decorator class, and the component classes are directly from the abstract component class. So, when the
concrete component objects are wrapped in concrete decorator objects, both objects share the same root superclass.
Thus, the decorated objects can keep the core object unmodified while changing its responsibilities.

In a larger OOP framework, the Decorator pattern can add and subtract functionality from an object by wrapping
selected components with selected decorators. Second, it can add more than a single functionality to an object by
wrapping one wrapper inside another wrapper. As a result, the design pattern can change functionality without
changing structure.

Please check back next week for the continuation of this article.

What's the Catch

This pattern allows us to provide the extensibility point in your implementation. As you might have noticed, while
implementing my decorators I never even touched my component classes. So even if one doesn’t own a class, one
can decorate it to add new behaviors dynamically and even recursively. This additional behavior might be added
before or after the base behavior, or this behavior might be blocking it. The decorators can provide new methods
and even new properties as you can see in the class diagram. But there are some problems associated with
decorators.

1. The programmer who is going to use decorators must understand their intention; otherwise he may end up
using some senseless combination or sequence. For example in our scenario if the programmer defines the
sequence in this way: message will be compressed, then encrypted, and then validated, it will be a bit
senseless. In real life scenarios, the results might be disastrous for some combinations or ,sequences.
2. Testing a decorator class will require providing a mock of decorated class. Since we haven’t yet covered
testing, so I will not discuss it
3. Also this pattern puts some responsibility on the base behavior designer. Although it's perfectly legitimate to
add new properties or public methods in the decorator, but this way it will lose the flexibility of being
handled by the base reference, and you will need to use the concrete instance

UML class diagram


using System;

class MainApp
{
public static void Main()
{
// Abstract factory #1
AbstractFactory factory1 = new ConcreteFactory1();
Client c1 = new Client(factory1);
c1.Run();

// Abstract factory #2
AbstractFactory factory2 = new ConcreteFactory2();
Client c2 = new Client(factory2);
c2.Run();

// Wait for user input


Console.Read();
}
}

// "AbstractFactory"
abstract class AbstractFactory
{
public abstract AbstractProductA CreateProductA();
public abstract AbstractProductB CreateProductB();
}

// "ConcreteFactory1"
class ConcreteFactory1 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}

// "ConcreteFactory2"
class ConcreteFactory2 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}

// "AbstractProductA"
abstract class AbstractProductA
{
}

// "AbstractProductB"
abstract class AbstractProductB
{
public abstract void Interact(AbstractProductA a);
}
// "ProductA1"
class ProductA1 : AbstractProductA
{
}

// "ProductB1"
class ProductB1 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + " interacts with " + a.GetType().Name);
}
}

// "ProductA2"
class ProductA2 : AbstractProductA
{
}

// "ProductB2"
class ProductB2 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + " interacts with " + a.GetType().Name);
}
}

// "Client" - the interaction environment of the products


class Client
{
private AbstractProductA AbstractProductA;
private AbstractProductB AbstractProductB;

// Constructor
public Client(AbstractFactory factory)
{
AbstractProductB = factory.CreateProductB();
AbstractProductA = factory.CreateProductA();
}

public void Run()


{
AbstractProductB.Interact(AbstractProductA);
}
}

Abstract Factory

Motivation

Modularization is a big issue in today's programming. Programmers all over the world are trying to avoid the idea
of adding code to existing classes in order to make them support encapsulating more general information. Take the
case of a information manager which manages phone number. Phone numbers have a particular rule on which they
get generated depending on areas and countries. If at some point the application should be changed in order to
support adding numbers form a new country, the code of the application would have to be changed and it would
become more and more complicated.
In order to prevent it, the Abstract Factory design pattern is used. Using this pattern a framework is defined, which
produces objects that follow a general pattern and at runtime this factory is paired with any concrete factory to
produce objects that follow the pattern of a certain country. In other words, the Abstract Factory is a super-factory
which creates other factories (Factory of factories).

Intent

• Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying
their classes.

Implementation
The pattern basically works as shown below, in the UML diagram:

The classes that participate to the Abstract Factory pattern are:

• AbstractFactory - declares a interface for operations that create abstract products.


• ConcreteFactory - implements operations to create concrete products.
• AbstractProduct - declares an interface for a type of product objects.
• Product - defines a product to be created by the corresponding ConcreteFactory; it implements the
AbstractProduct interface.
• Client - uses the interfaces declared by the AbstractFactory and AbstractProduct classes.

The AbstractFactory class is the one that determines the actual type of the concrete object and creates it, but it
returns an abstract pointer to the concrete object just created. This determines the behavior of the client that asks the
factory to create an object of a certain abstract type and to return the abstract pointer to it, keeping the client from
knowing anything about the actual creation of the object.
The fact that the factory returns an abstract pointer to the created object means that the client doesn't have
knowledge of the object's type. This implies that there is no need for including any class declarations relating to the
concrete type, the client dealing at all times with the abstract type. The objects of the concrete type, created by the
factory, are accessed by the client only through the abstract interface.

The second implication of this way of creating objects is that when the adding new concrete types is needed, all we
have to do is modify the client code and make it use a different factory, which is far easier than instantiating a new
type, which requires changing the code wherever a new object is created.

The classic implementation for the Abstract Factory pattern is the following:

abstract class AbstractProductA{


public abstract void operationA1();
public abstract void operationA2();
}

class ProductA1 extends AbstractProductA{


ProductA1(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
public void operationA1() { };
public void operationA2() { };
}

class ProductA2 extends AbstractProductA{


ProductA2(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
public void operationA1() { };
public void operationA2() { };
}

abstract class AbstractProductB{


//public abstract void operationB1();
//public abstract void operationB2();
}

class ProductB1 extends AbstractProductB{


ProductB1(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
}

class ProductB2 extends AbstractProductB{


ProductB2(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
}

abstract class AbstractFactory{


abstract AbstractProductA createProductA();
abstract AbstractProductB createProductB();
}

class ConcreteFactory1 extends AbstractFactory{


AbstractProductA createProductA(){
return new ProductA1("ProductA1");
}
AbstractProductB createProductB(){
return new ProductB1("ProductB1");
}
}
class ConcreteFactory2 extends AbstractFactory{
AbstractProductA createProductA(){
return new ProductA2("ProductA2");
}
AbstractProductB createProductB(){
return new ProductB2("ProductB2");
}
}

//Factory creator - an indirect way of instantiating the factories


class FactoryMaker{
private static AbstractFactory pf=null;
static AbstractFactory getFactory(String choice){
if(choice.equals("a")){
pf=new ConcreteFactory1();
}else if(choice.equals("b")){
pf=new ConcreteFactory2();
} return pf;
}
}

// Client
public class Client{
public static void main(String args[]){
AbstractFactory pf=FactoryMaker.getFactory("a");
AbstractProductA product=pf.createProductA();
//more function calls on product
}
}

Applicability & Examples


We should use the Abstract Factory design pattern when:

• the system needs to be independent from the way the products it works with are created.
• the system is or should be configured to work with multiple families of products.
• a family of products is designed to work only all together.
• the creation of a library of products is needed, for which is relevant only the interface, not the
implementation, too.

Phone Number Example

The example at the beginning of the article can be extended to addresses, too. The AbstractFactory class will
contain methods for creating a new entry in the information manager for a phone number and for an address,
methods that produce the abstract products Address and PhoneNumber, which belong to AbstractProduct classes.
The AbstractProduct classes will define methods that these products support: for the address get and set methods
for the street, city, region and postal code members and for the phone number get and set methods for the number.

The ConcreteFactory and ConcreteProduct classes will implement the interfaces defined above and will appear in
our example in the form of the USAddressFactory class and the USAddress and USPhoneNumber classes. For each
new country that needs to be added to the application, a new set of concrete-type classes will be added. This way
we can have the EnglandAddressFactory and the EnglandAddress and EnglandPhoneNumber that are files for
English address information.
Pizza Factory Example

Another example, this time more simple and easier to understand, is the one of a pizza factory, which defines
method names and returns types to make different kinds of pizza. The abstract factory can be named
AbstractPizzaFactory, RomeConcretePizzaFactory and MilanConcretePizzaFactory being two extensions of the
abstract class. The abstract factory will define types of toppings for pizza, like pepperoni, sausage or anchovy, and
the concrete factories will implement only a set of the toppings, which are specific for the area and even if one
topping is implemented in both concrete factories, the resulting pizzas will be different subclasses, each for the area
it was implemented in.

Look & Feel Example

Look & Feel Abstract Factory is the most common example. For example, a GUI framework should support several
look and feel themes, such as Motif and Windows look. Each style defines different looks and behaviors for each
type of controls: Buttons and Edit Boxes. In order to avoid the hardociding it for each type of control we define an
abstract class LookAndFeel. This calls will instantiate, depending on a configuration parameter in the application
one of the concrete factories: WindowsLookAndFeel or MotifLookAndFeel. Each request for a new object will
be delegated to the instatiated concrete factory which will return the controls with the specific flavor

Specific problems and implementation

The Abstract Factory pattern has both benefits and flaws. On one hand it isolates the creation of objects from the
client that needs them, giving the client only the possibility of accessing them through an interface, which makes
the manipulation easier. The exchanging of product families is easier, as the class of a concrete factory appears in
the code only where it is instantiated. Also if the products of a family are meant to work together, the Abstract
Factory makes it easy to use the objects from only one family at a time. On the other hand, adding new products to
the existing factories is difficult, because the Abstract Factory interface uses a fixed set of products that can be
created. That is why adding a new product would mean extending the factory interface, which involves changes in
the AbstractFactory class and all its subclasses. This section will discuss ways of implementing the pattern in order
to avoid the problems that may appear.

Factories as singletons

An application usually needs only one instance of the ConcreteFactory class per family product. This means that it
is best to implement it as a Singleton.

Creating the products

The AbstractFactory class only declares the interface for creating the products. It is the task of the ConcreteProduct
class to actually create the products. For each family the best idea is applying the Factory Method design pattern. A
concrete factory will specify its products by overriding the factory method for each of them. Even if the
implementation might seem simple, using this idea will mean defining a new concrete factory subclass for each
product family, even if the classes are similar in most aspects.

For simplifying the code and increase the performance the Prototype design pattern can be used instead of Factory
Method, especially when there are many product families. In this case the concrete factory is initiated with a
prototypical instance of each product in the family and when a new one is needed instead of creating it, the existing
prototype is cloned. This approach eliminates the need for a new concrete factory for each new family of products.

Extending the factories

The operation of changing a factory in order for it to support the creation of new products is not easy. What can be
done to solve this problem is, instead of a CreateProduct method for each product, to use a single Create method
that takes a parameter that identifies the type of product needed. This approach is more flexible, but less secure. The
problem is that all the objects returned by the Create method will have the same interface, that is the one
corresponding to the type returned by the Create method and the client will not always be able to correctly detect to
which class the instance actually belongs.

Hot Points:

• AbstractFactory class declares only an interface for creating the products. The actual creation is the task of
the ConcreteProduct classes, where a good approach is applying the Factory Method design pattern for each
product of the family.
• Extending factories can be done by using one Create method for all products and attaching information
about the type of product needed.
Question
What is the difference between a Style and a Template?

Edit

Answer
Style is used to set the properties of an object to particular values. In addition, a Style allows Triggers based on
styled object events, styled object property values, and data values. In turn, triggers allow the animation of the
object's properties.

In contrast, a Template is used to define the Visual Tree of a Control (ControlTemplate) or the Visual Tree of the
representation of an object (DataTemplate). While templates also have Triggers, it is to be noted that Style triggers
cannot interract with particular items of the Visual Tree for the object.

One common distinction of Styles and Templates states that a Style can contain one/many Setters/Triggers to
change the ControlTemplate or DataTemplate of controls/objects.

reply to this message


Re:What is the difference between DataTemplate and ControlTemplate
datatemplate is how to style the data and controltemplate is to style the
control(how the control looks
date: Wed, 17 May 2006 07:05:44 -0500 author: qazxsw

reply to this message


Re: What is the difference between DataTemplate and ControlTemplate
More Specifically:

A ControlTemplate is used to define/change the way a class derived from


Control looks...

Buttons, ListBox, ScrollBar, ...

However, some "Controls" you use are not derived from Control: Best
example is the TextBlock class. The TextBlock cannot have a
ControlTemplate.

Alternatly, the concept of DataTemplate is closelly linked with the


Content Model in WPF application.

Certain controls are made to display "Content"... The content can be


anything... An Image, Text, an Object.... in fact, it is defined as an
"object" type.

The DataTemplate simply defines how a particular content (or content


type) is meant to be displayed... Example: Usually, a string is
displayed using a simple TextBlock... However, if you want a custom
text layout, decoration, alignement, ... you would need to define an
Alternate DataTemplate.

I hope this clears the topic a little more...


date: 17 May 2006 06:16:55 -0700 author: Marcus

Re: What is the difference between DataTemplate and ControlTemplat


Ok, I've understood it to some extent.
Thanks a lot.
date: Thu, 18 May 2006 21:45:02 -0700 author: Daniel

Re: What is the difference between DataTemplate and ControlTemplate


Just wanted to add that you can take a look at the before/after
screenshots at the top and the bottom of this page:
http://tinyurl.com/rn3vz

The ListBox at the top... a ControlTemplate is used to define the


visuals of ListItems (what the Border looks like, what happens when an
item is selected). A DataTemplate is used to describe how the Photo
objects (the content/data items) should be displayed (in this case, as
images instead of filenames).

Before we get into differences between them, let me show how one would typically use them. It’s a good practice
that all your templates are embedded inside resources / styles. It makes your XAML centralized, shareable and
easier to understand (a re factored XAML of sorts, waiting for ReSharper to include this refactoring ).

Don’t Do:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<!– Your Data Template Goes here–>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Recommended:
<Window.Resources>
<DataTemplate x:Key=”myDataTemplate”>
<!– Your Data Template Goes here–>
</DataTemplate>
</Window.Resources>

<ListBox ItemTemplate=”{StaticResource myDataTemplate}” />

The above XAML holds true also for HierarchicalDataTemplate & ItemsPanelTemplate. But it won’t quite work
for ControlTemplate, as ControlTemplate can be assigned to Template property of a class that inherits from
ContentControl class, which ListBox doesn’t.

So the listbox code would typically look like this:

<ControlTemplate x:Key=”myControlTemplate” TargetType=”{x:Type ListBoxItem}”>


<TextBox />
</ControlTemplate>

<ListBox>
<ListBoxItem Template=”{StaticResource myControlTemplate}” />
</ListBox>

But the problem with above snippet is, you are manually specifying item which is never the case in real world.
Ideally you would like to bind ItemsSource Property of ListBox with some collection obtained at runtime from your
data access layer. Solution to this problem is creating a style and binding it to ItemContainerStyle property of
ListBox. By doing that you will be able to use ItemsSource for Binding & the ControlTemplate which is present
inside the style will be applied to each binded item.

<ListBox x:Name=”myList” ItemsSource=”{Binding}” ItemContainerStyle=”{StaticResource myStyle}” />


<Style x:Key=”myStyle” TargetType=”{x:Type ListBoxItem}”>
<Setter Property=”Template”>
<Setter.Value>
<ControlTemplate TargetType=”{x:Type ListBoxItem}”>
<TextBox Text=”{Binding collectionPropertyName}” />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

ItemsPanelTemplate is mainly used by controls inheriting from ItemsControl class for displaying their Items.
ItemsPanelTemplate can be customized through ItemsPanel property of ItemsControl class or any class which
inherits from ItemsControl.

<ListBox x:Name=”myList” ItemsPanel=”{StaticResource myItemsPanelTemplate}” />


<ItemsPanelTemplate x:Key=”myItemsPanelTemplate”>
<StackPanel Orientation=”Horizontal” />
</ItemsPanelTemplate>

Dependency properties are used when the resolution of a property’s value is based on other properties or runtime
settings (such as operating system settings). Here are some important features of dependency properties:

• Value resolution – DPs are used to form a system which can determine the actual property value based on
various runtime information. The resolution process has an order of precedence it assigns to various
environmental contexts in which the property might exist. For example, if the DP is being modified by an
animation then the value supplied by the animation is the resolved value, but if it is not animated, then the
value is derived from elsewhere.
• Self-contained validation – DPs can have custom callback methods execute when the property value has
changed. These callbacks can validate the new value or coerce the new property value into something
acceptable, according to the semantics of the property.
• Default values – DPs provide a consistent mechanism for associating a default value with a property. A
DP’s default value has the lowest precedence in the value resolution process, meaning that if there is no
other way to determine the property value, then the default value will be used.
• Property meta-data – The property system knows how a DP should behave based on meta-data supplied at
the time the property is registered with the system. Subclasses can tweak a DP by overriding the property’s
meta-data, instead of completely re-implementing the property itself. It is interesting to note that this meta-
data is not stored in attributes, partly because the performance impact associated with using reflection to
manipulate the meta-data was unacceptable.
• XAML friendly – Just like normal properties, DPs can be set in XAML.
• Value inheritance – Any DP can be given the ability to inherit its value from the property setting on an
ancestor element, in the logical tree. This provides similar functionality to the ambient properties used in
Windows Forms. Value inheritance is useful in many situations, such as propagating a data source down
the element tree, font settings, flow direction (right-to-left) settings, etc.
• Attached properties – A form of dependency property which allows a child element to store a value
associated with a property defined on an ancestor element.

My conclusion, after all of 10 minutes of research…. When you write:


<Rectangle Canvas.Top=”15”>
Validation Callbacks

Validation callbacks can be assigned to a dependency property when you first register it. The validation callback is
not part of property metadata; it is a direct input of the Register method. Therefore, once a validation callback is
created for a dependency property, it cannot be overridden by a new implementation.

public static readonly DependencyProperty CurrentReadingProperty =


DependencyProperty.Register(
"CurrentReading",
typeof(double),
typeof(Gauge),
new FrameworkPropertyMetadata(
Double.NaN,
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnCurrentReadingChanged),
new CoerceValueCallback(CoerceCurrentReading)
),
new ValidateValueCallback(IsValidReading)
);
public double CurrentReading
{
get { return (double)GetValue(CurrentReadingProperty); }
set { SetValue(CurrentReadingProperty, value); }
}

The callbacks are implemented such that they are provided an object value. They return true if the provided value is
valid for the property; otherwise, they return false. It is assumed that the property is of the correct type per the type
registered with the property system, so checking type within the callbacks is not ordinarily done. The callbacks are
used by the property system in a variety of different operations. This includes the initial type initialization by
default value, programmatic change by invoking SetValue, or attempts to override metadata with new default value
provided. If the validation callback is invoked by any of these operations, and returns false, then an exception will
be raised. Application writers must be prepared to handle these exceptions. A common use of validation callbacks
is validating enumeration values, or constraining values of integers or doubles when the property sets measurements
that must be zero or greater.

Validation callbacks specifically are intended to be class validators, not instance validators. The parameters of the
callback do not communicate a specific DependencyObject on which the properties to validate are set. Therefore
the validation callbacks are not useful for enforcing the possible "dependencies" that might influence a property
value, where the instance-specific value of a property is dependent on factors such as instance-specific values of
other properties, or run-time state.

The following is example code for a very simple validation callback scenario: validating that a property that is
typed as the Double primitive is not PositiveInfinity or NegativeInfinity.

public static bool IsValidReading(object value)


{
Double v = (Double)value;
return (!v.Equals(Double.NegativeInfinity) && !v.Equals(Double.PositiveInfinity));
}
Coerce Value Callbacks and Property Changed Events

Coerce value callbacks do pass the specific DependencyObject instance for properties, as do
PropertyChangedCallback implementations that are invoked by the property system whenever the value of a
dependency property changes. Using these two callbacks in combination, you can create a series of properties on
elements where changes in one property will force a coercion or reevaluation of another property.

A typical scenario for using a linkage of dependency properties is when you have a user interface driven property
where the element holds one property each for the minimum and maximum value, and a third property for the
actual or current value. Here, if the maximum was adjusted in such a way that the current value exceeded the new
maximum, you would want to coerce the current value to be no greater than the new maximum, and a similar
relationship for minimum to current.

The following is very brief example code for just one of the three dependency properties that illustrate this
relationship. The example shows how the CurrentReading property of a Min/Max/Current set of related *Reading
properties is registered. It uses the validation as shown in the previous section.

public static readonly DependencyProperty CurrentReadingProperty =


DependencyProperty.Register(
"CurrentReading",
typeof(double),
typeof(Gauge),
new FrameworkPropertyMetadata(
Double.NaN,
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnCurrentReadingChanged),
new CoerceValueCallback(CoerceCurrentReading)
),
new ValidateValueCallback(IsValidReading)
);
public double CurrentReading
{
get { return (double)GetValue(CurrentReadingProperty); }
set { SetValue(CurrentReadingProperty, value); }
}

The property changed callback for Current is used to forward the change to other dependent properties, by
explicitly invoking the coerce value callbacks that are registered for those other properties:

private static void OnCurrentReadingChanged(DependencyObject d,


DependencyPropertyChangedEventArgs e)
{
d.CoerceValue(MinReadingProperty);
d.CoerceValue(MaxReadingProperty);
}

The coerce value callback checks the values of properties that the current property is potentially dependent upon,
and coerces the current value if necessary:
private static object CoerceCurrentReading(DependencyObject d, object value)
{
Gauge g = (Gauge)d;
double current = (double)value;
if (current < g.MinReading) current = g.MinReading;
if (current > g.MaxReading) current = g.MaxReading;
return current;
}

Note
Default values of properties are not coerced. A property value equal to the default value might occur if a property
value still has its initial default, or through clearing other values with ClearValue.

The coerce value and property changed callbacks are part of property metadata. Therefore, you can change the
callbacks for a particular dependency property as it exists on a type that you derive from the type that owns the
dependency property, by overriding the metadata for that property on your type.
Pros and Cons

Many developers are leery of reflection (and the DLR) because of performance concerns. In my own work I haven’t
found this to be a problem. The performance penalty for the user when setting a single property in the UI is not
likely to be noticed. That may not be the case in highly interactive UIs, such as multi-touch design surfaces.

The only major performance issue is in the initial population of the view when there are a large number of fields.
Usability concerns should naturally limit the number of fields you’re exposing on any screen so that the
performance of the initial data bindings through this DLR approach is undetectable.

Nevertheless, performance should always be carefully monitored and understood as it relates to the user experience.
The simple approach previously described could be rewritten with reflection caching. For additional details, see
Joel Pobar’s article in the July 2005 issue of MSDN Magazine.

There is some validity to the argument that code readability and maintainability are negatively affected using this
approach because the View layer seems to be referencing properties on the ViewModel that don’t actually exist.
However, I believe the benefits of eliminating most of the hand-coded proxy properties far outweigh the problems,
especially with proper documentation on the ViewModel.

The dynamic proxy property approach does reduce or eliminate the ability to obfuscate the Model layer because the
properties on the Model are now referenced by name in the XAML. Using traditional proxy properties does not
limit your ability to obfuscate the Model because the properties are referenced directly and would be obfuscated
with the rest of the application. However, as most obfuscation tools do not yet work with XAML/BAML, this is
largely irrelevant. A code cracker can start from the XAML/BAML and work into the Model layer in either case.

Finally, this approach could be abused by attributing model properties with security-related metadata and expecting
the ViewModel to be responsible for enforcing security. Security doesn’t seem like a View-specific responsibility,
and I believe this is placing too many responsibilities on the ViewModel. In this case, an aspect-oriented approach
applied within the Model would be more suitable.

Collections

Collections are one of the most difficult and least satisfactory aspects of the MVVM design pattern. If a collection
in the underlying Model is changed by the Model, it’s the responsibility of the ViewModel to somehow expose the
change so that the View can update itself appropriately.

Unfortunately, in all likelihood the Model does not expose collections that implement the
INotifyCollectionChanged interface. In the .NET Framework 3.5, this interface is in the System.Windows.dll,
which strongly discourages its use in the Model. Fortunately, in the .NET Framework 4, this interface has migrated
to System.dll, making it much more natural to use observable collections from within the Model.

Observable collections in the Model open up new possibilities for Model development and could be used in
Windows Forms and Silverlight applications. This is currently my preferred approach because it’s much simpler
than anything else, and I’m happy the INotifyCollectionChanged interface is moving to a more common assembly.

Without observable collections in the Model, the best that can be done is to expose some other mechanism—most
likely custom events—on the Model to indicate when the collection has changed. This should be done in a Model-
specific way. For example, if the Person class had a collection of addresses it could expose events such as:

public event EventHandler<AddressesChangedEventArgs>


NewAddressAdded;
public event EventHandler<AddressesChangedEventArgs>
AddressRemoved;
This is preferable to raising a custom collection event designed specifically for the WPF ViewModel. However, it’s
still difficult to expose collection changes in the ViewModel. Likely, the only recourse is to raise a property-
changed event on the entire ViewModel collection property. This is an unsatisfactory solution at best.

Another problem with collections is determining when or if to wrap each Model instance in the collection within a
ViewModel instance. For smaller collections, the ViewModel may expose a new observable collection and copy
everything in the underlying Model collection into the ViewModel observable collection, wrapping each Model
item in the collection in a corresponding ViewModel instance as it goes. The ViewModel might need to listen for
collection-changed events to transmit user changes back to the underlying Model.

However, for very large collections that will be exposed in some form of virtualizing panel, the easiest and most
pragmatic approach is just to expose the Model objects directly.

MVVM
The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding
infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the two and
entirely remove the need for writing code in a ViewModel that directly updates a view. The data binding system
also supports input validation, which provides a standardized way of transmitting validation errors to a view.
Two other features of WPF that make this pattern so usable are data templates and the resource system. Data
templates apply Views to ViewModel objects shown in the user interface. You can declare templates in XAML and
let the resource system automatically locate and apply those templates for you at run time. You can learn more
about binding and data templates in my July 2008 article, "Data and WPF: Customize Data Display with Data
Binding and WPF."
If it were not for the support for commands in WPF, the MVVM pattern would be much less powerful. In this
article, I will show you how a ViewModel can expose commands to a View, thus allowing the view to consume its
functionality. If you aren't familiar with commanding, I recommend that you read Brian Noyes's comprehensive
article, "Advanced WPF: Understanding Routed Events and Commands in WPF," from the September 2008 issue.
In addition to the WPF (and Silverlight 2) features that make MVVM a natural way to structure an application, the
pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic
lives in a set of ViewModel classes, you can easily write code that tests it. In a sense, Views and unit tests are just
two different types of ViewModel consumers. Having a suite of tests for an application's ViewModels provides free
and fast regression testing, which helps reduce the cost of maintaining an application over time.

MVVM is a UI design pattern. The main use of this pattern to remove UI cluttered code like bindings ,
synchronization etc.

In this pattern we create a extra class called as view model or model which acts as a bridge between model and
view. The view sends the actions and data to the model view class who in turns sends the data to model. Any
changes in the model is replicated or informed to the UI using the INotifyPropertyChanged interface.

You might also like