<?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>Design Patterns &#8211; Xojo Programming Blog</title>
	<atom:link href="https://blog.xojo.com/tag/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.xojo.com</link>
	<description>Blog about the Xojo programming language and IDE</description>
	<lastBuildDate>Wed, 25 Sep 2024 14:26:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Updated Tutorial: Active Words</title>
		<link>https://blog.xojo.com/2021/09/16/updated-tutorial-active-words/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Thu, 16 Sep 2021 13:00:00 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[TextArea]]></category>
		<category><![CDATA[Xojo API 2.0]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=9171</guid>

					<description><![CDATA[Follow this tutorial to create active, aka clickable, words in the text of a TextArea control in your Xojo projects. Learn to use the Object-oriented Delegate design pattern to dynamically change how your app reacts when the user clicks on those active words. Best of all, this project is cross-platform, so you can use it for macOS, Windows and Linux!]]></description>
										<content:encoded><![CDATA[
<p><strong>This post was originally <a href="https://blog.xojo.com/2018/07/31/tutorial-active-words/">published</a> in 2018 and has been updated to use Xojo API 2.0</strong>.</p>



<p>Follow this tutorial&nbsp;to create active, aka clickable, words in the text of a TextArea control in your Xojo projects. Learn to use the Object-oriented <a href="https://blog.xojo.com/2016/07/25/make-an-rss-reader-with-xojoin-33-lines-of-code/">Delegate design pattern</a> to dynamically change how your app reacts when the user clicks on those active words. Best of all, this project is cross-platform, so you can use it for macOS, Windows and Linux!</p>



<span id="more-9171"></span>



<p>The active words&nbsp;will be based on the use of <a href="https://documentation.xojo.com/api/data_types/pair.html">Pairs</a>, so one piece of information will be the active word and the other piece of information will be the associated data, which is always a String. The associated data could be a link or text you want to show in another control when the user clicks on the active word.</p>



<p>For the sake of this tutorial, the class we are creating has some limitations. For example, you won&#8217;t be able to repeat the same word and assign it to take different actions. If you want your code to react the same to the same active word or words throughout your project, well then, that&#8217;s what it will do. Anyway, this tutorial serves as a good starting point and you&#8217;ll be able to modify and improve it to meet your own needs.</p>



<p>Download the class with the example project from <a href="https://www.dropbox.com/s/11z4g56q99lvw3j/URLTextArea.xojo_binary_project.zip?dl=1">here</a>.</p>



<div class="wp-block-image is-style-default"><figure class="aligncenter"><img fetchpriority="high" decoding="async" width="802" height="666" src="https://blog.xojo.com/wp-content/uploads/2021/09/ActiveWords.gif" alt="" class="wp-image-9172"/></figure></div>



<h3 class="wp-block-heading">TextArea Subclass</h3>



<p>This feature will be based in the <a href="https://documentation.xojo.com/api/deprecated/textarea.html">TextArea</a> class, the first step is add a new TextArea control from the Library panel to the Navigator, change its name to <code>LinkDetectorTextArea</code>. Next, add the following Event Handlers to the TextArea subclass. These will be responsible for following the pointer movement and reacting to the registered active words for the instance.</p>



<ul class="wp-block-list"><li><b>Open</b>. To assign the pointer cursor, more appropriate for the kind of functionality this subclass will provide</li><li><b>MouseMove</b>. To detect if there is an active word under the cursor pointer to click on</li><li><b>MouseDown</b>. To call all the registered Observers when the user clicks on an active word, passing along the detected word and the associated information</li></ul>



<p>Since we also want to make these events available for any instance created from the subclass, we have to create them again as Event Definitions. With the subclass selected in the Navigator, select <code>Insert &gt; Event Definition</code> using the following signatures:</p>



<ul class="wp-block-list"><li><b>Event Name. Open</b>.</li><li><b>Event Name. MouseMove</b>. Parameters: <code>X as Integer, Y as Integer</code>.</li><li><b>Event Name. MouseDown</b>. Parameters: <code>X as Integer, Y as Integer</code>. Return Type: <code>Boolean</code>.</li></ul>



<p>Add some Private properties used by the added Event Handlers and other methods we have yet to define to the class. Set these properties as private because they just need to be accessed from the class itself and not from other pieces of external code or additional classes inherited from the subclass:</p>



<ul class="wp-block-list"><li><b>Name. boundedWord</b>. Type: <code>Pair</code>. This is the property that will point to the current matched active word from the text.</li><li><b>Name. previousBoundedWord</b>. Type: <code>Pair</code>. This property points to the previous matched word from the text.</li><li><b>Name. linkedWords</b>. Type: <code>Dictionary</code>. This is the Dictionary that will contain all the active words / additional data pairs.</li><li><b>Name. observers()</b>. Type: <code>ActionDelegate</code>. This is an Array containing all the registered observers of the type <code>ActionDelegate</code> yet to be defined.</li></ul>



<p>As we have seen, we need to define a Delegate type for the class. Select <code>Insert &gt; Delegate</code> with the following data:</p>



<ul class="wp-block-list"><li><b>Delegate Name</b>: ActionDelegate.</li><li><b>Parameters</b>: boundedWord as Pair.</li><li><b>Scope</b>: Public.</li></ul>



<h3 class="wp-block-heading">Assigning the Cursor Type</h3>



<p>Select the <code>Open</code> Event and add the following code in the corresponding Code Editor:</p>



<pre class="wp-block-preformatted">Me.MouseCursor = System.cursors.standardpointer
RaiseEvent open</pre>



<p>We simply use this Event for assigning the Arrow cursor type that is most appropriate.</p>



<h3 class="wp-block-heading">Matching the Active Words</h3>



<p>Next, select the <code>MouseMove</code> Event Handler and type the following code in the corresponding Code Editor:</p>



<pre class="wp-block-preformatted">Var tlen As Integer = Me.Text.Length
If previousBoundedWord &lt;&gt; Nil Then
  setStyleForWord(previousBoundedWord, False)
  previousBoundedWord = Nil
End If

Var boundLeft, boundRight As Integer = -1
Var startPosition As Integer = Me.CharacterPosition(x,y)

If CharacterPosition(x,y) &gt;= tLen Then
  If boundedWord &lt;&gt; Nil Then setStyleForWord( boundedWord, False )
  mboundedWord = Nil
ElseIf Me.Text.Middle(startPosition,1) &lt;&gt; Chr(32) And Me.Text.Middle(startPosition,1) &lt;&gt; EndOfLine Then
  For n As Integer = startPosition DownTo 0
    If Me.Text.Middle(n,1) = Chr(32) Or Me.Text.Middle(n,1) = EndOfLine or n = 0 Then
      boundLeft = n
      Exit
    End
    
  Next
  For n As Integer = startPosition To tlen
    If Me.Text.Middle(n+1,1) = Chr(32) Or Me.Text.Middle(n+1,1) = EndOfLine Or n = tlen Then
      boundRight = n+1
      Exit
    End
  Next
End

If boundLeft &lt;&gt; -1 And boundRight &lt;&gt; -1 Then
  Var isolatedWord As String = Me.Text.Middle(boundLeft, boundRight - boundLeft)
  Var check As pair = wordInDictionary( isolatedWord, boundleft, boundRight )
  If check  &lt;&gt; Nil Then 
    mboundedWord  = check
    If previousBoundedWord = Nil Then previousBoundedWord = mboundedWord
    setStyleForWord(previousBoundedWord, True)
  Else
    mboundedWord = Nil 
  End If
End If

RaiseEvent mouseMove(X, Y)</pre>



<p>This code is in charge of detecting the limits of the word under the cursor and finding if it is one of the active words registered for the class.</p>



<h3 class="wp-block-heading">Reacting to Active Words</h3>



<p>Finally, select the <code>MouseDown</code> Event Handler and write the following code into the associated Code Editor:</p>



<pre class="wp-block-preformatted">If linkedWords &lt;&gt; Nil And boundedWord &lt;&gt; Nil Then
  Var p As New pair(mboundedWord.Left,linkedWords.Value(mboundedWord.Left))
  For Each item As LinkDetectorTextArea.ActionDelegate In observers
    item.Invoke p
  Next
  Return True
End If

Return RaiseEvent mousedown(x,y)</pre>



<p>This code will invoke all the registered Observers for the active word detected under the cursor.</p>



<h3 class="wp-block-heading">Registering the Active Words</h3>



<p>We need a way to inform the instances about the active words to be aware of. We could do that from a Constructor or using a Computed Property. In this case, we will use a method for assigning the received Dictionary of Pairs to the Property in charge of storing that information. Select <code>Insert &gt; Method</code> and use this data in the associated Inspector Panel:</p>



<ul class="wp-block-list"><li><b>Name</b>: setDictionary.</li><li><b>Parameters</b>: d As Dictionary.</li><li><b>Scope</b>: Public.</li></ul>



<p>In the associated Code Editor, put this simple line of code:</p>



<pre class="wp-block-preformatted">linkedWords = d</pre>



<h3 class="wp-block-heading">Registering (and Deregistering) Observers</h3>



<p>As we have said, the class will be able to react to the active words, so we need to provide a couple of methods to register and deregister Observers at any time. Use the following information for the first method:</p>



<ul class="wp-block-list"><li><b>Method Name</b>: registerObserver.</li><li><b>Parameters</b>: observer as ActionDelegate.</li><li><b>Scope</b>: Public.</li></ul>



<p>And write this line of code in the associated Code Editor:</p>



<pre class="wp-block-preformatted">if observer &lt;&gt; nil then observers.add observer</pre>



<p>Add a second method that will be in charge of deregistering an Observer. Use the following data for that:</p>



<ul class="wp-block-list"><li><b>Method Name</b>: deleteObserver.</li><li><b>Parameters</b>: observer As LinkDetectorTextArea.ActionDelegate.</li><li><b>Scope</b>: Public.</li></ul>



<p>This is the code that will search and remove the received <code>ActionDelegate</code> from the instance Array of Observers:</p>



<pre class="wp-block-preformatted">If observer &lt;&gt; Nil Then
  Var n As Integer = observers.IndexOf(observer)
  observers.RemoveAt(n)
end</pre>



<h3 class="wp-block-heading">Regular Expressions to the Rescue …&nbsp;and Styling!</h3>



<p>Finally, add a couple of methods to finish the TextArea subclass. These will be Private for the class, auxiliary methods called mainly from the Event Handlers. The first one is the method that does the matching with the received candidate and upon finding a match, will return the corresponding data pair to the caller. To do this, add a new Method using the following data:</p>



<ul class="wp-block-list"><li><b>Method Name</b>: wordInDictionary.</li><li><b>Parameters</b>: word As string, leftposition As integer, RightPosition As integer.</li><li><b>Return Type</b>: Pair.</li><li><b>Scope</b>: Private.</li></ul>



<p>And write the following code in the associated Code Editor:</p>



<pre class="wp-block-preformatted">#Pragma Unused RightPosition

Var theRightPosition As Integer
Var re As New RegEx
re.SearchPattern = "[a-zA-Z]+"
Var rm As RegExMatch
rm = re.Search(word)

If rm &lt;&gt; Nil Then 
  Var foundword As String = rm.SubExpressionString(0)
  Var characterPosition As Integer = word.LeftBytes(rm.SubExpressionStartB(0)).Length
  word = foundword
  leftposition = leftposition + characterPosition
  therightposition = leftposition + word.Length
End If

If linkedWords.HasKey(word) Then Return New pair(word,leftposition.ToString+"-"+ theRightPosition.ToString)

Var blu As Integer
Var dictionaryKeys() as variant = linkedWords.Keys

for each thekey as string in dictionaryKeys  
  If thekey.IndexOf(word) &lt;&gt; -1 Then
    blu = Me.Text.IndexOf(thekey)
    If leftposition &gt;= blu And leftposition &lt;= (blu + thekey.Length) Then
      Var finalposition As Integer =blu+thekey.Length
      Return New pair(thekey,blu.ToText+"-"+finalposition.ToString)
    end if
  end
next

Return nil</pre>



<h3 class="wp-block-heading">Adding Style</h3>



<p>Finally, we need to choose how to inform the user that the word below the cursor is an active word so they can click on it. For this example, I&#8217;ve used the Underline text style, but you can change that. Add the last method for the class using the following data:</p>



<ul class="wp-block-list"><li><b>Method Name</b>: setStyleForWord</li><li><b>Parameters</b>: word As pair, mode As Boolean.</li><li><b>Scope</b>: Private.</li></ul>



<p>Use the <code>mode</code> parameter in order to use the method to apply or delete the style. For example, removing the style from the previous detected active word and styling the new one. Write the following code in the associated Code Editor:</p>



<pre class="wp-block-preformatted">Var cStart, cEnd As Double
cStart = word.Right.StringValue.NthField("-",1).Val
cEnd = word.Right.StringValue.NthField("-",2).Val - cStart

Var t As StyledText

t = Me.StyledText

cstart = If( cstart - 1 &lt; 0, 0, cstart)

t.Underline(cstart, cEnd) = mode</pre>



<h3 class="wp-block-heading">Putting it all together!</h3>



<p>With the subclass finished it is time to do some Window Layout so we can test the subclass functionality. Select the <code>Window1</code> item in the Navigator to access the Window Layout Editor and drag the <code>LinkDetectorTextArea</code> subclass from the Navigator onto the Window Layout. Use the Inspector to change its name to <code>myURLField</code>. Then add three Label controls and an HTMLViewer, both from the Library. The HTMLViewer will show the URL associated with the active word, while one of the three Label controls will show the detected active words. Both the URL loading as the displaying of the detected word will be done by a previously registered Observer (a window method). The finished window layout should look something like this:</p>



<div class="wp-block-image is-style-default"><figure class="aligncenter"><img decoding="async" width="1732" height="1420" src="https://blog.xojo.com/wp-content/uploads/2018/07/TextAreaLinkLayout.png" alt="" class="wp-image-4608"/></figure></div>



<p>Where the text under the &#8220;Sample Text&#8221; label is the one assigned to the <code>Text</code> property of the <code>LinkDetectorTextArea</code> instance.</p>



<p>Now, let&#8217;s add to the <code>Window1</code> object the method that will act as an Observer, select the <code>Add &gt; Method</code> option in combination with the following data:</p>



<ul class="wp-block-list"><li><b>Name</b>: updateContents</li><li><b>Parameters</b>: p as pair</li><li><b>Scope</b>: Public</li></ul>



<p>And put the following code in the associated Code Editor:</p>



<pre class="wp-block-preformatted">linkedControl.Text = p.Left
HTMLViewer1.LoadURL p.Right</pre>



<p>Lastly, add the <code>Open</code> event to the <code>Window1</code> window, adding the following code to the associated Code Editor. This will initialize the <code>LinkDetectorTextArea</code> instance providing the clickable words and their associated URLs:</p>



<pre class="wp-block-preformatted">myURLField.setDictionary New Dictionary("Xojo":"https://www.xojo.com","iOS":"http://www.apple.com/ios/",_
"macOS":"http://www.apple.com/osx/", "Windows":"https://www.microsoft.com/en-US/windows","Linux":"https://es.wikipedia.org/wiki/GNU/Linux",_
"Raspberry Pi":"https://www.raspberrypi.org/","AprendeXojo":"https://www.aprendexojo.com","Web":"https://www.xojo.com/web")

myURLField.registerObserver WeakAddressOf updateContents</pre>



<p>Run the project, move the cursor over the text and you will see the how the active words are underlined on the fly; and if you click on any of them, the Window will display the detected word, while loading the associated URL.</p>



<p>Of course, this can be vastly improved and expanded upon … enjoy!</p>



<p><em>Paul learned to program in BASIC at age 13 and has programmed in more languages than he remembers, with Xojo being an obvious favorite. When not working on Xojo, you can find him talking about retrocomputing at <a href="https://goto10.substack.com" target="_blank" rel="noreferrer noopener">Goto 10</a> and </em>on Mastodon @lefebvre@hachyderm.io.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Singletons and the Web</title>
		<link>https://blog.xojo.com/2020/04/28/singletons-and-the-web/</link>
		
		<dc:creator><![CDATA[Wayne Golding]]></dc:creator>
		<pubDate>Tue, 28 Apr 2020 10:00:00 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=6976</guid>

					<description><![CDATA[The singleton design pattern has its place in the desktop environment where there will be only one user running the application, and when that user quits the app the singleton is destroyed. This doesn't fit the requirements of a multi-user environment such as the web where many users will be accessing the application at once. I recently came across this issue when porting a desktop app to the web which required me to design a singleton class that is session sensitive. Here's a walk through of how I achieved my goal. Please note that scopes are particularly important when creating this class.]]></description>
										<content:encoded><![CDATA[
<p>The Singleton design pattern has its place in the desktop environment where there will be only one user running the application, and when that user quits the app the Singleton is destroyed. This doesn&#8217;t fit the requirements of a multi-user environment such as the web where many users will be accessing the application at once. I recently came across this issue when porting a desktop app to the web which required me to design a Singleton class that is session sensitive. Here&#8217;s a walk through of how I achieved my goal. Please note that scopes are particularly important when creating this class.</p>



<p>If you need a refresher on the Singleton design pattern, read <a href="https://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Design Patterns in Xojo: Singleton</a>.</p>



<p>First, I inserted a class into my project and called it SessionSingleton (if you don&#8217;t name your class SessionSingleton you need to replace all references to that name in your class).</p>



<p>Next, I added a property to that class with the name SessionIdentifier As String with no default value and set as&nbsp;<strong>private</strong>&nbsp;scope. This will hold the Session.Identifier associated with this object.</p>



<pre class="wp-block-preformatted">Protected Property SessionIdentifier as String</pre>



<p>Now add a method called Constructor and make it&nbsp;<strong>private</strong>, this is to prevent the object from being created outside control of the class.</p>



<pre class="wp-block-preformatted">Private Sub Constructor()

End Sub</pre>



<p>Add another method called Constructor with a parameter SessionIdentifier As String and make it&nbsp;<strong>private</strong>. In this method add the code:</p>



<pre class="wp-block-preformatted">Protected Sub Constructor(SessionIdentifier As String)
  Me.SessionIdentifier = SessionIdentifier
  Constructor()
  
End Sub</pre>



<p>This saves the Session Identifier and runs the constructor method (which may be used by you to initialize properties etc. of the object).</p>



<p>Now, add a shared Property mInstances() As SessionSingleton and make it&nbsp;<strong>private</strong>. This will hold the array of session Singletons.</p>



<pre class="wp-block-preformatted">Private Shared Property mInstances() as SessionSingleton</pre>



<p>Lastly, we need to add two&nbsp;<strong>public</strong>&nbsp;Shared Methods. The first is:</p>



<pre class="wp-block-preformatted">Public Shared Function GetInstance(SessionIdentifier As String) as SessionSingleton
  // Find the instance.  If it exists return it.
  For i As Integer = 0 To mInstances.LastRowIndex
    If mInstances(i).SessionIdentifier = SessionIdentifier Then
      Return mInstances(i)
    End If
  Next
  
  // Not found so create a new instance and return it
  mInstances.AddRow(New SessionSingleton(SessionIdentifier))
  System.DebugLog("Creating new instance for Session with ID " + SessionIdentifier)
  
  Return mInstances(mInstances.LastRowIndex)
  
End Function</pre>



<p>This code returns an existing instance or creates and returns a new one.</p>



<p>Now, because a Web application is multi-user app there&#8217;s the need to clean up when a session is closed so we need the second Shared Method:</p>



<pre class="wp-block-preformatted">Public Shared Sub DestroyInstance(SessionIdentifier As String)
  // This function will remove the instance and should be called from the 
  // Session.Closing event
  For i As Integer = 0 To mInstances.LastRowIndex
    If mInstances(i).SessionIdentifier = SessionIdentifier Then
      mInstances(i) = Nil
      mInstances.RemoveRowAt(i)
    End If
  Next
End Sub</pre>



<p>In this code we find the instance that has the identifier of the current session and destroy that object.</p>



<p>To use the class you would:</p>



<pre class="wp-block-preformatted">Var Singleton As SessionSingleton = SessionSingleton.GetInstance(Session.Identifier)</pre>



<p>Or if in a Session Event Handler:</p>



<pre class="wp-block-preformatted">Var Singleton As SessionSingleton = SessionSingleton.GetInstance(Identifier)</pre>



<p>Add the code to the Session.Closing Event handler to clean up.</p>



<pre class="wp-block-preformatted">SessionSingleton.RemoveInstance(Identifier)</pre>



<p>Don&#8217;t forget to replace all references to SessionSingleton to your class name.</p>



<p>You may have noticed I haven&#8217;t excluded an empty string as the SessionIdentifier and indeed have defaulted the constructor to this empty string. This allows me to use this same class in my desktop projects and potentially when handling Special URL&#8217;s in a web project.</p>



<p><em>Wayne Golding has been a Xojo developer since 2005 and is a Xojo MVP. He operates the IT Company&nbsp;<a href="http://www.axisdirect.nz">Axis Direct Ltd&nbsp;</a>which primarily develops applications using Xojo that integrate with Xero www.xero.com. Wayne’s hobby is robotics where he uses Xojo to build applications for his Raspberry Pi, often implementing IoT for remote control.</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Tutorial: Active Words</title>
		<link>https://blog.xojo.com/2018/07/31/tutorial-active-words/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 31 Jul 2018 10:00:50 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[TextArea]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=4605</guid>

					<description><![CDATA[Follow this tutorial to see how you can show active (clickable) words in a text of a TextArea control using the OOP Delegate pattern.]]></description>
										<content:encoded><![CDATA[<p>Follow this tutorial to learn how to create active (clickable) words in a text of a TextArea control using the <b>OOP</b> <a href="https://blog.xojo.com/2016/07/25/make-an-rss-reader-with-xojoin-26-lines-of-code/">Delegate design pattern</a>, which allows you to dynamically change how your app will react when the user clicks on any of these active words. Best of all, this is cross-platform, so you can use it for macOS, Windows and Linux deployments!<span id="more-4605"></span></p>
<p>Our <em>active words</em> will be based on the use of <a href="http://developer.xojo.com/pair"><b>Pairs</b></a>, so one of the pieces of information will be the active word (or words) we want to detect on the text, and the other piece of information for the <b>Pair</b> will be any associated data you want…this is always a String. For example, the associated data could be a link or text you want to show in another control when the user clicks on the word.</p>
<p>For the sake of this tutorial, the class created has some limitations. For example, you can&#8217;t repeat the same word (or same combination of words) assigning them to different actions. If you do that, the class will alway react to the first occurrence found; if you want your code to always react the same to the same active word or words…then that&#8217;s ok. Anyway, this tutorial serves as a good starting point so you can modify and improve it to meet your own needs.</p>
<p>You can download the class with the example project from <a href="https://www.dropbox.com/s/qe9qu5gcx883e1o/LinkDetectorTextArea.zip?dl=1">here</a>.</p>
<h2>TextArea subclass</h2>
<p>This feature will be based in the <a href="http://documentation.xojo.com/api/deprecated/textarea.html"><b>TextArea</b></a> class, so the first step is add a new TextArea control from the <b>Library</b> panel to the <b>Navigator</b>, changing its name to <code>LinkDetectorTextArea</code>. Next, add the following <b>Event Handlers</b> to our TextArea subclass. These will be responsible for following the pointer movement and reacting to the registered active words for the instance:</p>
<ul>
<li><b>Open</b>. Just to assign the <b>Pointer</b> cursor, more appropriate for the kind of functionality this subclass will provide.</li>
<li><b>MouseMove</b>. Here is where we will detect if there is an active word (or combination of words) found under the cursor pointer.</li>
<li><b>MouseDown</b>. This is the Event Handler that will call all the registered <b>Observers</b> when the user clicks on an active word, passing along the detected word and the associated information.</li>
</ul>
<p>As we want to make these events also available for any instance created from our subclass, then we have to create them again as <b>Event Definitions</b>. With the subclass selected in the Navigator, select <code>Insert &gt; Event Definition</code> using the following signatures:</p>
<ul>
<li><b>Event Name. Open</b>.</li>
<li><b>Event Name. MouseMove</b>. Parameters: <code>X as Integer, Y as Integer</code>.</li>
<li><b>Event Name. MouseDown</b>. Parameters: <code>X as Integer, Y as Integer</code>. Return Type: <code>Boolean</code>.</li>
</ul>
<p>Next we will need to add to the class some <b>Private</b> properties used by the added Event Handlers and other methods yet to define. These properties will be set as private because they just need to be accessed from the class itself, and not from other pieces of external code or additional classes inherited from our own subclass:</p>
<ul>
<li><b>Name. boundedWord</b>. Type: <code>Pair</code>. This is the property that will point to the current matched active word from the text.</li>
<li><b>Name. previousBoundedWord</b>. Type: <code>Pair</code>. This property points to the previous matched word from the text.</li>
<li><b>Name. linkedWords</b>. Type: <code>Dictionary</code>. This is the Dictionary that will contain all the active words / additional data pairs.</li>
<li><b>Name. observers()</b>. Type: <code>ActionDelegate</code>. Array containing all the registered observers of the type <code>ActionDelegate</code> yet to define.</li>
</ul>
<p>As we have seen, we need to define a <b>Delegate</b> type for our class. Select <code>Insert &gt; Delegate</code> with the following data:</p>
<ul>
<li><b>Delegate Name</b>: ActionDelegate.</li>
<li><b>Parameters</b>: boundedWord as Pair.</li>
<li><b>Scope</b>: Public.</li>
</ul>
<h3>Assigning the Cursor type</h3>
<p>Select the <code>Open</code> Event and add the following code in the corresponding Code Editor. We simply use this Event for assigning the Arrow cursor type that is more appropriate for the kind of functionality offered:</p>
<pre>Me.MouseCursor = System.cursors.standardpointer
RaiseEvent open</pre>
<h3>Matching the Active Words</h3>
<p>Next, select the <code>MouseMove</code> Event Handler and type the following code in the corresponding Code Editor. This code is in charge of detecting the limits of the word under the cursor and finding if it is one of the active words registered for the class:</p>
<pre>Dim length As Integer = Me.Text.Len
if previousBoundedWord &lt;&gt; nil then
  setStyleForWord(previousBoundedWord, false)
  previousBoundedWord = nil
end if
dim boundLeft, boundRight as integer

Dim startPosition As Integer = Me.CharPosAtXY(x,y)

If CharPosAtxy(x,y) &gt;= length Then
  if boundedWord &lt;&gt; nil then setStyleForWord( boundedWord, false )
  mboundedWord = nil
elseif me.text.mid(startPosition,1) &lt;&gt; chr(32) and me.Text.mid(startPosition,1) &lt;&gt; EndOfLine then
  for n as integer = startPosition DownTo 1
    if me.Text.mid(n-1,1) = chr(32) or me.Text.mid(n-1,1) = EndOfLine then
      boundLeft = n
      exit
    end
  next
  for n as integer = startPosition to length
    if me.Text.mid(n+1,1) = chr(32) or me.Text.mid(n+1,1) = EndOfLine or n = length then
      boundRight = n+1
      exit
    end
  next
end
dim isolatedWord as string = me.Text.mid(boundLeft, boundRight - boundLeft)
dim check as pair = wordInDictionary( isolatedWord, boundleft, boundRight )
if check  &lt;&gt; nil then
  mboundedWord  = check
  if previousBoundedWord = nil then previousBoundedWord = mboundedWord
  setStyleForWord(previousBoundedWord, true)
else
  mboundedWord = nil
end if
RaiseEvent mouseMove(X, Y)</pre>
<h3>Reacting to Active Words</h3>
<p>Finally, select the <code>MouseDown</code> Event Handler and write the following code into the associated Code Editor. This code will invoke all the registered observers for the active word detected under the cursor pointer (if any):</p>
<pre>If linkedWords &lt;&gt; Nil And boundedWord &lt;&gt; Nil Then
  Dim p As New pair(mboundedWord.Left,linkedWords.Value(mboundedWord.Left))
  For Each item As LinkDetectorTextArea.ActionDelegate In observers
    item.Invoke p
  Next
  Return True
End If
Return RaiseEvent mousedown(x,y)</pre>
<h2>Registering the Active Words</h2>
<p>We need a way to inform the instances about the active words it has to be aware of. We could do that from a <b>Constructor</b> or using a <b>Computed Property</b> instead of a regular one. In this case, we will use a method for assigning the received Dictionary of Pairs to the Property in charge of storing that information. So, select <code>Insert &gt; Method</code> and use this data in the associated Inspector Panel:</p>
<ul>
<li><b>Name</b>: setDictionary.</li>
<li><b>Parameters</b>: d As Dictionary.</li>
<li><b>Scope</b>: Public.</li>
</ul>
<p>In the associated Code Editor we just need to put this simple line of code:</p>
<pre>linkedWords = d</pre>
<h2>Registering (and deregistering) Observers</h2>
<p>As we have said, our class will be able to <b>react</b> to the active words, so we need to provide a couple of methods to register and deregister <b>Observers</b> at any time. Use the following information for the first method:</p>
<ul>
<li><b>Method Name</b>: registerObserver.</li>
<li><b>Parameters</b>: observer as ActionDelegate.</li>
<li><b>Scope</b>: Public.</li>
</ul>
<p>And write this line of code in the associated Code Editor:</p>
<pre>if observer &lt;&gt; nil then observers.Append observer</pre>
<p>Add a second method that will be in charge of deregistering an observer. Use the following data for that:</p>
<ul>
<li><b>Method Name</b>: deleteObserver.</li>
<li><b>Parameters</b>: observer As LinkDetectorTextArea.ActionDelegate.</li>
<li><b>Scope</b>: Public.</li>
</ul>
<p>This is the code that will search and remove the received <code>ActionDelegate</code> from the instance Array of observers:</p>
<pre>If observer &lt;&gt; Nil Then
  observers.Remove( observers.IndexOf( observer ) )
end</pre>
<h2>Regular Expressions to the rescue… and Styling!</h2>
<p>Finally we just need to add a couple of methods more for finishing our TextArea subclass. These will be <b>Private</b> for the class, auxiliary methods called mainly from the Event Handlers. The first one will be the method in charge of doing the matching from the received candidate, and if it finds it, then it will return the corresponding pair of data to the caller. For this one, add a new Method using the following data:</p>
<ul>
<li><b>Method Name</b>: wordInDictionary.</li>
<li><b>Parameters</b>: word As string, leftposition As integer, RightPosition As integer.</li>
<li><b>Return Type</b>: Pair.</li>
<li><b>Scope</b>: Private.</li>
</ul>
<p>And write the following code in the associated Code Editor:</p>
<pre>Dim theRightPosition As Integer
dim re as new RegEx
re.SearchPattern = "[a-zA-Z]+"
dim rm as RegExMatch
rm = re.Search(word)
if rm &lt;&gt; nil then
  dim foundword as string = rm.SubExpressionString(0)
  dim characterPosition as integer = word.LeftB(rm.SubExpressionStartB(0)).Len
  word = foundword
  leftposition = leftposition + characterPosition
  therightposition = leftposition + word.Len
end if
if linkedWords.HasKey(word) then Return new pair(word,leftposition.ToText+"-"+ theRightPosition.ToText)
dim blu as integer
dim dictionaryKeys() as variant = linkedWords.Keys
for each thekey as string in dictionaryKeys
  if thekey.InStr(word) &gt; 0 then
    blu = me.text.instr(thekey)
    if leftposition &gt;= blu and leftposition &lt;= (blu + thekey.Len) then
      dim finalposition as integer =blu+thekey.len
      Return new pair(thekey,blu.ToText+"-"+finalposition.totext)
    end if
  end
next
Return nil</pre>
<h3>Adding some style</h3>
<p>Finally, we need a way to inform the user that the word down the pointer cursor is active so she can click on it. For this example I&#8217;ve used the Underline text style, but you can adapt it once you see how this is done. So, let&#8217;s add the last method for the class using the following data:</p>
<ul>
<li><b>Method Name</b>: setStyleForWord</li>
<li><b>Parameters</b>: word As pair, mode As Boolean.</li>
<li><b>Scope</b>: Private.</li>
</ul>
<p>We use the <code>mode</code> parameter so we can use the method to apply or delete the style to the received word; removing for example the style from the previous detected active word and styiling the new one. Write the following code in the associated Code Editor:</p>
<pre>Dim cStart, cEnd, sStart As Double
cStart = NthField(word.Right,"-",1).Val
cEnd = NthField(word.Right,"-",2).Val - cStart
Dim t As StyledText
t = Me.StyledText
cstart = If( cstart - 1 &lt; 0, 0, cstart-1)
t.Underline(cstart, cEnd) = mode</pre>
<h2>Putting it all together!</h2>
<p>With our subclass finished it is time to do some Window Layout so we can test the subclass functionality. Select the <code>Window1</code> item in the Navigator to access the Window Layout Editor and drag the <code>LinkDetectorTextArea</code> subclass from the Navigator onto the Window Layout in order to create a new instance. Use the Inspector to change its name to <code>myURLField</code>. Then add three <b>Label</b> controls from the Library and an HTMLViewer. The HTMLViewer will show the URL associated with the active word, while one of the three Label controls will show the detected active words. Both the URL loading as the displaying of the detected word will be done by a previously registered observer (a window method). The Finished window layout should be something like this:</p>
<p><img decoding="async" class="size-full wp-image-4608 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/07/TextAreaLinkLayout.png" alt="" width="1732" height="1420" /></p>
<p>Where the text under the &#8220;Sample Text&#8221; label is the one assigned to the <code>Text</code> property of the <code>LinkDetectorTextArea</code> instance.</p>
<p>Let&#8217;s add now to the <code>Window1</code> object the method that will act as an observer, so select the <code>Add &gt; Method</code> option in combination with the following data:</p>
<ul>
<li><b>Name</b>: updateContents</li>
<li><b>Parameters</b>: p as pair</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>And put the following code in the associated Code Editor:</p>
<pre>linkedControl.Text = p.Left
HTMLViewer1.LoadURL p.Right</pre>
<p>Lastly, add now the <code>Open</code> event to the <code>Window1</code> window, adding the following code to the associated Code Editor. Here is where we will initialize our <code>LinkDetectorTextArea</code> instance providing the clickable words and their associated URL:</p>
<pre>myURLField.setDictionary New Dictionary("Xojo":"http://www.xojo.com","Web":"https://www.w3.org","iOS":"http://www.apple.com/ios/",_"OS X":"http://www.apple.com/osx/", "Windows":"https://www.microsoft.com/en-US/windows","Linux":"https://es.wikipedia.org/wiki/GNU/Linux",_
"Raspberry Pi":"https://www.raspberrypi.org/","AprendeXojo":"http://www.aprendexojo.com")
myURLField.registerObserver WeakAddressOf updateContents</pre>
<p>Run the project, move the pointer cursor over the text and you will see the how the detected active words are underlined on the fly; and if you click on any of them, then the Window will display the detected word, loading the associated URL.</p>
<p>Of course, this can be vastly improved…and that is something that maybe you can do in any number of ways!</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
<p>*<a href="https://www.aprendexojo.com/2016/04/linkdetectortextarea-subclase-y-patron-observer/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>An Insider&#8217;s Top 10 Code-Free Tips To Being A Skilled Programmer</title>
		<link>https://blog.xojo.com/2017/09/13/an-insiders-top-10-code-free-tips-to-being-a-skilled-programmer/</link>
		
		<dc:creator><![CDATA[Geoff Perlman]]></dc:creator>
		<pubDate>Wed, 13 Sep 2017 10:03:55 +0000</pubDate>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Beginner Tips]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Software Development]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2701</guid>

					<description><![CDATA[Whether you’re new to programming or an experienced developer, there are some things you’ll never find in a reference manual. We’re passionate about writing good code - so we put together this list of 11 tips to be a better programmer.]]></description>
										<content:encoded><![CDATA[<p>At Xojo we&#8217;re a company of programmers who work with programmers and after 21 years or so, we like to think we know our stuff. In honor of International Programmer&#8217;s Day today, we&#8217;d like to offer our experience in the form of a listicle <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Whether you’re new to programming or an experienced developer, there are some things you’ll just never find in a reference manual. We’re passionate about writing good code and these are our 10 tips to be a better programmer.</p>
<p><span id="more-2701"></span></p>
<h2><strong>1. Be curious &#8211; ask questions and seek answers</strong></h2>
<p>Computers aren&#8217;t magical. They do things in a methodical and predictable way. If you are curious about why they are doing what they are doing, you can learn a lot.</p>
<p><img loading="lazy" decoding="async" class="size-medium" src="https://media.giphy.com/media/xTiN0v1R0c1rPsrEU8/giphy.gif" width="500" height="500" /></p>
<h2><strong>2. Be methodical</strong></h2>
<p>Computers follow the steps we tell them in our code one after the other (even in multithreaded programs although there can be fun side effects in this case). They start at the beginning and work their way along until they either finish, the user quits them or maybe &#8211; unfortunately- they crash. But they just do what we tell them.</p>
<h2><strong>3. Read the docs</strong></h2>
<p>No matter how many times you do something if you have problems read the documentation. You may learn something new from them even if you&#8217;ve been doing it for years. (This ties into point #1 as well). Documentation is there to help you learn how to use things.</p>
<p><img loading="lazy" decoding="async" class="size-medium aligncenter" src="https://media.giphy.com/media/SEm3csrqNDeLe/giphy.gif" width="500" height="347" /></p>
<h2><strong>4. Try things out</strong></h2>
<p>It usually can&#8217;t hurt… well, unless you&#8217;re writing something that may wipe out data on a hard drive, etc. In that case, you should have &#8220;testing&#8221; set up to be able to try out ideas &#8211; version control systems can help here.</p>
<h2><strong>5. Don’t be afraid to get help</strong></h2>
<p>Ask colleagues, friends, forums or wherever else you can get help AFTER you&#8217;ve read the docs. Being self-reliant and self-sufficient is, in many ways, the mark of a good programmer. They try out things and exhaust the resources they have ready access to before they come asking for help in emails lists and forums. Members appreciate it when they can say, &#8220;Did you try &#8230;&#8221; and the reply is, &#8220;I tried everything like &#8230;.&#8221; with a long of things already tried. Often we see forums, Twitter and Facebook are used as the first thing consulted without having looked over docs or existing samples and examples.</p>
<p><img loading="lazy" decoding="async" class="size-medium aligncenter" src="https://media.giphy.com/media/OcEp8ZXt3Pri0/giphy.gif" width="430" height="228" /></p>
<h2><strong>6. Learn from those who have come before you</strong></h2>
<p>The best thing a person can start out doing is maintenance work, you’ll learn good habits and those bad habits to avoid in code. And applying steps 1 to 5 along the way will result in learning a lot more. And hopefully you’ll have a good mentor!</p>
<h2><strong>7. Be a mentor</strong></h2>
<p>Sharing what you know with those less experienced helps you become better at what you do. You HAVE to know your subject VERY well in order to teach someone. Teaching is the best way to learn, even if you&#8217;re not that good, but answering questions (and maybe researching the answer) will only help you too.</p>
<h2><strong>8. Learn about design patterns</strong></h2>
<p>They&#8217;re invaluable when it comes to figuring out how to approach and solve a commonly occurring problem. Some key design patterns include: <a href="http://blog.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/">Observer</a> and <a href="http://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton</a>.</p>
<h2><strong>9. Review code, acquire ideas, refactor, and then do it again and again and again</strong></h2>
<p>Code is never &#8220;done&#8221;. It always needs to evolve, be updated, or rewritten. Get in the habit of reviewing your code with other programmers you work with. Even when you think it&#8217;s perfect, a different set of eyes can often find something you hadn&#8217;t considered or an optimization. A code review revealed a great one for me that I wrote about <a href="https://blog.xojo.com/2017/08/30/pro-tip-inserting-text-quickly-in-a-xojo-ios-app/">here</a>.</p>
<h2><strong>10. Be brave</strong></h2>
<p>Don&#8217;t be afraid to tackle hard problems or to fail. It&#8217;s how we learn.</p>
<h2><strong>Bonus Tip: Look at various programming languages</strong></h2>
<p>Even check out ones you&#8217;ll likely never use! It helps you gain perspective on how other languages approach solutions and problems. Sometimes that perspective is whats needed to figure out how to solve a problem.</p>
<p><img loading="lazy" decoding="async" class="size-medium aligncenter" src="https://media.giphy.com/media/13avrMpiUeW6Va/giphy.gif" width="478" height="320" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Patterns in Xojo: Observer, Part II</title>
		<link>https://blog.xojo.com/2016/11/15/design-patterns-observer-part-ii/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 15 Nov 2016 07:24:08 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<category><![CDATA[Observer]]></category>
		<category><![CDATA[Singleton]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2070</guid>

					<description><![CDATA[In previous blog entries we saw how easy it is to implement the Design Pattern Singleton and how we can find the Observer Design Pattern&#8230;]]></description>
										<content:encoded><![CDATA[<p>In previous blog entries we saw how easy it is to implement the Design Pattern <a href="http://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton</a> and how we can find the <a href="http://blog.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/">Observer</a> Design Pattern already implemented on several Xojo features by default, greatly simplifying our code and interaction between the objects. Now, as promised, it is time to put it all in practice, creating our own Notification Center: a class that will allow us to share the same unique instance for the entire App (Singleton), and that can use any object in order to register itself for receiving notifications by the observed Control, for one or more message (the notifications themselves).<span id="more-2070"></span><br />
In addition, the designed Class will allow you to unsubscribe any of the previously registered objects, either to stop receiving notifications by the observed object at all, or just some of the previously registered notifications.</p>
<p>The <a href="http://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton</a> and <a href="http://blog.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/">Observer</a> Design Patterns have been described in previous blog entries and I highly recommend to read them now so you can get the flavor of the fundamentals behind them. I&#8217;ll wait here for you, I promise! Then we will deal with the code that varies to implement our <strong>NotificationCenter</strong> class, and to put it in practice with a Desktop example project.</p>
<p>Of course, before of continuing reading, you can <a href="https://www.dropbox.com/s/ry6ip9oe5jkm4av/Xojo-Observer-II.zip?dl=1">download the example project,</a> run it and review the code to get a first glance of what it does and how it works. Then, you can come back and continue reading if you want to better understand the <strong>NotificationCenter</strong> class inner, or how other objects can use this class.</p>
<h2>The NotificationCenter Class</h2>
<p>Execute the <strong>Xojo</strong> IDE and create a new Desktop project. Add a new class using <strong>Insert &gt; Class</strong>. Go to the Inspector and change the <strong>Name</strong> attribute to &#8220;NotificationCenter&#8221;. This is the name of the new class we are designing (and, thus, a new Data Type).</p>
<p>With the new class still selected in the Navigator (the leftmost column on the Xojo IDE), add a new <strong>Shared Property</strong> (<strong>Insert &gt; Shared Property</strong>). Use the Inspector again to change the <strong>Name</strong> attribute to &#8220;Instance&#8221;, the Type field to &#8220;NotificationCenter&#8221; and the <strong>Scope</strong> to &#8220;Private&#8221;. (You know, a Shared Property or Shared Method are those that you can access from the class itself, without needing to create previously a new instance from the class.)</p>
<p>Add a second Property to the class, this time via <strong>Insert &gt; Property</strong> (this is, an instance property). Use this values on the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> Objects</li>
<li><strong>Type:</strong> Xojo.Core.Dictionary</li>
<li><strong>Scope:</strong> Private</li>
</ul>
<p>Next, add a new Method (<strong>Insert &gt; Method</strong>). Use the Inspector to choose the <strong>Constructor</strong> option from the &#8220;Method Name&#8221; dropdown menu, and set the method Scope to Private.</p>
<p>Write the following code on the associated Code Editor for the method:</p>
<pre>Objects = new xojo.core.Dictionary</pre>
<p>Defining the Constructor method with a Private scope prohibits the creation of several instances from the class. Instead of that, the class consumers will have to use the convenience method defined by us in order to retrieve the same —and unique— instance for all the cases.</p>
<p>So, now we will add a new Shared Method using <strong>Insert &gt; Shared Method</strong>. Use the Inspector to put the following values on the created method:</p>
<ul>
<li><strong>Name:</strong> SharedInstance</li>
<li><strong>Return Type:</strong> NotificationCenter</li>
</ul>
<p>And write the following code in the associated Code Editor for the method:</p>
<pre>if instance = nil then instance = new NotificationCenter
Return instance</pre>
<p>These are the wires to write our Singleton class and to define our Data Model: the &#8220;Objects&#8221; property of data type <a href="http://developer.xojo.com/xojo-core-dictionary"><strong>Xojo.Core.Dictionary</strong></a>. This property will be responsible for storing the registered objects as observers of the desired Control(s), as well as the messages for whom it is interested in receiving notifications for the observed object(s). Probably this is better understood in the following figure:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-2072 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/11/DataModel.png" alt="Data Model for Notification Center Class" width="485" height="551" />That is, the &#8220;Observers&#8221; Xojo.Core.Dictionary Property uses as <strong>Key</strong> any object of <a href="http://developer.xojo.com/rectcontrol">RectControl</a> data type (the observed object). The associated value for that key is a new Xojo.Core.Dictionary, whose entries will use as Key the Notification (message as Text data type) for what an object wants to register as observer for such Control.</p>
<p>This way, one same object can be registered to several controls and also to several messages (Notifications) on one or several controls.</p>
<p>Finally, the associated value for every <strong>Key</strong> on this second Xojo.Core.Dictionary is an <strong>Array</strong> data type whose items are instances of the <strong>NotificationReceiver</strong> data type.</p>
<p>I know, I know… Stop. Breathe. Execute again the example project. Review the code on the &#8220;Register&#8221; method to get a better grasp… and back to follow!</p>
<h3>Registering Observers</h3>
<p>With the class still selected on the Navigator, add a new method (<strong>Insert &gt; Method</strong>) using the following values. This is the method responsible for registering the new observers on the shared Notification Center instance:</p>
<ul>
<li><strong>Name:</strong> Register</li>
<li><strong>Parameters:</strong> sourceControl as NotificationReceiver, observedObject as RectControl, message as Text</li>
<li><strong>Scope:</strong> Public</li>
</ul>
<p>As you can see in &#8220;Parameters&#8221;, the first parameter is the Observer object (this is the interesed object in receiving the notifications); the second parameter is the observed object (that is from which we want to receive notifications); and the third parameter is the message from which we are interested in receiving the notifications by the observed object.</p>
<p>Write the following code on the Code Editor associated for this method:</p>
<pre>dim observedObjects as xojo.Core.Dictionary = Objects.Lookup( observedObject, new xojo.core.Dictionary )
dim messages() as NotificationReceiver
if observedObjects.HasKey( message ) then messages = observedObjects.Value( message )
messages.Append sourceControl
observedObjects.Value( message) = messages
objects.Value( observedObject ) = observedObjects</pre>
<h3>Sending Notifications</h3>
<p>Now is time to add to the class the method responsible to send the notifications to those objects interested in receiving them from any previously registered object. Insert a new method for the <strong>NotificationCenter</strong> class and use the following values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> sendNotification</li>
<li><strong>Parameters:</strong> sourceObject as RectControl, message as text, value as Auto</li>
<li><strong>Scope:</strong> Public</li>
</ul>
<p>And the following code in the Code Editor associated with the method:</p>
<pre>dim observedObjects as xojo.Core.Dictionary = objects.Lookup(sourceObject, nil)
if observedObjects &lt;&gt; nil then
  dim sourceObjects() as NotificationReceiver
  if observedObjects.haskey(message) then sourceObjects = observedObjects.Value( message )
  for n as integer = 0 to sourceObjects.Ubound
    dim target as NotificationReceiver = sourceObjects(n)
    target.valueReceived( value, message )
  next
end if</pre>
<p>As you can see, the first parameter of the method is the control that wants to send a notification (second parameter) to all the possible registered objects, passing the value that such objects can be interested to receive for processing it (third parameter).</p>
<h3>Stop receiving Notifications</h3>
<p>However, it is probable that one object wants to stop receiving notifications from any previously registered control. For that, we need to add a new method to the NotificationCenter class using this values:</p>
<ul>
<li><strong>Name:</strong> RemoveObserver</li>
<li><strong>Parameters:</strong> sourceControl as NotificationReceiver</li>
</ul>
<p>And the following code on the associated Code Editor:</p>
<pre>for each observedObjects as xojo.Core.DictionaryEntry in objects
  dim d as xojo.Core.Dictionary = objects.Value(observedObjects.Key)
  for each messagesForObject as xojo.Core.DictionaryEntry in d
    dim sourceObjects() as NotificationReceiver = d.Value(messagesForObject.Key)
    for n as integer = sourceObjects.Ubound DownTo 0
      if sourceObjects(n) = sourceControl then sourceObjects.Remove(n)
    next
  next
next</pre>
<h3>Stop receiving some Notifications</h3>
<p>It may also be the case that one object wants to unsuscribe from the Notification Center to stop receiving just one particular notification. For that, add a new method and use the following values on the Inspector:</p>
<ul>
<li><strong>Name:</strong> removeObserverForMessage</li>
<li><strong>Parameters:</strong> sourceControl as NotificationReceiver, message as text</li>
</ul>
<p>And write the following code in the associated Code Editor:</p>
<pre>for each observedObjects as xojo.Core.DictionaryEntry in objects
  dim d as xojo.Core.Dictionary = objects.Value(observedObjects.Key)
  for each messagesForObject as xojo.Core.DictionaryEntry in d
    if messagesForObject.Key = message then
      dim sourceObjects() as NotificationReceiver = d.Value(messagesForObject.Key)
      for n as integer = sourceObjects.Ubound DownTo 0
        if sourceObjects(n) = sourceControl then sourceObjects.Remove(n)
      next
    end if
  next
next</pre>
<h2>One Class Interface that runs them all: NotificationReceiver</h2>
<p>Along the implementation of our Notification Center class we have seen several times the reference to the <strong>NotificationReceiver</strong> data type. This is what we are going to get our hands on next.</p>
<p>In fact this is a <strong>Class Interface;</strong> what means that it works as a &#8220;glue&#8221; in order that any object can implement their defined methods. This way the objects can be seen as their native class and also as an instance from <strong>NotificationReceiver</strong>, so they can be registered as observers on the Notification Center independently the native class they are based on.</p>
<p>Use <strong>Insert &gt; Class</strong> Interface to add a new Class Interface to the project. Next, write the following values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> NotificationReceiver</li>
</ul>
<p>With the Class Interface still selected in the Navigator, add a new method using the following signature in the Inspector:</p>
<ul>
<li><strong>Method Name:</strong> valueReceived</li>
<li><strong>Parameters:</strong> value as Auto, message as Text</li>
</ul>
<p>Done! Depending on your own needs, you can add more methods for the interface class in combination with the Notification Center class itself.</p>
<h2>Testing the Notification Center</h2>
<p>Now it is time to design the user interface in order to test the Notification Center class. The changes made on a <strong>TextField</strong> control will automatically update the contents of a <strong>Label</strong> control, a <strong>Slider</strong> control, a <strong>ListBox</strong> control and a <strong>Canvas</strong> control. Moreover, the Label instance will subscribe in the Notification Center to receive two types of notifications, changing his behaviour (the text shown) based on the received notification.</p>
<p>We will also add a couple of <strong>CheckBox</strong> controls to test the functionality to unsuscribe the Label control from all or just some notifications.</p>
<p>But before we start with that, and as we have seen in the previous step, we need that all the objects that want to be able to register on the Notification Center be of the <strong>NotificationReceiver</strong> data type. That means that we need to create our own subclases for the Label, Slider, ListBox and Canvas controles. Let&#8217;s start with the Label!</p>
<h3>Label Subclass</h3>
<p>Create a new sublcass for the Label Class. You can do that selecting the Label control from the <strong>Library</strong> and choosing the &#8220;New Subclass&#8221; option from the contextual menu; or you can drag and drop the control from the Library to the Navigator. Anyway, the result will be the same: you will have created a new subclass with the name &#8220;CustomLabel&#8221; (it can vary, depending the Xojo release you use). By the way, you also can use <strong>Insert &gt; Class</strong> in order to create a new subclass.</p>
<p>Regardless of the method used to create the new subclass, choose it in the Navigator and use this values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> MyLabel</li>
<li><strong>Super:</strong> Label // This way, our sublcass will inherit all the methods, events and properties from the base class.</li>
<li><strong>Interfaces:</strong> Click on the button and choose &#8220;NotificationReceived&#8221; from the resulting panel/Window. Confirm the selection clicking on the &#8220;OK&#8221; button.</li>
</ul>
<p>As result of the last action, Xojo will automatically added the ValueReceived method to the class. Write the following code in the associated Code Editor:</p>
<pre>RaiseEvent newValueReceived value, message</pre>
<p>Here we raise a new event (not defined yet), so every instance from the class can be in charge of implement the real behavior in base of the parameters received.</p>
<p>So, with the &#8220;MyLabel&#8221; class still selected, use <strong>Insert &gt; Event Definition</strong> to add the event definition we need. Use the following values in the associated Inspector:</p>
<ul>
<li><strong>Event Name:</strong> newValueReceived</li>
<li><strong>Parameters:</strong> value as auto, message as Text</li>
</ul>
<h3>Slider Subclass</h3>
<p>Add a new subclass and use these values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> MySlider</li>
<li><strong>Super:</strong> Slider</li>
<li><strong>Interfaces:</strong> Add the NotificationReceiver Class Interface as seen in the previous step.</li>
</ul>
<p>Write the following code for the ValueReceived method:</p>
<pre>RaiseEvent newValueReceived val(value)</pre>
<p>And add the event definition using <strong>Insert &gt; Event Definition</strong>, as we have seen in the previous step. Use this signature in the Inspector:</p>
<ul>
<li><strong>Event Name:</strong> newValueReceived</li>
<li><strong>Parameters:</strong> value as integer</li>
</ul>
<h3>ListBox Subclass</h3>
<p>Let&#8217;s create now the subclass for the ListBox, following basically the same steps already done with the previous subclasses. Use the following values:</p>
<ul>
<li><strong>Name:</strong> MyListBox</li>
<li><strong>Super:</strong> ListBox</li>
<li><strong>Interfaces:</strong> NotificationReceiver</li>
</ul>
<p>Write the following code in the Code Editor associated with the ValueReceived method added by the Class Interface:</p>
<pre>RaiseEvent newValueReceived val(value)</pre>
<p>And add the corresponding Event Definition using this signature:</p>
<ul>
<li><strong>Event Name:</strong> newValueReceived</li>
<li><strong>Parameters:</strong> value as integer</li>
</ul>
<h3>Canvas Subclass</h3>
<p>We have arrived to the last subclass definition for our example project. Add a new subclass to the project and use this values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> MyCanvas</li>
<li><strong>Super:</strong> Canvas</li>
<li><strong>Interfaces:</strong> NotificationReceiver</li>
</ul>
<p>Write the following code for the ValueReceived method:</p>
<pre>dim s as string = value
newValue = s.ToText
me.Refresh</pre>
<p>Next, use <strong>Insert &gt; Event Handler</strong> to add the Paint event to the subclass. Write this code in the associated Code Editor:</p>
<pre>dim size as integer = val(newValue)
g.TextSize = size
dim centerx as integer = g.Width/2 - g.StringWidth(newValue)/2
dim centery as integer = g.Height/2+g.StringHeight(newValue,g.Width)/2
g.ForeColor = rgb(size, size, size)
g.FillRect(0,0,g.Width,g.Height)
g.ForeColor = if(size &lt;= 50, rgb(255,255,255), rgb(0,0,0))
g.DrawString(newValue,centerx,centery)</pre>
<p>Lastly, add a new property to the subclass using <strong>Insert &gt; Property</strong>, and using this values:</p>
<ul>
<li><strong>Name:</strong> newValue</li>
<li><strong>Type:</strong> Text</li>
<li><strong>Scope:</strong> Private</li>
</ul>
<h2>Designing the User Interface</h2>
<p>Once we have created the subclasses for the Controls we will use as observers in our example app, it is time to design the user interface. For that, choose the window by default for the project (Window1).</p>
<p>Xojo will show the <strong>Layout Designer</strong> for the selected Window. Drag the subclass controls from the Navigator (or from the Library) so they are arranged as shown in this picture. In addition, drag a couple of CheckBox controls and one TextField too from the Library to the layout.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2073" src="https://blog.xojo.com/wp-content/uploads/2016/11/Captura-de-pantalla-2016-11-10-a-las-13.23.55.png" alt="captura-de-pantalla-2016-11-10-a-las-13-23-55" width="910" height="534" /></p>
<p>Choose the label instance (with the name &#8220;Label2&#8221; in the example project) and use <strong>Insert &gt; Event Handler</strong> to add the &#8220;newValueReceived&#8221; event handler previously defined in our class. Write the following code in the associated Code Editor:</p>
<pre>dim s as string = value
Select case message
  case "valueChanged"
    me.Text = "Value on source Control: "+ s
  case "charValue"
    me.Text = "ASCII Code for last keystroke: "+ str(asc(s))
End Select</pre>
<p>As you can see, the event uses the received message to decide how to work with the value sent by the observed object. In one case it will show the value as is, and for the other it will show the ASCII code for the value received as Text.</p>
<p>Select now the Slider instance (with the name &#8220;Slider1&#8221; in the example project), and repeat the action to add the Event Handler &#8220;newValueReceived&#8221; to the control. Write the following code in the associated Code Editor:</p>
<pre>me.Value = value</pre>
<p>In this case, the control will simply assign to his &#8220;value&#8221; property the value received.</p>
<p>Select now the ListBox instance (&#8220;ListBox1&#8221; in the example project). Add the Event Handler &#8220;newValueReceived&#8221; and write this line of code:</p>
<pre>me.ListIndex = value</pre>
<p>We will also add the &#8220;Open&#8221; Event Handler, so we can populate some default values to use in the example. Once we&#8217;ve added this event, write the following code in the associated Code Editor:</p>
<pre>for n as integer = 0 to 99
  me.AddRow str(n)
next</pre>
<p>Lastly, select the TextField instance (&#8220;TextField1&#8221; in the example project), and add the &#8220;Keydown&#8221; and &#8220;Lost Focus&#8221; Event Handlers. Once added, select the <strong>KeyDown</strong> event handler and write the following code:</p>
<pre>dim myNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
myNotificationCenter.sendNotification(me,"charValue",key)</pre>
<p>Next, select the <strong>LostFocus</strong> event and writhe the following code:</p>
<pre>dim myNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
mynotificationcenter.sendNotification(me,"valueChanged",me.Text)</pre>
<p>For both cases, we retrieve the shared instance from the Notification Center class and publish a new notification, passing along the own control as first argument (acting as originator), the message or published notification as second argument, and the value sent as the third argument. From this point on, the Notification Center will be in charge of propagate the received notification to all the interested objects.</p>
<h3>Subscribing and Unsubscribing to Notifications</h3>
<p>Let&#8217;s get in charge of the user interface controls whose function is to enable and disable the notifications for our MyLabel instance (Label1).</p>
<p>Select the <strong>CheckBox1</strong> control, add the Action event handler and write the following code in the associated Code Editor:</p>
<pre>dim miNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
select case me.Value
  case true
    miNotificationCenter.register(Label2,TextField1, "valueChanged")
    miNotificationCenter.register(Label2, TextField1, "charValue")
  case False
    miNotificationCenter.removeObserver(Label2)
    CheckBox2.value = false
end select</pre>
<p>Select now the <strong>CheckBox2</strong> control, add the Action event handler and write the following code:</p>
<pre>dim miNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
select case me.Value
  case true
    miNotificationCenter.register(Label2,TextField1, "valueChanged")
  case False
    miNotificationCenter.removeObserverForMessage(Label2,"valueChanged")
end select</pre>
<p>As you can see, in the first block of code we register the &#8220;Label2&#8221; control so it can receive both notifications when the checkbox value is <strong>True</strong>, and unsubscribe the control from receiving any notification when the checkbox is <strong>False</strong>. For the second block of code, the &#8220;Label2&#8221; control just subscribe or unsubscribe for one of the two notifications, respectively.</p>
<h2>Starting engines!</h2>
<p>What we need to put all to work? Add the <strong>Open</strong> event handler to &#8220;Window1&#8221; and write the following code.</p>
<pre>dim miNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
miNotificationCenter.register(Label2,TextField1, "valueChanged")
miNotificationCenter.register(Label2, TextField1, "charValue")
miNotificationCenter.register(Listbox1,TextField1, "valueChanged")
miNotificationCenter.register(Slider1,TextField1, "valueChanged")
miNotificationCenter.register(canvas1,TextField1, "valueChanged")</pre>
<p>This code will register the interested controls (observers) to the Notification Center for those Notifications they are interested in. Of course, this can also be done inside the Open event handler for every interested control!</p>
<h2>In brief</h2>
<p>As we have seen, with the combination of the <strong>Observer</strong> and <strong>Singleton</strong> Design Patterns, and the help of one <strong>Class Interface</strong> definition, we have created our own Notification Center from scratch to greatly automatice and simplify the communication between the objects, their processes and easying also the maintenance and extension of the app functionallity.</p>
<p>You can watch <a href="https://youtu.be/bCsGtHKM5GA">the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="http://www.aprendexojo.com/2016/11/patrones-de-diseno-observer-y-ii/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Patterns in Xojo: Observer, Part 1</title>
		<link>https://blog.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 15 Jun 2016 00:00:00 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/</guid>

					<description><![CDATA[Learn how easy is it is to implement the Observer Design Pattern using Xojo and UI controls like the PushButton, the BevelButton, and the Timer class. ]]></description>
										<content:encoded><![CDATA[<p>In a previous post we saw how to implement the <a href="../../../com/xojo/blog/design-patterns-in-xojo-singleton.html" target="_blank" rel="noopener">Singleton Design Pattern in our Xojo apps</a>. Now, it is time to look at another useful Design Pattern you can use in your apps: the Observer Design Pattern. This one solves the kind of question &#8220;How can the &#8216;x&#8217; controls be automatically notified every time there are changes on &#8216;y&#8217;?&#8221; Sound interesting? Let&#8217;s see how!</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/Faro.jpgt1466486449161ampwidth200ampheight241" sizes="auto, (max-width: 200px) 100vw, 200px" alt="Faro.jpg" width="200" height="241" /></p>
<p>In fact, this is the first of a two part series regarding the Observer Design Pattern. This one will focus on how easy is to implement using the interfaces already available in Xojo for UI controls like the <a href="http://documentation.xojo.com/api/deprecated/pushbutton.html" target="_blank" rel="noopener"><strong><strong>PushButton</strong></strong></a>, the <a href="http://documentation.xojo.com/api/deprecated/bevelbutton.html" target="_blank" rel="noopener"><strong><strong>BevelButton</strong></strong></a>, and also for the <a href="http://documentation.xojo.com/api/language/timer.html" target="_blank" rel="noopener"><strong>Timer</strong></a> class. In Part 2, we will see how to implement the Observer Design Pattern from scratch, using our own Classes and Interfaces, so it will be easier to understand the mechanisms behind this Pattern and how to use it.<br />
<span id="more-268"></span></p>
<h2>Why to use the Observer Design Pattern?</h2>
<p>Let&#8217;s suppose we want to create an app where several <a href="http://documentation.xojo.com/api/deprecated/canvas.html" target="_blank" rel="noopener"><strong><strong>Canvas</strong></strong></a> controls have to randomly change their color every time we push a button. Of course, we can approach this from several angles. For instance, we can put the code in charge of iterating every window control into the &#8220;Action&#8221; event of the PushButton control, changing the color only if the iterated item is an instance of our Canvas based subclass (let&#8217;s call this class the ColorPatch class).</p>
<p>That will work, but undoubtedly is not the most elegant, flexible and decoupled of the possible solutions.</p>
<p>A better way of approaching this problem is using the <a href="https://en.wikipedia.org/wiki/Observer_pattern" target="_blank" rel="noopener"><strong><strong>Observer Design Pattern</strong></strong></a>. This one consists on the ability for any class instance to register itself into other instance, in order to receive a message every time there is an action in the object we have registered on.</p>
<p>Sounds weird? Ok, it&#8217;s like a group of people interested in one event saying the organizer: &#8220;hey, notify me once the tickets are available for purchase&#8221;. Best of all, you already can do this kind of things via the <a href="http://documentation.xojo.com/api/language/actionsource.html" target="_blank" rel="noopener">ActionSource</a> and <a href="http://documentation.xojo.com/api/language/actionnotificationreceiver.html" target="_blank" rel="noopener">ActionNotificationReceiver</a> Class Interfaces.</p>
<p>In fact, the ActionSource and ActionNotificationReceiver work together, because an ActionSource instance (PushButton, BevelButton or Timer) will call the <a href="http://documentation.xojo.com/api/language/actionnotificationreceiver.html#actionnotificationreceiver-performaction" target="_blank" rel="noopener"><strong><strong>PerformAction</strong></strong></a> method of every ActionNotificationReceiver object registered with it (i.e. the event organizer will notify every registered person about the availability of the tickets).</p>
<h2>ActionSource and ActionNotificationReceiver at Work</h2>
<p>So let&#8217;s use these Class Interfaces to see how they apply on our example app. Go ahead and create a new Desktop Project using the Xojo IDE. Then, drag the <a href="http://documentation.xojo.com/api/deprecated/canvas.html" target="_blank" rel="noopener"><strong><strong>Canvas</strong></strong></a> icon from the <strong>Library</strong> panel and drop it into the Project Browser (the leftmost column of the IDE). This action will create a new Canvas based subclass with the name &#8220;CustomCanvas&#8221;.</p>
<p>Select the CustomCanvas item and push the Interfaces button on the Inspector panel. This action will show a sheet window where we will be able to choose any of the already available Class Interfaces in the Xojo Framework for our subclass. In this case we are only interested on the actionNotificationReceiver Class Interface, so select the associated checkbox control and confirm the selection, clicking the &#8220;OK&#8221; button to dismiss the window. Now, our CustomCanvas class <strong>IsA</strong> Canvas and also <strong>IsA</strong> actionNotificationReceiver.</p>
<p>As result of the Class Interface selection, you will see that the PerformAction method has been automatically added to the CustomCanvas class; and, in fact, this is the method that will be invoked by the object acting as the source of notifications. Write the following sentence in the PerformAction Code Editor:</p>
<pre>me.Refresh</pre>
<p>Simple, isn&#8217;t? The truth is that the <strong>Paint</strong> event of our Canvas subclass (triggered with the <strong>Refresh</strong> method) will be in charge of executing the code needed to randomly change the control color. For that to happen, add the Paint Event to the CustomClass (<strong>Insert &gt; Event</strong>) and write the following code inside:</p>
<pre>Dim r as new Random
g.ForeColor = rgb(r.InRange(0,255),r.InRange(0,255),r.InRange(0,255))
g.FillRect(0,0,g.Width,g.Height)</pre>
<p>We have finished the work on our CustomCanvas Class, so it&#8217;s time to create a mere functional user interface. Select the Window1 item on the Project Browser, then drag the CustomCanvas item from the Project Browser to the Window Editor. That action will create a new instance from our Canvas based class.</p>
<p>To reproduce several color patches, the easiest is to define a <strong>Control Set</strong>. Let&#8217;s think about it as a group of controls of the same type that share the same behaviour and that we can refer from code using their index, as the &#8220;position&#8221; they have inside the group.</p>
<p>To define a new Control Set, select the CustomCanvas instance on the Window1 control and select the Attributes tab of the Inspector Panel, as shown in the following image:</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/ControlSet.jpgt1466486449161ampwidth285ampheight204" sizes="auto, (max-width: 285px) 100vw, 285px" alt="ControlSet.jpg" width="285" height="204" /></p>
<p>Select the popup menu &#8220;Member of&#8221; and choose the &#8220;New Control Set&#8221; option. When done, the Xojo IDE will create the &#8220;CustomCanvas1&#8221; group assigning the index &#8220;0&#8221; to the current selected instance.</p>
<p>Now, duplicate the control four times and align them side by side. You will notice that each control has its own index on the control group they belong to. In fact, this is shown in the Project Browser as a hierarchy.</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/ControlSetHierarchy.pngt1466486449161ampwidth249ampheight238" sizes="auto, (max-width: 249px) 100vw, 249px" alt="ControlSetHierarchy.png" width="249" height="238" /></p>
<p>The user interface should look like this:</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/Observer-UserInterface.pngt1466486449161ampwidth578ampheight328" sizes="auto, (max-width: 578px) 100vw, 578px" alt="Observer-UserInterface.png" width="578" height="328" /></p>
<p>To finish our user interface, just need to add a trigger control, and for that we will add a PushButton to the window. Remember that this control implements by default the &#8220;ActionSource-ActionNotificationReceiver&#8221; paradigm.</p>
<h2>Observer Pattern Design into action</h2>
<p>Now, we have to register all the objects that we want to be notified as result of the PushButton action (that is, the ActionSource control), so they can execute their associated action. For that, we will celebrate having grouped them in a Control Set!</p>
<p>Choose the item labeled &#8220;CustomCanvas1 Set&#8221; on the Project Browser; that is, the item that groups all the members, instead of selecting any one of its members.</p>
<p>Add the Open event to the selected item (<strong>Insert &gt; Event</strong>) and write the following code on the associated Code Editor:</p>
<pre>PushButton1.addActionNotificationReceiver me</pre>
<p>This way we will have registered all the members of the group as objects interested on receiving the notification from the PushButton.</p>
<p>Run the app and push the PushButton control, you&#8217;ll see that every time you push the buttonâ¦ all the canvas will radomly change their color!</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/Observer-Result.pngt1466486449161ampwidth578ampheight356" sizes="auto, (max-width: 578px) 100vw, 578px" alt="Observer-Result.png" width="578" height="356" />This way, we have seen how simple has been to achieve the solution (and the little amount of code that has been need). In fact, the PushButton added to the project has not one line of code! and best of all we have our code decoupled, easy to maintain and we can modify it without impacting the rest of the app.</p>
<p>You can <a href="https://www.youtube.com/watch?v=pNY-YttGEGY" target="_blank" rel="noopener">watch the video</a> (in Spanish only) that talks you though this example.</p>
<p><strong>NEXT:</strong> <a href="http://blog.xojo.com/2016/11/15/design-patterns-observer-part-ii/">Design Patterns in Xojo: Observer, Part II</a></p>
<p><em>Javier RodrÃ­guez has been the Xojo Spanish Evangelist since 2008, he&#8217;s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p><a href="http://www.aprendexojo.com/2016/05/patron-de-diseno-observer-en-xojo/" target="_blank" rel="noopener">*Read this post in Spanish</a><!-- end HubSpot Call-to-Action Code --></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Patterns in Xojo: Singleton</title>
		<link>https://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 08 Jun 2016 00:00:00 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/</guid>

					<description><![CDATA[In this post I am going to focus on one of these particular Design Patterns and how to implement it in Xojo: Singleton.]]></description>
										<content:encoded><![CDATA[<p>One of the best things that <strong>Xojo</strong> offers to programming newcomers is that they can simply jump-in and start to write code. In a matter of a few hours they&#8217;ll have a functional app! Nothing new here. (Or for not-so-newcomers, a fast way of creating a functional prototype from a idea).</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/CandyMachine.pngt1466486449161ampwidth227ampheight369" sizes="auto, (max-width: 227px) 100vw, 227px" alt="CandyMachine.png" width="227" height="369" />But as these users advance in their Xojo skills, they probably will care about coding better and to embrace the <strong>OOP</strong> way of doing things. After all, Xojo is a modern programming language with <strong>Classes</strong>, <strong>Inheritance</strong>, <strong>Interfaces</strong> and a bunch of the usual OOP paradigms that have much to offer: reusability, better maintainability and a lot of flexibility.<br />
<span id="more-269"></span></p>
<p>When we talk about OOP, Design Patterns arise! Design Patterns are like  recipes, well known solutions or best practices, to a series of problems or situations that emerge again and again in our OOP designs.</p>
<p>These <strong>Design Patterns</strong> are so common that you are probably already using some without knowing it. And if you are curious about what are the most common and the code design problems they solve, then you have to definetly take a look into the BOOK (yes, in uppercase): &#8220;<a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/" target="_blank">Design Patterns: Elements of Reusable Object-Oriented Software</a>&#8221;</p>
<p>In this post I am going to focus on one of these particular Design Patterns and how to implement it in Xojo: <a href="https://en.wikipedia.org/wiki/Singleton_pattern" target="_blank">Singleton</a>.</p>
<p>OOP is mainly about the instantiation âor object creationâ from a Class definition that acts like a template; so we can have several of these objects around sharing the same behaviour but with a state of their own. Well, the Singleton pattern is the &#8220;opposite&#8221; thing. The answer to having (generally) just one object around from a particular Class.</p>
<p>Why should we want this? The short answer: to limit the access or &#8220;enty point&#8221; to a main functionality of your apps, or when the created object has a high cost or high impact in used resources.</p>
<h2>Implementing the Singleton Pattern</h2>
<p>The key to implement this Design Pattern in your apps is to limit the instantiation of the Class to just one object. So let&#8217;s see how can we achieve this using the Xojo language features. These are the ingredients to the recipe!</p>
<p>A Class Constructor whose scope is set to Private. This is the way we will ensure that the Class consumer will not be able to create several instances using the usual syntax:</p>
<pre>Dim myInstance as MyClass = new MyClass
Dim myInstance as new Myclass</pre>
<p>A <strong>Shared Method</strong> (also known as Static Method or Class Method in other programming languages). This will be the entry point we will use in order to retrieve the unique instance allowed by the Class.</p>
<p>A <strong>Shared Property</strong> whose scope is set to <strong>Private</strong>. This one will be the responsible to hold (point to) the unique instance fromâ¦ the same Class!</p>
<p>Now that we know what the ingredients are, let&#8217;s create our own &#8220;Hello Machine&#8221; as a Singleton Class. Obviously this is not the most useful class in the world, but maintaining the functionality to a minimum will help to focus on the main point about how to implement this Design Pattern in Xojo.</p>
<h2>The &#8220;Hello Machine&#8221; Singleton</h2>
<p>Start the new project creating a new Class using <strong>Insert &gt; Class</strong>. Then, go to the Inspector panel and name the Class as &#8220;HelloMachine&#8221;.</p>
<p>With the new Class item selected in the Project Browser panel (the leftmost), add a new property to it using <strong>Insert &gt; Property</strong>. Name the new property as &#8220;Counter&#8221;, set the Type as Integer and the &#8220;Default Value&#8221; to 1. This is the property that will inform us about how many times has been invoked the class.</p>
<p>Add a new method to the HelloMachine Class (<strong>Insert &gt; Method</strong>). This will be in charge of providing the real functionality to our Singleton class. Use &#8220;Greet&#8221; for the method name and set the Scope to Public. Now, type the following code for the just created method:</p>
<pre>MsgBox "Hello World! Is not funny being the only one instance on Earth?" + endofline + endofline + "You have invoked me " + counter.totext + " times."
counter = counter + 1</pre>
<p>Now it is time to create the class members that will make our HelloMachine behave as a Singleton one.</p>
<p>Start adding the Shared Property that will be in charge to hold the unique class instance used by the App. Use <strong>Insert &gt; Shared Property</strong> for that. Select the just added shared property and using the Inspector panel type &#8220;sharedInstance&#8221; for the &#8220;Name&#8221;, and set the type to &#8220;HelloMachine&#8221;; that is, the same Class type we are just defining (it sounds kind of weird, I know).</p>
<p>Now is time to add our <strong>Class Constructor</strong>. Remember that this one is the special Method whose code is executed every time we want to create a new instance (object) from a particular class.</p>
<p>Use <strong>Insert &gt; Method</strong> and type &#8220;Constructor&#8221; on the &#8220;Method Name&#8221; field of the associated Inspector panel (or choose &#8220;Constructor&#8221; from the dropdown menu). Make sure you set the Scope of the Constructor method as Private. This way we will be sure that nobody will be able to directly instantiate new objects from the class.</p>
<p>Finally we will write the method that will act as the entry point to retrieve the unique instance available from the class; that is, the instance shared among the App.</p>
<p>Use <strong>Insert &gt; Shared Method</strong> and type &#8220;getInstance&#8221; for the &#8220;Method Name&#8221; field. Make sure to set the &#8220;Return Type&#8221; field to &#8220;HelloMachine&#8221;.</p>
<p>Select the &#8220;getInstance&#8221; shared method and type the following code on the associated Code Editor:</p>
<pre>If sharedInstance is Nil then sharedInstance = new HelloMachine
Return sharedInstance</pre>
<p>As you can see, all the &#8220;magic&#8221; consists to verify if has been created already a HelloMachine instance (holded by the sharedInstance Property), returning it if is the case or instantiating and returning it, if otherwise. VoilÃ¡, a Singleton Class!</p>
<h2>Singleton At Work</h2>
<p>Once we have finished our Singleton class definition, let&#8217;s use it in our App. Add the Open event to the default window, for example, and type the following code in the Code Editor:</p>
<pre>Dim myHelloMachine as HelloMachine = HelloMachine.getInstance
myHelloMachine.Greet
Dim myOtherHelloMachine as HelloMachine = HelloMachine.getInstance
myOtherHelloMachine.Greet</pre>
<p>As you can see, we are not instantiating new objects from the Class, just using the Public method to retrieve the unique instance managed by the own Class.</p>
<p>Just for fun, try to instantiate a new object from the class using the regular syntax (I mean, with &#8220;Dim myHellowMachine as new HelloMachine&#8221;) and you will get a Compiler error. That is, no way to have several objects around!</p>
<p>Download an example using the Singleton Design Patter <a href="https://www.dropbox.com/s/znvae5jyvxryz4q/OOP%20Singleton.zip?dl=0" target="_blank">from this link</a>.</p>
<p>You can <a href="https://youtu.be/61KYjND2Vz0" target="_blank">watch the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier RodrÃ­guez has been the Xojo Spanish Evangelist since 2008, he&#8217;s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>More Posts From Javier:</p>
<p><!--HubSpot Call-to-Action Code --> <span id="hs-cta-wrapper-2f91fd6d-fb29-4bba-96f2-4a07775b851e" class="hs-cta-wrapper"> <span id="hs-cta-2f91fd6d-fb29-4bba-96f2-4a07775b851e" class="hs-cta-node hs-cta-2f91fd6d-fb29-4bba-96f2-4a07775b851e"><br />
<!-- [if lte IE 8]>


<div id="hs-cta-ie-element"></div>


<![endif]--> <a href="http://blog.xojo.com/2016/05/25/methods-overloading-computed-properties-setters-and-getters/" target="_blank"><img loading="lazy" decoding="async" id="hs-cta-img-2f91fd6d-fb29-4bba-96f2-4a07775b851e" class="hs-cta-img aligncenter" style="border-width: 0px; margin: 0 auto; display: block; margin-top: 20px; margin-bottom: 20px;" src="https://blog.xojo.com/wp-content/uploads/2016/06/2f91fd6d-fb29-4bba-96f2-4a07775b851e.png" alt="Methods Overloading: Computed Properties, Setters and Getters" width="390" height="64" align="middle" /></a> </span><script src="https://js.hscta.net/cta/current.js" charset="utf-8">// <![CDATA[
<script type="text/javascript"><![CDATA[ hbspt.cta.load(608515, '2f91fd6d-fb29-4bba-96f2-4a07775b851e', {});
// ]]&gt;</script></span><br />
<!-- end HubSpot Call-to-Action Code --></p>
<p><a href="http://www.aprendexojo.com/2015/11/patron-singleton-en-xojo/" target="_blank">*Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
