Difference between revisions of "OOP Class12"

esse quam videri
Jump to: navigation, search
(ArrayList of Objects)
 
(36 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:OOP]]
+
[[Category:IAM Classes]]
==Dymnically Adding Elements==
 
  
===Array===
+
==Interfaces Part2==
http://www.c-sharpcorner.com/UploadFile/Saurabh.Mishra/GenericsInC2PartI04122006074306AM/GenericsInC2PartI.aspx
 
  
Say we have an empty drop down list.
+
There are many interfaces in the .net framework. Some that we have been working with are the [ICollection https://msdn.microsoft.com/en-us/library/system.collections.icollection(v=vs.110).aspx] [IList https://msdn.microsoft.com/en-us/library/system.collections.ilist(v=vs.110).aspx] and [IEnumerable https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx]
  
<pre><asp:DropDownList id="ddlCheese" autopostback="True" runat="server"  /></pre>
+
These interfaces allow us to use methods in a List and Array.
  
Since we know that all Lists in the framework contain ListItems we can dymaically add a bunch of cheeses by using a for loop that creates and add ListItems.
+
Here is an example of sorting a list of ints or an int[]
 +
<syntaxhighlight lang="csharp">
 +
            int[] ints = new int[] { 5, 4, 2, 3, 1 };
 +
            foreach (var number in ints)
 +
            {
 +
                Console.Write(string.Format("{0}\t", number));
 +
            }
 +
            Console.WriteLine();
  
ListItem has several constuctors
+
            Array.Sort(ints);  //Sort ints... they a primitive types so c# already knows how to sort them
{| align="center"
+
            foreach (var number in ints)
|-
+
            {
|Visibility || Constructor || Parameters
+
                Console.Write(string.Format("{0}\t", number));
|-
+
            }
|public || ListItem ||( )
+
            Console.WriteLine();
|-
+
           
|public || ListItem ||( String text )
+
            ints = ints.Reverse().ToArray();
|-
+
            foreach (var number in ints)
|public || ListItem ||( String text , String value )
+
            {
|-
+
                Console.Write(string.Format("{0}\t", number));
|public || ListItem ||( String text , String value , Boolean enabled )
+
            }
|}
+
            Console.WriteLine();
 +
 
 +
            //mess it up again
 +
            ints = new int[] { 5, 4, 2, 3, 1 };
 +
 
 +
            ints = ints.OrderBy(i => i).ToArray();
 +
            foreach (var number in ints)
 +
            {
 +
                Console.Write(string.Format("{0}\t", number));
 +
            }
 +
            Console.WriteLine();
 +
 
 +
            //mess it up again
 +
            ints = new int[] { 5, 4, 2, 3, 1 };
 +
 
 +
            //last way slightly uses agregate function to Order array by int, turns array into list so we can call foreach
 +
            ints.OrderBy(i => i).ToList().ForEach(ii=>Console.Write(string.Format("{0}\t", ii)));
 +
            Console.WriteLine();
 +
</syntaxhighlight>
 +
 
 +
Demo that we can do the same thing with lists with List
 +
 
 +
Some other ICollection Types that have more structure. These are known as '''Data Structures'''
 +
<syntaxhighlight lang="csharp">
 +
//Colllection Types
 +
            List<int> ints = new List<int> { 5, 3, 4, 2, 1 };
 +
 
 +
            Stack<int> intStack = new Stack<int>();
 +
 
 +
            intStack.Push(1);  //We push new item onto a stack
 +
            intStack.Push(2);
 +
            intStack.Push(3);
 +
 
 +
            Console.WriteLine(intStack.Pop());  //We pop items off of a stack
 +
            Console.WriteLine(intStack.Pop());
 +
            Console.WriteLine(intStack.Pop());
 +
 
 +
            Queue<int> intQueue = new Queue<int>();
 +
            intQueue.Enqueue(1);
 +
            intQueue.Enqueue(2);
 +
            intQueue.Enqueue(3);
 +
 
 +
            Console.WriteLine(intQueue.Peek());
 +
            Console.WriteLine(intQueue.Dequeue());
 +
            Console.WriteLine(intQueue.Dequeue());
 +
            Console.WriteLine(intQueue.Dequeue());
 +
 
 +
            Dictionary<string, string> States = new Dictionary<string, string>();
 +
            States.Add("AL", "Alabama");
 +
            States.Add("AK", "Alaska");
 +
            States.Add("AR", "Arizona");
 +
 
 +
            foreach (var item in States)
 +
            {
 +
                Console.WriteLine(string.Format("{0} {1}", item.Key, item.Value));
 +
            }
 +
 
 +
 
 +
            SortedList<int, string> StatesSorted = new SortedList<int, string>();
 +
            StatesSorted.Add(1, "Delware");
 +
            StatesSorted.Add(2, "Pennsylvania");
 +
            StatesSorted.Add(3, "New Jersey");
 +
 
 +
            foreach (var item in StatesSorted)
 +
            {
 +
                Console.WriteLine(string.Format("{0} {1}", item.Key, item.Value));
 +
            }
 +
 
 +
            Console.ReadKey();
 +
</syntaxhighlight>
 +
 
 +
Now lets sort some dogs
 +
<syntaxhighlight lang="csharp">
 +
class Dog : IComparable
 +
    {
 +
        public string Name;
 +
        protected int age;
 +
 
 +
        public int Age { get { return age; } set { age = value; } }
 +
 
 +
        public int Weight;
 +
        public string BarkSound;
 +
 
 +
        public Dog()
 +
        {
 +
            this.Name = "fido";
 +
            this.BarkSound = "woof!";
 +
            this.Weight = 1;
 +
        }
 +
 
 +
        public string About()
 +
        {
 +
            return string.Format("Hello my name is {0}. I'm {1} years old. I weigh {2} lbs", this.Name, this.Age, this.Weight);
 +
        }
 +
 
 +
 
 +
 
 +
        public int CompareTo(object obj)
 +
        {
 +
            if (obj is Dog)
 +
            {
 +
                if (this.Age > ((Dog)obj).Age) return 1;
 +
            }
 +
            return 0;
 +
        }
 +
}
 +
</syntaxhighlight>
  
<csharp>
+
and finally override some operators
         //an array of names of cheese
+
<syntaxhighlight lang="csharp">
        string [] aryNames = new string[5];
+
public static int Compare(Dog left, Dog right)
         
+
         {
        aryNames [0] = "Feta";
+
            if (object.ReferenceEquals(left, right))
        aryNames [1] = "Colby";
+
            {
        aryNames [2] = "Gruyere";
+
                return 0;
        aryNames [3] = "Edam";
+
            }
         aryNames [4] = "Colby";
+
            if (object.ReferenceEquals(left, null))
 +
            {
 +
                return -1;
 +
            }
 +
            return left.CompareTo(right);
 +
         }
  
         foreach (string cheeseName in aryNames)
+
         public static bool operator <(Dog left, Dog right)
 +
        {
 +
            return (Compare(left, right) < 0);
 +
        }
 +
        public static bool operator >(Dog left, Dog right)
 
         {
 
         {
             ListItem newItem = new ListItem(cheeseName, cheeseName);   //get a new list item
+
             return (Compare(left, right) > 0);
                                                    //with i for string text and i for value
+
        }
            ddlCheese.Items.Add(newItem); 
+
</syntaxhighlight>
        }</csharp>
+
 
 +
==Strategy Pattern==
 +
 
 +
<p>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</p>
  
 +
http://www.dofactory.com/Patterns/PatternStrategy.aspx
  
[http://iam.colum.edu/oop/classsource/class12/CheeseArray.aspx CheeseArray.aspx]
+
http://www.dofactory.com/images/diagrams/net/strategy.gif
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class12/CheeseArray.aspx - source]
 
  
===ArrayList of Objects===
+
Create Characters class and weapons class that uses the strategy pattern
  
<csharp>//an arraylist of cheeses
+
 
        Cheese Feta = new Cheese("Feta");
+
http://iam.colum.edu/oop/classsource/ConsoleApplicationCharacters.zip
         Cheese Colby = new Cheese("Colby");
+
 
         Cheese Gruyere = new Cheese("Gruyere");
+
browser http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/ConsoleApplicationCharacters/ConsoleApplicationCharacters/ConsoleApplicationCharacters
         Cheese Edam = new Cheese("Edam");
+
 
 +
===Weapons===
 +
 
 +
[[image:CharactersStrategy.PNG|700px]]
 +
 
 +
{|
 +
|<syntaxhighlight lang="csharp">public abstract class Weapon : IWeapon
 +
    {
 +
        protected string name, verb;
 +
         protected int damage;
 +
 
 +
         public Weapon()
 +
         {
 +
            this.verb = "uses";
 +
        }
 
          
 
          
 +
        #region IWeapon Members
 +
 +
        public string Name
 +
        {
 +
            get
 +
            {
 +
                return this.name;
 +
            }
 +
            set
 +
            {
 +
                this.name = value;
 +
            }
 +
        }
 +
 +
        public string Verb
 +
        {
 +
            get
 +
            {
 +
                return this.verb;
 +
            }
 +
            set
 +
            {
 +
                this.verb = value;
 +
            }
 +
        }
 +
 +
        public int Damage
 +
        {
 +
            get
 +
            {
 +
                return this.damage;
 +
            }
 +
            set
 +
            {
 +
                this.damage = value;
 +
            }
 +
        }
 +
 +
        public string Use(Character c)
 +
        {
 +
            return c.TakeDamage(this.damage).ToString();
 +
        }
 +
 +
        #endregion
 +
    }
 +
</syntaxhighlight>
 +
|<syntaxhighlight lang="csharp">public interface IWeapon
 +
    {
 +
        string Name
 +
        {
 +
            get;
 +
            set;
 +
        }
 +
 +
        int Damage
 +
        {
 +
            get;
 +
            set;
 +
        }
 +
 +
        string Verb { get; set; }
 +
 +
        string Use(Character otherCharacter);
 +
 +
     
 +
    }
 +
</syntaxhighlight>
 +
|}
 +
 +
{|
 +
|<syntaxhighlight lang="csharp">public abstract class HandToHand : Weapon
 +
    {
 +
        public HandToHand()
 +
        {
 +
            this.verb = "swings";
 +
        }
 +
    }
 +
</syntaxhighlight>
 +
|<syntaxhighlight lang="csharp">public class Hands : Characters.HandToHand
 +
    {
 +
        public Hands()
 +
        {
 +
            this.Name = "Hands";
 +
            this.verb = "punches";
 +
            this.damage = 1;
 +
        }
 +
    }
 +
</syntaxhighlight>
 +
|<syntaxhighlight lang="csharp">public class Sword : HandToHand
 +
    {
 +
        public Sword()
 +
        {
 +
            this.Name = "Sword";
 +
            this.Damage = 7;
 +
        }
 +
    }
 +
</syntaxhighlight>
 +
|}
 +
 +
===Characters===
 +
 +
[[File:CharacterStrategy.PNG|700px]]
 +
{|
 +
|<syntaxhighlight lang="csharp">
 +
public abstract class Character : IDamagable
 +
    {
 +
        protected IWeapon currentWeapon;
 +
        protected int hp;
 +
        public string Name;
 +
 +
        public Character()
 +
        {
 +
            this.Name = "Character";
 +
            this.hp = 100;
 +
            this.currentWeapon = new Hands();
 +
        }
 
          
 
          
         ArrayList alCheeses = new ArrayList();
+
         public int HP
         alCheeses.Add(Feta);
+
        {
        alCheeses.Add(Colby);
+
            get
         alCheeses.Add(Gruyere);
+
            {
         alCheeses.Add(Edam);</csharp>
+
                return this.hp;
 +
            }
 +
            set
 +
            {
 +
                this.hp = value;
 +
            }
 +
         }
 +
 
 +
        public IWeapon CurrentWeapon
 +
        {
 +
            get
 +
            {
 +
                return this.currentWeapon;
 +
            }
 +
            set
 +
            {
 +
                this.currentWeapon = value;
 +
            }
 +
        }
 +
 
 +
         public string About()
 +
         {
 +
            //TODO write about
 +
            return string.Format("About Character");
 +
        }
  
and the cheese class
+
        public string Attack(Character otherCharacter)
<csharp>public class Cheese
+
        {
{
+
            return string.Format("{0} {1} with {2} at {3} -{4} HP",
    public string Name;
+
                this.Name, currentWeapon.Verb, this.currentWeapon.Name, 
    public Milks MilkType;
+
                otherCharacter.Name, this.currentWeapon.Use(otherCharacter));
     public string Region;
+
        }
      
+
 
     public Cheese()
+
        public int TakeDamage(int damage)
 +
        {
 +
            this.hp -= damage;
 +
            return damage;
 +
        }
 +
     }
 +
 
 +
</syntaxhighlight>
 +
|<syntaxhighlight lang="csharp">
 +
public interface IDamagable
 +
    {
 +
        int HP
 +
        {
 +
            get;
 +
            set;
 +
        }
 +
 
 +
        int TakeDamage(int damage);
 +
     }
 +
</syntaxhighlight>
 +
|}
 +
Than a specific character
 +
{|
 +
|<syntaxhighlight lang="csharp">
 +
public class Troll : Character
 +
     {
 +
        public Troll()
 +
        {
 +
            this.Name = "Troll";
 +
            this.currentWeapon = new WarHammer();
 +
        }
 +
    }
 +
</syntaxhighlight>
 +
|<syntaxhighlight lang="csharp">
 +
public class SpaceMarine : Character
 
     {
 
     {
 +
        public SpaceMarine()
 +
        {
 +
            this.Name = "Master Chief";
 +
            this.currentWeapon = new BFG();
 +
        }
 
     }
 
     }
   
+
</syntaxhighlight>
    public Cheese(string name)
+
|<syntaxhighlight lang="csharp">
 +
public class Knight : Character
 
     {
 
     {
         this.Name = name;
+
         public Knight()
 +
        {
 +
            this.Name = "Sir Lancalot";
 +
            this.currentWeapon = new Sword();
 +
        }
 
     }
 
     }
   
+
</syntaxhighlight>
    public enum Milks { Cows, Goats, Mix, Vegetarian }
+
|}
}</csharp>
+
Notice the IWeapon becomes a specific interchangeable weapon.
  
Then you can bind the new cheese arraylist to a dropdown box.
+
==Use Case==
  
[http://iam.colum.edu/oop/classsource/class12/CheeseObject.aspx CheeseObject.aspx]
+
http://en.wikipedia.org/wiki/Use_case
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class12/CheeseObject.aspx - source]
 
  
===Saveing the Arraylist in the Seesion===
+
Diagrams
Wouldn't it be nice if we make our own cheese and add them to the arraylist. Here is an exmaple where you can dynamically add cheeses to the arraylist. The arraylist is preserved by saving it in a session variable between page hits. The first cheese 'Cheddar' is added to the Session in the initial page hit.
 
  
http://iam.colum.edu/oop/classsource/class12/CheeseObjectSession.aspx [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class12/CheeseObjectSession.aspx - source] 
+
http://en.wikipedia.org/wiki/Use_case_diagram
  
Final verson of the cheese saved in a session. This one added the MIlkType Enum and Uses a more abstracted  method to add the arraylist to the ListControl.
+
==Windows Course App Use Case==
  
http://iam.colum.edu/oop/classsource/class12/CheeseObjectSession2.aspx [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class12/CheeseObjectSession2.aspx - source]
+
Actors
 +
:particiant outside of the system
  
==Observer==
+
[[Image:Actor.png]]
  
Observer
+
Activity
:Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.  
+
:something an actor does
 +
[[Image:Activity.png]]
  
http://www.dofactory.com/Patterns/PatternObserver.aspx
+
[[Image:Restaurant-UML-UC.png]]
  
Observer is a deisgn pattern that is often used to publish (push) or subcribe (pull) changes in the stae of one object to other intersted object. It encourgaes loose coupling of objects.
+
Version 1 breif use case
  
The object the get the data often called the subject then notifies the observing objects of the change. The observing object will often repond to the subject.
+
Actor Admin
 +
 +
Course
 +
#Add a course to the system
 +
#Delete a course to the system
 +
Student
 +
#Add a student to the system
 +
#Delete a student to the system
 +
#Student add a course
 +
#Student remove a course
  
  
[[Image:Observer.gif]]
+
[[Image:CourseUseCase.png]]
 +
 
 +
 
 +
Use Cases often get translated in to sequence Diagrams
 +
 
 +
http://www.agilemodeling.com/artifacts/sequenceDiagram.htm
 +
 
 +
 
 +
<!--Finish the consumable example. Make Beverages Consumable by dogs and humans.
 +
 
 +
http://iam.colum.edu/oop/classsource/class11/ConsoleApplicationLunch.zip
 +
http://iam.colum.edu/oop/classsource/class11/Race.zip
 +
 
 +
-->
 +
 
 +
<!--
 +
 
 +
<syntaxhighlight lang="csharp">
 +
private void addCourseToolStripMenuItem_Click(object sender, EventArgs e)
 +
        {
 +
            AddCourse AC1 = new AddCourse();
 +
            AC1.FormClosed += new FormClosedEventHandler(AC1_FormClosed);
 +
            AC1.Show();
 +
 
 +
        }
 +
</syntaxhighlight>
 +
<syntaxhighlight lang="csharp">
 +
using System;
 +
using System.Collections.Generic;
 +
using System.Text;
 +
using System.Collections;
 +
 
 +
namespace course_registration
 +
{
 +
    class Course
 +
    {
 +
        public string CourseName;
 +
        public string CourseNumber;
 +
        public static ArrayList Courses;
 +
 
 +
        public Course()
 +
        {
 +
            CourseName = "Empty Course";
 +
            CourseNumber = "00-0000";
 +
        }
 +
 
 +
        public Course(string NewCourseName, string NewCourseNumber)
 +
        {
 +
            this.CourseNumber = NewCourseNumber;
 +
            this.CourseName = NewCourseName;
 +
        }
 +
 
 +
        public string About()
 +
        {
 +
            return "CourseName : " + this.CourseName + "\tCourseMumber :" + this.CourseNumber;
 +
        }
 +
 
 +
        public static void AddCourse(Course b)
 +
        {
 +
            if (Course.Courses == null)
 +
            {
 +
                Course.Courses = new ArrayList();
 +
            }
 +
            Course.Courses.Add(b);
 +
        }
 +
 
 +
        public static ArrayList GetCourseNames()
 +
        {
 +
            ArrayList CourseNames = new ArrayList();
 +
            foreach(Course c in Course.Courses)
 +
            {
 +
                CourseNames.Add(c.CourseName);
 +
               
 +
            }
 +
 
 +
            return CourseNames;
 +
 
 +
         
 +
        }
 +
 
 +
        public static void RemoveCourse(string CourseName)
 +
        {
 +
            Course CourseToRemove = GetCourseFromCourseName(CourseName);
 +
            Course.Courses.Remove(CourseToRemove);
 +
        }
 +
 
 +
        public static Course GetCourseFromCourseName(string CourseName)
 +
        {
 +
            foreach (Course c in Courses)
 +
            {
 +
                if (c.CourseName == CourseName)
 +
                {
 +
                    return c;
 +
                }
 +
            }
 +
            return null;
 +
        }
 +
    }
 +
}
 +
</syntaxhighlight>
 +
</syntaxhighlight>
 +
 
 +
-->
  
Here is a real example in c#. In this exmaple a stock (the subject) notifies and investor (the observer) of a change in price.
+
==Home work==
 +
Toastable project in moodle : Toaster should be able to toast (cook) any number of Itoastable object with the strategy pattern
  
[[Image:ObserverStocks.png]]
+
[[File:ToastableStrategy.PNG]]
  
 +
http://lms.colum.edu/mod/assign/view.php?id=161796
  
http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class12/Observer_j.cs
+
Make one of your classes sortable by implementing IComparable : Modify one of you classes to implements IComparable so that you objects may be sorted. Create an Array or LIst of you objects and demonstrate sorting them.
  
http://iam.colum.edu/oop/classsource/class12/Observer.aspx [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class12/Observer.aspx - source]
+
http://lms.colum.edu/mod/assign/view.php?id=161799

Latest revision as of 16:31, 10 June 2019


Interfaces Part2

There are many interfaces in the .net framework. Some that we have been working with are the [ICollection https://msdn.microsoft.com/en-us/library/system.collections.icollection(v=vs.110).aspx] [IList https://msdn.microsoft.com/en-us/library/system.collections.ilist(v=vs.110).aspx] and [IEnumerable https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx]

These interfaces allow us to use methods in a List and Array.

Here is an example of sorting a list of ints or an int[]

            int[] ints = new int[] { 5, 4, 2, 3, 1 };
            foreach (var number in ints)
            {
                Console.Write(string.Format("{0}\t", number));
            }
            Console.WriteLine();

            Array.Sort(ints);   //Sort ints... they a primitive types so c# already knows how to sort them
            foreach (var number in ints)
            {
                Console.Write(string.Format("{0}\t", number));
            }
            Console.WriteLine();
            
            ints = ints.Reverse().ToArray();
            foreach (var number in ints)
            {
                Console.Write(string.Format("{0}\t", number));
            }
            Console.WriteLine();

            //mess it up again
            ints = new int[] { 5, 4, 2, 3, 1 };

            ints = ints.OrderBy(i => i).ToArray();
            foreach (var number in ints)
            {
                Console.Write(string.Format("{0}\t", number));
            }
            Console.WriteLine();

            //mess it up again
            ints = new int[] { 5, 4, 2, 3, 1 };

            //last way slightly uses agregate function to Order array by int, turns array into list so we can call foreach
            ints.OrderBy(i => i).ToList().ForEach(ii=>Console.Write(string.Format("{0}\t", ii)));
            Console.WriteLine();

Demo that we can do the same thing with lists with List

Some other ICollection Types that have more structure. These are known as Data Structures

 //Colllection Types
            List<int> ints = new List<int> { 5, 3, 4, 2, 1 };

            Stack<int> intStack = new Stack<int>();

            intStack.Push(1);   //We push new item onto a stack
            intStack.Push(2);
            intStack.Push(3);

            Console.WriteLine(intStack.Pop());  //We pop items off of a stack
            Console.WriteLine(intStack.Pop());
            Console.WriteLine(intStack.Pop());

            Queue<int> intQueue = new Queue<int>();
            intQueue.Enqueue(1);
            intQueue.Enqueue(2);
            intQueue.Enqueue(3);

            Console.WriteLine(intQueue.Peek());
            Console.WriteLine(intQueue.Dequeue());
            Console.WriteLine(intQueue.Dequeue());
            Console.WriteLine(intQueue.Dequeue());

            Dictionary<string, string> States = new Dictionary<string, string>();
            States.Add("AL", "Alabama");
            States.Add("AK", "Alaska");
            States.Add("AR", "Arizona");

            foreach (var item in States)
            {
                Console.WriteLine(string.Format("{0} {1}", item.Key, item.Value));
            }


            SortedList<int, string> StatesSorted = new SortedList<int, string>();
            StatesSorted.Add(1, "Delware");
            StatesSorted.Add(2, "Pennsylvania");
            StatesSorted.Add(3, "New Jersey");

            foreach (var item in StatesSorted)
            {
                Console.WriteLine(string.Format("{0} {1}", item.Key, item.Value));
            }

            Console.ReadKey();

Now lets sort some dogs

class Dog : IComparable
    {
        public string Name;
        protected int age;

        public int Age { get { return age; } set { age = value; } }

        public int Weight;
        public string BarkSound;

        public Dog()
        {
            this.Name = "fido";
            this.BarkSound = "woof!";
            this.Weight = 1;
        }

        public string About()
        {
            return string.Format("Hello my name is {0}. I'm {1} years old. I weigh {2} lbs", this.Name, this.Age, this.Weight);
        }



        public int CompareTo(object obj)
        {
            if (obj is Dog)
            {
                if (this.Age > ((Dog)obj).Age) return 1;
            }
            return 0;
        }
}

and finally override some operators

public static int Compare(Dog left, Dog right)
        {
            if (object.ReferenceEquals(left, right))
            {
                return 0;
            }
            if (object.ReferenceEquals(left, null))
            {
                return -1;
            }
            return left.CompareTo(right);
        }

        public static bool operator <(Dog left, Dog right)
        {
            return (Compare(left, right) < 0);
        }
        public static bool operator >(Dog left, Dog right)
        {
            return (Compare(left, right) > 0);
        }

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

http://www.dofactory.com/Patterns/PatternStrategy.aspx

strategy.gif

Create Characters class and weapons class that uses the strategy pattern


http://iam.colum.edu/oop/classsource/ConsoleApplicationCharacters.zip

browser http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/ConsoleApplicationCharacters/ConsoleApplicationCharacters/ConsoleApplicationCharacters

Weapons

CharactersStrategy.PNG

public abstract class Weapon : IWeapon
    {
        protected string name, verb;
        protected int damage;

        public Weapon()
        {
            this.verb = "uses";
        }
        
        #region IWeapon Members

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
            }
        }

        public string Verb
        {
            get
            {
                return this.verb;
            }
            set
            {
                this.verb = value;
            }
        }

        public int Damage
        {
            get
            {
                return this.damage;
            }
            set
            {
                this.damage = value;
            }
        }

        public string Use(Character c)
        {
            return c.TakeDamage(this.damage).ToString();
        }

        #endregion
    }
