<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>mxml.it &#187; solutions</title>
	<atom:link href="http://www.mxml.it/index.php/category/solutions/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mxml.it</link>
	<description>avoid mickey mouse programming</description>
	<lastBuildDate>Mon, 06 Jun 2011 11:45:11 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Longest common subsequence problem</title>
		<link>http://www.mxml.it/index.php/2011/06/04/longest-common-subsequence-problem/</link>
		<comments>http://www.mxml.it/index.php/2011/06/04/longest-common-subsequence-problem/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 17:05:40 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/?p=45</guid>
		<description><![CDATA[Dynamic Programming is a powerful technique that can be used to solve many problems in time T(n2) or T(n3) for which a naive approach would take exponential time. “DP” is a general approach to solving problems, much like “divide-and-conquer” is a general method, except that unlike divide-and-conquer, the subproblems will typically overlap and are used to solve the next one.]]></description>
			<content:encoded><![CDATA[<p>Dynamic Programming is a powerful technique that can be used to solve many problems in time T(n2) or T(n3) for which a naive approach would take exponential time. “DP” is a general approach to solving problems, much like “divide-and-conquer” is a general method, except that unlike divide-and-conquer, the subproblems will typically overlap and are used to solve the next one.<br />
The cost of an algorithm in a program is a critical aspect because it can significantly impact on performances. In order to keep the cost low “DP” follow a couple of standard ways to progress</p>
<p>•    memorization<br />
•    converting from top-down to bottom-up</p>
<p>Another very common problem when dealing with dynamic programming is the longest common subsequence problem (for brevity since now “LCS”). The “LCS” problem is as follows</p>
<p style="text-align: center;"><em>We are given two strings: string S of length n, and string T of length m. The goal is to produce their longest common subsequence: the longest sequence of characters that appear left-to-right (but not necessarily in a contiguous block) in both strings.</em></p>
<p>The problem can be solved comparing the two strings; in the case S and T have a different length the desired subsequence has to ignore the ending elements of one of the two strings, in the case S and T have the same length all the characters have to be considered.<br />
As subproblems the algorithm will look at the “LCS” of a prefix of S and a prefix of T, running over all pairs of prefixes. For simplicity, let’s worry first about finding the length of the LCS and then we can modify the algorithm to produce the actual sequence itself.</p>
<p>The longest common subsequence(LCS) problem is one of the classical and well- studied problems in computer science. The computation of the &#8220;LCS&#8221; is a frequent task in DNA sequence analysis, and has applications to genetics and molecular biology.  Another practical application of the &#8220;LCS&#8221; algorithm is in order to compute the file differences.</p>
<p>Theoretically speaking the algorithm just fill out a matrix row by row, doing constant amount of work per entry, so this takes T(mn) time overall. The work actually performed is a comparison between the chars of the two strings at specific indexes.<br />
The final answer (i.e. the length of the LCS of S and T) is in the lower-right corner.<br />
To find the common sequence, the algorithm just walk backwards through matrix starting the lower-right corner.<br />
If either the cell directly above or directly to the right contains a value equal to the value in the current cell, then move to that cell (if both to, then chose either one). If both such cells have values strictly less than the value in the current cell, then move diagonally up-left, and output the associated character.<br />
This will output the characters in the LCS in reverse order.</p>
<p>Consider a practical example and search the “LCS” of the following strings</p>
<p>•    ABAZDC<br />
•    BACBAD</p>
<p>The algorithm will fill out a matrix like the following one and running backward the matrix the output will be DABA that is the “LCS” between the two strings.</p>
<table border="1" cellspacing="0" cellpadding="0" width="183">
<tbody>
<tr>
<td width="31" valign="top"></td>
<td width="28" valign="top"><strong>B</strong></td>
<td width="25" valign="top"><strong>A</strong></td>
<td width="23" valign="top"><strong>C</strong></td>
<td width="27" valign="top"><strong>B</strong></td>
<td width="27" valign="top"><strong>A</strong></td>
<td width="22" valign="top"><strong>D</strong></td>
</tr>
<tr>
<td width="31" valign="top"><strong>A</strong></td>
<td width="28" valign="top">0</td>
<td width="25" valign="top"><strong>1</strong></td>
<td width="23" valign="top">1</td>
<td width="27" valign="top">1</td>
<td width="27" valign="top">1</td>
<td width="22" valign="top">1</td>
</tr>
<tr>
<td width="31" valign="top"><strong>B</strong></td>
<td width="28" valign="top">1</td>
<td width="25" valign="top">1</td>
<td width="23" valign="top">1</td>
<td width="27" valign="top"><strong>2</strong></td>
<td width="27" valign="top">2</td>
<td width="22" valign="top">2</td>
</tr>
<tr>
<td width="31" valign="top"><strong>A</strong></td>
<td width="28" valign="top">1</td>
<td width="25" valign="top">2</td>
<td width="23" valign="top">2</td>
<td width="27" valign="top">2</td>
<td width="27" valign="top"><strong>3</strong></td>
<td width="22" valign="top">3</td>
</tr>
<tr>
<td width="31" valign="top"><strong>Z</strong></td>
<td width="28" valign="top">1</td>
<td width="25" valign="top">2</td>
<td width="23" valign="top">2</td>
<td width="27" valign="top">2</td>
<td width="27" valign="top">3</td>
<td width="22" valign="top">3</td>
</tr>
<tr>
<td width="31" valign="top"><strong>D</strong></td>
<td width="28" valign="top">1</td>
<td width="25" valign="top">2</td>
<td width="23" valign="top">2</td>
<td width="27" valign="top">2</td>
<td width="27" valign="top">3</td>
<td width="22" valign="top"><strong>4</strong></td>
</tr>
<tr>
<td width="31" valign="top"><strong>C</strong></td>
<td width="28" valign="top">1</td>
<td width="25" valign="top">2</td>
<td width="23" valign="top">3</td>
<td width="27" valign="top">3</td>
<td width="27" valign="top">3</td>
<td width="22" valign="top">4</td>
</tr>
</tbody>
</table>
<p>From a  practical point of view the following diagram shows up the classes involved into an ActionScript “DP” solution to the problem.</p>
<p><a href="http://www.mxml.it/wp-content/uploads/2011/06/Screen-shot-2011-06-04-at-7.09.56-PM.png"><img class="alignnone size-full wp-image-50" title="Screen shot 2011-06-04 at 7.09.56 PM" src="http://www.mxml.it/wp-content/uploads/2011/06/Screen-shot-2011-06-04-at-7.09.56-PM.png" alt="" width="607" height="656" /></a></p>
<p>Let&#8217;s start to examine what model used by these classes.<br />
The class LCSTable is the one to use in order to represent the matrix outlined at the beginning of the post, for this reason the constructor accept two arguments that represent the rows and columns of the matrix (i.e. the length of the two strings that will be examined) and use them to create an Array of Vectors</p>
<pre class="brush:java">public function LCSTable(rows:int, columns:int){

	_table = [];

	for(var i:int = 0; i &lt;= rows; i++){

		table[i] = new Vector.(columns + 1, true);

		for(var j:int = 0; j &lt;= columns; j++){

			table[i][j] = new LCSCell(0, LCSCell.UNDEFINED);

		}
	}

}</pre>
<p>The property _<em>table</em> is exposed through a public getter and return the array of Vectors that is the way all the cells are represented into the model.<br />
The LCSCell class is pretty simple, it stores the total number of matching strings and the direction the algorithm has to follow to walk backwards through matrix starting, the direction is stored into four static constants</p>
<ul>
<li>public static const UP:String             = &#8220;^&#8221;;</li>
<li>public static const LEFT:String         = &#8220;&lt;&#8221;;</li>
<li>public static const DIAGONAL:String     = &#8220;\\&#8221;;</li>
<li>public static const UNDEFINED:String     = &#8220;+&#8221;;</li>
</ul>
<p>when the <em>LCSTable</em> create the new cells set the direction to <em>UNDEFINED</em> and the <em>total</em> to 0.</p>
<p>The core of this solution for the longest common subsequence problem is the <em>LCSParser</em> class, let&#8217;s start to explore it.<br />
The constructor of the class needs two arguments (i.e. the strings to compare) and store them into two private members of the class</p>
<pre class="brush:java">public function LCSParser(first:String, second:String){

	firstString = first;
	secondString = second;

	init();
	populate();

}</pre>
<p>The protected method <em>init()</em> store the number of columns in other two private members and initialize the table setting the default values of the cells (i.e. direction <em>UNDEFINED</em> and <em>total</em> 0)</p>
<pre class="brush:java">protected function init():void{

	_lcs = "";

	columns = firstString.length;
	rows = secondString.length;

	table = new LCSTable(rows, columns).table;

}</pre>
<p>The <em>populate()</em> method creates two local variables to keep track of the total numbers of matching strings for each column and start the exploration of the <em>LCSTable</em> with tow nested for loops</p>
<pre class="brush:java">var totalTemp1:int;
var totalTemp2:int;

for(var i:int = 1; i &lt;= rows; i++){

	for(var j:int = 1; j &lt;= columns; j++){

              // Additional code here

        }

}</pre>
<p>In the body of the loop the method checks if there are matching characters or not in the two stored strings. If there is a match the current cell is updated considering if it belongs to the first row or column of the table (in this situation the total is 0 and the direction is intentionally left as <em>UNDEFINED</em>) or not.<br />
When updating the cell the local variable <em>totalTemp1</em> is used in order to increase the <em>total</em> property of the <em>LCSCell</em> instance properly.</p>
<pre class="brush:java">if(firstString.charAt(j - 1) == secondString.charAt(i - 1)){

	var currentCell:LCSCell = getCell(i, j);

	if (i == 0 || j == 0) {

		currentCell.total = 0;

	// if not, set it to 1 plus the value of its upper left element
	} else {

		totalTemp1 = getCell(i - 1, j - 1).total;

		currentCell.total = totalTemp1 + 1;
		currentCell.direction = LCSCell.DIAGONAL;							

	}						

}else{

	totalTemp1 = getCell(i - 1, j).total;
	totalTemp2 = getCell(i, j - 1).total;

	updateDirection(getCell(i, j), totalTemp1, totalTemp2);

}</pre>
<p>If there are not matching chars the method <em>updateDirection()</em> is called.<br />
This method consider the position in the table (i.e. actual row and column) and update the direction and total accordingly to the position</p>
<pre class="brush:java">private function updateDirection(cell:LCSCell, s1:int, s2:int):void{

	if(s1 &gt;= s2){

		cell.total = s1;
		cell.direction = LCSCell.UP;

	}else{

		cell.total = s2;
		cell.direction = LCSCell.LEFT;

	}

}</pre>
<p>Once the table is populated the public method <em>lcs()</em> can be used to recover the longest common subsequence.<br />
The method calls another one to walk backwards through matrix and return a string</p>
<pre class="brush:java">public function get lcs():String{

	parseLCS(secondString, rows, columns);
	return _lcs;

}</pre>
<p>The <em>parseLCS()</em> method uses recursion and populate the <em>_lcs</em> property accordingly to the direction of each cell</p>
<pre class="brush:java">private function parseLCS(data:String, i:int, j:int):void{

	if ((i == 0) || (j == 0)){

		return;

	}

	var currentCell:LCSCell = getCell(i, j);

	if(currentCell){

		if(currentCell.direction == LCSCell.DIAGONAL){

			parseLCS(data, i - 1, j- 1);
			var temp:String = data.charAt(i - 1);
			_lcs += temp;

		}else if(currentCell.direction == LCSCell.UP){

			parseLCS(data, i - 1, j);

		}else{

			parseLCS(data, i, j - 1);

		}

	}

}</pre>
<p>A fully working demo is available <a href="http://www.mxml.it/samples/lcs/LCS_web.html" target="_blank">here</a> with the source code included (right click -&gt; view source),  please feel free to use it as you want but please provide me as much as possible your feedback.</p>
<p>Just in case you would like to go deeper on this topic following you can find some interesting linka</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Dynamic_programming" target="_blank">http://en.wikipedia.org/wiki/Dynamic_programming</a></li>
<li><a href="http://wordaligned.org/articles/longest-common-subsequence" target="_blank">http://wordaligned.org/articles/longest-common-subsequence</a></li>
<li><a href="http://igm.univ-mlv.fr/~lecroq/seqcomp/node4.html" target="_blank">http://igm.univ-mlv.fr/~lecroq/seqcomp/node4.html</a></li>
</ul>
<p>Enjoy with dynamic programming!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2011/06/04/longest-common-subsequence-problem/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using the Abstract Factory pattern with Flex</title>
		<link>http://www.mxml.it/index.php/2009/02/13/using-the-abstract-factory-pattern-with-flex/</link>
		<comments>http://www.mxml.it/index.php/2009/02/13/using-the-abstract-factory-pattern-with-flex/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 06:21:33 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[samples]]></category>
		<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/index.php/2009/02/13/using-the-abstract-factory-pattern-with-flex/</guid>
		<description><![CDATA[Accordingly to the Gang of four the Abstract Factory pattern intent is to provide an interface for creating families of related or dependent objects without specifying their concrete classes.
This design pattern actually ensures that the patterns automatically get and use the correct object accordingly to the context in which the client is working.
There are many]]></description>
			<content:encoded><![CDATA[<p>Accordingly to the Gang of four the Abstract Factory pattern intent is to <em>provide an interface for creating families of related or dependent objects without specifying their concrete classes</em>.<br />
This design pattern actually ensures that the patterns automatically get and use the correct object accordingly to the context in which the client is working.<br />
There are many different situations in which this pattern can work, imagine for instance a system in which the drawing and printing method varies accordingly to the resolution supported by the system; the system has to use different drivers in different cases.<br />
At a first glance you may be tempted to use two different switch case for the drawing and printing procedure in which your system reacts in a different way accordingly to the resolution but remember that switches may indicate the need of abstraction in your system and that it can bring your system to a combinatorial explosion (imagine to add new drivers for each different resolution and create and even more complex switch case).<br />
A good way to solve this issue us to create a Factory that creates the appropriate object accordingly to the resolution supported by the system, in this way you avoid the combinatorial explosion I mentioned and you can keep the switches in a single place or even better accordingly to the language you are working on and to your code style you can avoid switches also in the factory.<br />
We have talked since now about two possible families of objects to use, monitor and printer drivers. Give me a chance to introduce you to a more complex system, an e-commerce with a group of families related to the system payments</p>
<p>•    Credit Card<br />
•    OnLine payment<br />
•    Other payment</p>
<p>For each of these families you may have the need to define multiple objects when you system starts</p>
<p>•    <em>Credit Card</em><br />
o    Visa<br />
o    American Express<br />
o    Master Card<br />
•    <em>OnLine payment</em><br />
o    Paypal<br />
o    E-check<br />
•    <em>Other payment</em><br />
o    Wire transfer<br />
o    Check</p>
<p>and add even more objects when the system grows or when new payment methods will be released over the net.<br />
In an e-commerce system you may also have the need to show to the user the appropriate payment system accordingly to his preferences, in order to increase the abstraction of your system you can define multiple Abstract classes and keep the system ignorant on which particular implementation is in use because the factories are the responsible to instantiate them.<br />
Imagine the scenario I described an put it in an UML diagram</p>
<p><img src="http://www.mxml.it/samples/abstractfactory/AbstractFactoryImp.gif" alt="Abstract Factory" width="720" height="493" /></p>
<p>The application is composed by a form that contains a submit button and the form fields vary accordingly to the user preferences retrieved by the system.<br />
The CheckOutFactory class is an abstract class that have two concrete implementations able to return to the client the UI needed for each payment (actually the MXML representation of the class). The PaymentContainer is a VBox with a property used to store a reference to the payment form created from the factory that implements an interface that defines two common methods of the payment forms</p>
<pre class="brush:java">
•    validateFields()
•    submit()</pre>
<p>As you know ActionScript 3.0 doesn’t support abstract classes, so the CheckOutFactory simulates the abstraction of the class trough the use of an internal class in its constructor.<br />
Another good way to implement the abstraction is the use of interfaces, this is the reason why I defined a common interface ICheckOut and two other interfaces (IOnlinePayment and ICreditCard) that extend the base interface and that will be implemented in the view of each payment form of the system.<br />
Take a look to the class hierarchy in order to understand where we are and where we are going</p>
<p><img src="http://www.mxml.it/samples/abstractfactory/class_hierarchy.JPG" alt="class hierarchy" width="309" height="507" /></p>
<p>The abstraction of the on-line and credit card payments is reached through the interfaces put on the top of the onLinePayment and creditCardPayment packaging, the view and it’s logic has been keep separated through the <a href="http://www.mxml.it/index.php/2008/09/09/introduction-to-mvp-for-flex/">Model View Presenter</a> pattern used from each payment form.<br />
Each presenter implements a public submit() method, in this way you can call in a centralized fashioned way the submit of each form trough the PaymentContainer property named element, each presenter will have the responsibility to recover the data from the view and each view, due to the fact that implements the ICheckOut interface, validate it’s fields (a good idea is to validate each credit card with a different Validator, this is the reason why you find an instance of the CreditCardValidator class in the  credit card payment forms.<br />
In order to run this <a href="http://www.mxml.it/samples/abstractfactory/AbstractFactory.html" target="_blank">sample </a>(view source enabled) I created an XML file that stores the name of some users and the payment preferences, each node has the following structure</p>
<pre class="brush:xml">&lt;user name = "Giorgio Natili" mode = "OnlinePayment" type = "PayPal" /&gt;</pre>
<p>In the main application a combo box is populated with this data and each time you change the selection a concrete factory is created and through the factory a new view is added to the PaymentContainer</p>
<pre class="brush:java">
private function onUserSelection(e:Event):void{
checkOutFactory = CheckOutFactory.getPaymentFacotry(e.target.selectedItem.@mode);
var s:String = e.target.selectedItem.@type;
checkOutModule = checkOutFactory.getUI(s.substr(0, 1).toLocaleLowerCase() + s.substring(1, s.length) + ".view." + s + "View");
paymentContainer.element = checkOutModule;
}</pre>
<p>The checkOutFactory and the checkOutMopdule properties data type represents the layer of abstraction I’m searching for<br />
private var checkOutFactory:CheckOutFactory;<br />
private var checkOutModule:ICheckOut;<br />
The method defined as a listener for the click event inside the PaymentContainer uses the methods defined in the ICheckOut interface to complete his task</p>
<pre class="brush:java">private function doSubmit():void{
if(_element.validateData()){
_element.submit();
}else{
Alert.show("Invalid data in the form...", "Attention!");
}
}</pre>
<p>At the end of the day we have a quite flexible sample, but which are the benefits of this pattern? It would be simpler to have a switch instead of all this code?<br />
The main benefit is that if you have to add the support for another credit card you have to deal only with the logic stored in the MVP triad you need to add a payment form and the system automatically will be able to handle the new form.<br />
The switch could be hard to maintain in a situation with more than 4 payment methods, moreover the abstraction layer that the system has reached give to you the flexibility to put each developer you want on the new payment forms the system needs without having to explain to the developer anything about the system itself.</p>
<p>There are other possible contexts in which the Abstract Factory pattern can be used</p>
<p>•    Handle different operating systems API in a cross platform application<br />
•    Different traits for users of an application<br />
•    Different version of an application<br />
•    Different performance guidelines</p>
<p>At the end of the day we can recap with the following points the Abstract Factory pattern</p>
<p>•    You want to have families or sets of objects for particular clients<br />
•    Families of related objects have to be instantiated<br />
•    You want to coordinate the creation of families of objects<br />
•    You need to isolates the rules of which objects are to be made</p>
<p>Obviously this is only a small sample and more complex implementation are out of the scope of this blog entry, so feel free to open a discussion on this topic.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2009/02/13/using-the-abstract-factory-pattern-with-flex/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using the Strategy pattern with ActionScript 3.0</title>
		<link>http://www.mxml.it/index.php/2009/02/11/using-the-strategy-pattern-with-actionscript-30/</link>
		<comments>http://www.mxml.it/index.php/2009/02/11/using-the-strategy-pattern-with-actionscript-30/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 12:27:25 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[resources]]></category>
		<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/index.php/2009/02/11/using-the-strategy-pattern-with-actionscript-30/</guid>
		<description><![CDATA[Accordingly to the Gang of four the Strategy pattern intent is to define a family of algorithms an make them interchangeable; the pattern let the algorithm vary independently from the client that use it.
It seems to me a very nice idea because I believe that a good developer have to write his code in an]]></description>
			<content:encoded><![CDATA[<p>Accordingly to the Gang of four <em>the Strategy pattern intent is to define a family of algorithms an make them interchangeable; the pattern let the algorithm vary independently from the client that use it</em>.<br />
It seems to me a very nice idea because I believe that a good developer have to write his code in an “open way”. What I mean is that if your code it’s full of if statements, conditionals, etc. each change became very difficult to introduce and maintain.<br />
The Strategy pattern can be roughly summarized like in the following UML diagram</p>
<p><img src="http://www.mxml.it/samples/strategy/pattern.gif" alt="Strategy pattern" width="644" height="285" /></p>
<p>The context is your application or a component in your application, the strategy may be a class or a method that define which algorithm your system can use, the concrete strategies are the classes that implements the algorithm that suits the needs of your system.<br />
One of the most sample and concrete samples of the application of the Strategy pattern is the calculation of taxes inside an e-commerce application.<br />
Imagine the situation in which your application has to deliver products all around the world and to apply different taxes factor accordingly to the country your customer lives, this means to use a different algorithm (a strategy) for each country.<br />
We need to define a strategy and apply a different tax factor for each country, so model your system with the following classes and interfaces<br />
1.    Calculator: an abstract class that implements the main algorithm<br />
2.    ENTaxCalculator: the class that changes the algorithm in order to apply the right amount of taxes for the English customers<br />
3.    ITTaxCaclulator: the class that changes the algorithm in order to apply the right amount of taxes for the English customers<br />
4.    ITaxCaclulator: the interface that defines the common operations of the strategy and that you can use in your system as the algorithm data type and that it’s implemented by all the strategies</p>
<p><img src="http://www.mxml.it/samples/strategy/strategy.gif" width="519" height="477" /></p>
<p>Let’s take a look to the implementation…<br />
First of all in order to avoid the instantiation of your abstract Calculator defines an internal class in the same Calculator.as file and use it in the constructor</p>
<pre class="brush:java">package it.mxml.utilities.taxes{
public class Calculator implements ITaxCalculator{
protected var _amount:Number;
protected var _taxesFactor:Number;
public function Calculator(enforcer:AbstractEnforcer){
if (enforcer == null){
throw new Error("AbstractException");
}
}
protected static function getAccess():AbstractEnforcer{
return new AbstractEnforcer();
}
}
internal class AbstractEnforcer{
// Do nothing
}</pre>
<p>Now you are ready to define your algorithms extending this class Calculator and changing in the constructor the _taxesFactor value (for brevity I removed from here the methods used for calculation but you can get them in the <a href="http://www.mxml.it/samples/strategy/srcview/index.html" target="_blank">source </a>code of the sample you find here).<br />
Imagine to have in your application a small basket and a method that calculate the taxes to apply, you can create the instance of the appropriate tax calculator through reflection and show the result</p>
<pre class="brush:java">
private function doCalculate():void{
var lang:String = Capabilities.language.toUpperCase();
var amount:Number = 0;
for each (var item:Object in selectedItems){
amount += item.price;
}
var calculator:ITaxCalculator;
var ClassDefinition:Class;
try{
ClassDefinition = getDefinitionByName("it.mxml.utilities.taxes." + lang + "TaxCalculator") as Class;
}catch(e:Error){
ClassDefinition = getDefinitionByName("it.mxml.utilities.taxes.DefaulTaxCalculator") as Class;
}
}</pre>
<p>In the complete sample <a href="http://www.mxml.it/samples/strategy/StrategyPattern01.html" target="_blank">application </a>you find here you can get also the output of this method.<br />
At the end of the day we can recap with the following points the Strategy pattern<br />
1.    Define a family of algorithms (with an abstract class) in order to solve a particular issue of your system<br />
2.    Define the single algorithms making them interchangeable (use an interface)<br />
3.    Define a procedure that is able to detect automatically the con text and which strategy to use (the appropriate algorithm)<br />
4.    Keep separate the algorithm definition / implementation and the selection of an algorithm</p>
<p>Obviously this is only a Mickey Mouse sample, but following this building blocks you can define great strategies for your system.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2009/02/11/using-the-strategy-pattern-with-actionscript-30/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flex and SVN</title>
		<link>http://www.mxml.it/index.php/2008/10/14/flex-and-svn/</link>
		<comments>http://www.mxml.it/index.php/2008/10/14/flex-and-svn/#comments</comments>
		<pubDate>Tue, 14 Oct 2008 16:06:52 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[resources]]></category>
		<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/index.php/2008/10/14/flex-and-svn/</guid>
		<description><![CDATA[I’m sure that tons of flex developers has already used SVN during the development of their projects but I have seen sometimes great difficulties when during the development of a project different coders need to modify the same file or add a file to a project. In the first situation the way to handle merge]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal"><span lang="EN-US">I’m sure that tons of flex developers has already used SVN during the development of their projects but I have seen sometimes great difficulties when during the development of a project different coders need to modify the same file or add a file to a project. In the first situation the way to handle merge is not really intuitive, in the second one most of the times the file is not committed.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">For this reason I decided to write some notes on SVN and TortoiseSVN 1.5.4 that has been recently released.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">First of all please be sure to use a sane repository layout. There are many ways to lay out your repository. Because branches and tags are ordinary directories, you&#8217;ll need to account for them in your repository structure. The Subversion project officially recommends the idea of a &#8220;project root&#8221;, which represents an anchoring point for a project that contains exactly three subdirectories: /trunk, /branches, and /tags. <o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">&#8220;trunk&#8221; is supposed to signify the main development line for the project. You could call this &#8220;main&#8221; or &#8220;mainline&#8221; or &#8220;production&#8221; or whatever you like.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">&#8220;branches&#8221; is obviously supposed to be a place to create branches. People use branches for a lot of purposes. You might want to separate your release or maintenance branches from your feature branches or your customer modification branches etc. <o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">&#8220;tags&#8221; are not treated as special by Subversion either. They are a convention, perhaps enforced by hook script or authoring rules, that indicate you are creating a point in time snapshot. Typically the difference between tags and branches is that the former are not modified once they are created. You might call your tag folders &#8220;releases&#8221; or &#8220;snapshots&#8221; or &#8220;baselines&#8221; or whatever term you prefer.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Be sure to Commit logical change set. When you commit a change to the repository, make sure your change reflects a single purpose: the fixing of a specific bug, the addition of a new feature, or some particular task. Your commit will create a new revision number which can forever be used as a &#8220;name&#8221; for the change. You can mention this revision number in bug databases, or use it as an argument to SVN merge should you want to undo the change or port it to another branch.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Merging changes sounds simple enough, but in practice it can become a headache. The problem is that if you repeatedly merge changes from one branch to another, you might accidentally merge the same change twice. When this happens, sometimes things will work fine. When patching a file, Subversion typically notices if the file already has the change, and does nothing. But if the already-existing change has been modified in any way, you&#8217;ll get a conflict.<br />
Ideally, your version control system should prevent the double-application of changes to a branch. It should automatically remember which changes a branch has already received, and be able to list them for you. It should use this information to help automate merges as much as possible. Unfortunately, Subversion is not such a system. Like CVS, Subversion 1.0 does not yet records any information about merge operations. When you commit local modifications, the repository has no idea whether those changes came from running SVN merge, or from just hand-editing the files.<br />
What does this mean to you, the user? It means that until the day Subversion grows this feature, you&#8217;ll have to track merge information yourself. The best place to do this is in the commit log-message.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Let’s take a look to a practical Flex development situation, first of all you have to install Tortoise SVN on your machine and create an empty folder for your project (I’m supposing that you have already started to work on some stuff and that is the time to go under source control and that you are the one that will create the repository).<br />
Right click on the folder and select the import option<o:p></o:p></span></p>
<p class="MsoNormal"><img src="http://www.mxml.it/samples/svn/01.gif" alt="01.gif" width="283" height="68" /><span lang="EN-US"><o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">In the dialog that appears insert the data for the remote repository<o:p></o:p></span></p>
<p class="MsoNormal"><img src="http://www.mxml.it/samples/svn/02.gif" alt="02.GIF" width="464" height="341" /><span lang="EN-US"><o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Right click again and perform the check out, now your folder is synchronized with the remote repository.<br />
Copy the files you need in the folder and perform a commit, you’ll be prompted to select the files you want to commit<o:p></o:p></span></p>
<p class="MsoNormal"><img src="http://www.mxml.it/samples/svn/03.PNG" alt="03.PNG" width="236" height="300" /><span lang="EN-US"><o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">It’s a good habit to remove properties, project, bin-debug, bin-release, etc. in order to perform this task you can deselect the files from this dialog or you can select a specific file, right click and remove it or all the files with the same extension from the synchronization of the repository<o:p></o:p></span></p>
<p class="MsoNormal"><img src="http://www.mxml.it/samples/svn/04.gif" alt="04.gif" width="331" height="134" /><span lang="EN-US"><o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Now you are able to work quite easily with SVN but remember that <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-indent: -18pt"><!--[if !supportLists]--><span style="font-family: Symbol" lang="EN-US"><span>·<span style="font-family: 'Times New Roman'; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal">         </span></span></span><!--[endif]--><span lang="EN-US">in order to rename a file or a folder you must first checkout the file or folder to your machine. Once it&#8217;s on your machine, right-click on the file or folder, and select the menu option SVN Rename, <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent: -18pt"><!--[if !supportLists]--><span style="font-family: Symbol" lang="EN-US"><span>·<span style="font-family: 'Times New Roman'; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal">         </span></span></span><!--[endif]--><span lang="EN-US">in order to delete a file or folder, simply right-click on it, and select the <em>Delete&#8230;</em> option from the <em>Tortoise SVN</em> menu<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-indent: -18pt"><!--[if !supportLists]--><span style="font-family: Symbol" lang="EN-US"><span>·<span style="font-family: 'Times New Roman'; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal">         </span></span></span><!--[endif]--><span lang="EN-US">to add a file or folder, check out the repo (if you haven&#8217;t already done so). move the new file(s) and folder(s) to the location you want them in the repository (for e.g. to add the file newfile.mxml to the mxml/trhunk/newclient/ folder, move newfile.mxml to that folder). Now, with everything in its place, right-click on the file(s) and folder(s) you want to add to the repository, and select the SVN Add&#8230; menu option<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Basically all the usual operations of an operating system needs to be performed trough the Tortoise SVN contextual menu.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">SVN is not a back-up system, is a way to handle versioning and conflict, what happens if you make some changes to a file and another developer make the changes to the same file and both of you make a commit at the end of your working day?<br />
SVN will try to make a merge but sometimes it’s not possible so be careful when you do the commit and use the <em>Check for modifications </em>function from the Tortoise SVN menu option<o:p></o:p></span></p>
<p class="MsoNormal"><img src="http://www.mxml.it/samples/svn/05.gif" alt="05.gif" width="334" height="66" /><span lang="EN-US"><o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">If something goes wrong during the merge you’ll keep your work safe because in the file you are committing SVN will add the change log in the code<o:p></o:p></span></p>
<pre>
<p class="MsoNormal"><span lang="EN-US">&lt;&lt;&lt;&lt;&lt;&lt;&lt; .mine<o:p></o:p></span>
<p class="MsoNormal"><span lang="EN-US"><span>                </span>var beautiful:int = 5;<o:p></o:p></span>
<p class="MsoNormal"><span lang="EN-US">=======<o:p></o:p></span>
<p class="MsoNormal"><span lang="EN-US"><span>                </span>var ugly:int = 5;<o:p></o:p></span>
<p class="MsoNormal"><span lang="EN-US">&gt;&gt;&gt;&gt;&gt;&gt;&gt; .r10<o:p></o:p></span>
</pre>
<p class="MsoNormal"><span lang="EN-US">and in your folder you get a copy of the file with the release name.<br />
I wasn’t a fun of SVN the first time I used but now I am happy to say “It works!”.<o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US">Resources<br />
<a href="http://electricjellyfish.net/garrett/talks/oscon2004/svn-best-practices/">http://electricjellyfish.net/garrett/talks/oscon2004/svn-best-practices/</a><br />
<a href="http://blog.evanweaver.com/articles/2007/08/15/svn-branching-best-practices-in-practice/">http://blog.evanweaver.com/articles/2007/08/15/svn-branching-best-practices-in-practice/</a><br />
<a href="http://www.iovene.com/5-svn-best-practices/">http://www.iovene.com/5-svn-best-practices/</a><br />
<a href="http://svnbook.red-bean.com/en/1.4/svn.tour.cycle.html">http://svnbook.red-bean.com/en/1.4/svn.tour.cycle.html</a><br />
<a href="http://www.changelogic.com/SvnProjectSetup">http://www.changelogic.com/SvnProjectSetup</a><br />
<a href="http://svnbook.red-bean.com/en/1.0/ch05s04.html#svn-ch-5-sect-6.1">http://svnbook.red-bean.com/en/1.0/ch05s04.html#svn-ch-5-sect-6.1</a><br />
<!--[if !supportLineBreakNewLine]--><br />
<!--[endif]--><o:p></o:p></span></p>
<p class="MsoNormal"><span lang="EN-US"><o:p> </o:p></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2008/10/14/flex-and-svn/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Flex code annotations</title>
		<link>http://www.mxml.it/index.php/2008/10/14/flex-code-annotations/</link>
		<comments>http://www.mxml.it/index.php/2008/10/14/flex-code-annotations/#comments</comments>
		<pubDate>Tue, 14 Oct 2008 12:38:06 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/index.php/2008/10/14/flex-code-annotations/</guid>
		<description><![CDATA[Today I was talking with a friend of mine that said to me that the only way to find something related to code annotations in Flex is a book he has&#8230; that&#8217;s definitely not true, the Flex documentation contain a lot of info on this topic and the web is full of resources.
In this short]]></description>
			<content:encoded><![CDATA[<p>Today I was talking with a friend of mine that said to me that the only way to find something related to code annotations in Flex is a book he has&#8230; that&#8217;s definitely not true, the Flex documentation contain a lot of info on this topic and the web is full of resources.</p>
<p>In this short post I want to summarize the building blocks of code annotation in Flex.</p>
<p>In computing, the programmer often adds annotations to source code in the form of comments. These do not affect the working of the program but give explanations (for other programmers, or potential readers of the code principally, but also as a reminder for the author),  hints or plans for improvement, etc.<br />
Further Annotations can also be added by a compiler or programmer in the form of metadata, which is then made available in later stages of building or executing a program. For example, a compiler may use metadata to make decisions about what warnings to issue, or a linker can use metadata to connect multiple object files into a single executable.</p>
<p>In computer programming, a Java annotation is a way of adding metadata to Java source code that can also be available to the programmer at run-time.<br />
Java annotations can be added to program elements such as classes, methods, fields, parameters, local variables, and packages.<br />
Unlike tags added to Java documentation and processed with tools such as XDoclet, Java annotations are completely accessible to the programmer while the software is running using reflection.</p>
<p>Class annotations, also known as metadata in Flex, are extremely valuable as they allow developers to provide additional information about classes, properties and methods which may not be appropriate to convey through implementation details such as Marker interfaces or some other means.</p>
<p>You can create your own custom metadata following the same format. The example which follows defines a custom metadata attribute utilized for annotating a class with version information. The name of the annotation is “Version”, which contains three properties; major, minor and revision.</p>
<pre class="brush:java">
package{

[Version(major="1", minor="2", revision="123")]
public class Model {

}
}</pre>
<p>Accessing custom annotations in Flex is accomplished via the flash.utils reflection APIs; describeType, getQualifiedClassName and getDefinitionByName.</p>
<p>ArrayElementType metadata tag can be easily associated to code annotations in fact when you define an Array variable in ActionScript, you specify Array as the data type of the variable but you cannot specify the data type of the elements of the Array.<br />
To allow the Flex MXML compiler to perform type checking on Array elements, you can use the [ArrayElementType] metadata tag to specify the allowed data type of the Array elements, as the following example shows:</p>
<pre class="brush:java">
public class myComponent extends VBox {
[ArrayElementType("String")]
public var users:Array;

[ArrayElementType("Number")]
public var orders:Array;

}</pre>
<p>In a more complex environment you can use java beans in Flex as the datatype of the ArrayElementType tag specifyng the fully qualified name of the class or get inspiration from this article <a href="http://www.flexpasta.com/index.php/2008/05/19/blazeds-with-annotations-for-remote-objects/" target="_blank">http://www.flexpasta.com/index.php/2008/05/19/blazeds-with-annotations-for-remote-objects/</a> that is strictly related to Flex and Blaze DS (i.e. java based enterprise applications).</p>
<p>This tag only works for Arrays &#8211; there is no way to set the type of elements in ArrayCollection, to have typed array collection, you can take existing ArrayCollection.as rename it to YourArrayCollection.as and modify source property and add ArrayElementType tag with your prefered type, (I have not tried it but it should work) or even better extend the ArrayCollection in order to create your custom collection with the support for the ArrayElementType metatag.</p>
<p>In order to check the generated code add the -keep parameters to the flex builder compiler.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2008/10/14/flex-code-annotations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Update Framework for Adobe AIR Applications</title>
		<link>http://www.mxml.it/index.php/2008/06/25/update-framework-for-adobe-air-applications/</link>
		<comments>http://www.mxml.it/index.php/2008/06/25/update-framework-for-adobe-air-applications/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 23:59:18 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/index.php/2008/06/25/update-framework-for-adobe-air-applications/</guid>
		<description><![CDATA[This beta release of the update framework for Adobe AIR Applications provides APIs to assist developers in including good update capabilities in their AIR applications. The functionality present in update framework assists developers in the following:
* Periodically checking for updates based on an interval or at the request of the user
* Downloading AIR files (updates)]]></description>
			<content:encoded><![CDATA[<p>This beta release of the update framework for Adobe AIR Applications provides APIs to assist developers in including good update capabilities in their AIR applications. The functionality present in update framework assists developers in the following:</p>
<p>* Periodically checking for updates based on an interval or at the request of the user<br />
* Downloading AIR files (updates) from a web source<br />
* Alerting the user on the first run of the newly installed version or performing data migration<br />
* Confirming that the user wants to check for updates<br />
* Displaying information to the user on the new available version for download<br />
* Displaying download progress and error information to the user</p>
<p>The update framework supplies a default user interface that your application can use. It provides the user with basic information and options related to application updates. Your application can also also define its own custom user interface for use with the update framework.</p>
<p>For more info chek this <a href="http://labs.adobe.com/wiki/index.php/Adobe_AIR_Update_Framework" target="_blank">link</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2008/06/25/update-framework-for-adobe-air-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flex Google Analytics</title>
		<link>http://www.mxml.it/index.php/2008/04/18/7/</link>
		<comments>http://www.mxml.it/index.php/2008/04/18/7/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 03:11:09 +0000</pubDate>
		<dc:creator>Giorgio Natili</dc:creator>
				<category><![CDATA[solutions]]></category>

		<guid isPermaLink="false">http://www.mxml.it/index.php/2008/04/18/7/</guid>
		<description><![CDATA[Sometimes you need to monitor your Flex application and get all the info dealing with the usage of the application.
Surfing the web I found this nice component.
Flex Google Analytics Magic component will now allow you to track all of your Flex Application activities through Google Analytics. The magic is that you only have to write]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to monitor your Flex application and get all the info dealing with the usage of the application.<br />
Surfing the web I found this nice <a href="http://flexinmotion.com/" target="_blank">component</a>.</p>
<p>Flex Google Analytics Magic component will now allow you to track all of your Flex Application activities through Google Analytics. The magic is that you only have to write one line of code in your Flex application to enable this if you use this component. The Flex Google Analytics Magic component will automatically track all user navigation clicks, button click, check boxes, radio buttons and a number of other controls within your app automatically.</p>
<p>Nice stuff!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mxml.it/index.php/2008/04/18/7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