public interface IWeapon
    {
        string Name
        {
            get;
            set;
        }

        int Damage
        {
            get;
            set;
        }

        string Verb { get; set; }

        string Use(Character otherCharacter);

       
    }
public abstract class HandToHand : Weapon
    {
        public HandToHand()
        {
            this.verb = "swings";
        }
    }
public class Hands : Characters.HandToHand
    {
        public Hands()
        {
            this.Name = "Hands";
            this.verb = "punches";
            this.damage = 1;
        }
    }
public class Sword : HandToHand
    {
        public Sword()
        {
            this.Name = "Sword";
            this.Damage = 7;
        }
    }

Characters

CharacterStrategy.PNG

public abstract class Character : IDamagable
    {
        protected IWeapon currentWeapon;
        protected int hp;
        public string Name;

        public Character()
        {
            this.Name = "Character";
            this.hp = 100;
            this.currentWeapon = new Hands();
        }
        
        public int HP
        {
            get
            {
                return this.hp;
            }
            set
            {
                this.hp = value;
            }
        }

        public IWeapon CurrentWeapon
        {
            get
            {
                return this.currentWeapon;
            }
            set
            {
                this.currentWeapon = value;
            }
        }

        public string About()
        {
            //TODO write about
            return string.Format("About Character");
        }

        public string Attack(Character otherCharacter)
        {
            return string.Format("{0} {1} with {2} at {3} -{4} HP",
                this.Name, currentWeapon.Verb, this.currentWeapon.Name,  
                otherCharacter.Name, this.currentWeapon.Use(otherCharacter));
        }

        public int TakeDamage(int damage)
        {
            this.hp -= damage;
            return damage;
        }
    }
public interface IDamagable
    {
        int HP
        {
            get;
            set;
        }

        int TakeDamage(int damage);
    }

Than a specific character

public class Troll : Character
    {
        public Troll()
        {
            this.Name = "Troll";
            this.currentWeapon = new WarHammer();
        }
    }
public class SpaceMarine : Character
    {
        public SpaceMarine()
        {
            this.Name = "Master Chief";
            this.currentWeapon = new BFG();
        }
    }
 public class Knight : Character
    {
        public Knight()
        {
            this.Name = "Sir Lancalot";
            this.currentWeapon = new Sword();
        }
    }

Notice the IWeapon becomes a specific interchangeable weapon.

Use Case

http://en.wikipedia.org/wiki/Use_case

Diagrams

http://en.wikipedia.org/wiki/Use_case_diagram

Windows Course App Use Case

Actors

particiant outside of the system

Actor.png

Activity

something an actor does

Activity.png

Restaurant-UML-UC.png

Version 1 breif use case

Actor Admin

Course
#Add a course to the system
#Delete a course to the system
Student
#Add a student to the system
#Delete a student to the system
#Student add a course
#Student remove a course


CourseUseCase.png


Use Cases often get translated in to sequence Diagrams

http://www.agilemodeling.com/artifacts/sequenceDiagram.htm



Home work

Toastable project in moodle : Toaster should be able to toast (cook) any number of Itoastable object with the strategy pattern

ToastableStrategy.PNG

http://lms.colum.edu/mod/assign/view.php?id=161796

Make one of your classes sortable by implementing IComparable : Modify one of you classes to implements IComparable so that you objects may be sorted. Create an Array or LIst of you objects and demonstrate sorting them.

http://lms.colum.edu/mod/assign/view.php?id=161799