Difference between revisions of "Composition - 2017"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
Composition is where if you delete the main class the subclasses are deleted along with it, or they no longer work.
+
Composition is where objects created within another object are destroyed along with the containing object.
 +
 
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
 
   class Location
 
   class Location
Line 28: Line 29:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
The Warren class declare an array of Rabbit. The constructor method for Warren creates each rabbit:
+
The Warren class declares an array of Rabbit. The constructor method for Warren creates each rabbit:
  
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
Line 44: Line 45:
  
 
So if a Warren is destroyed it will destroy all of the rabbits in that warren also.
 
So if a Warren is destroyed it will destroy all of the rabbits in that warren also.
 +
 +
=Conclusion=
 +
The following are therefore examples of composition (Composition shown with Filled Diamond):
 +
*Location to Fox
 +
*Location to Warren
 +
*Warren to Rabbit
 +
*Simulation to Location

Latest revision as of 12:48, 28 May 2017

Composition is where objects created within another object are destroyed along with the containing object.

  class Location
  {
    public Fox Fox;
    public Warren Warren;

    public Location()
    {
      Fox = null;
      Warren = null;
    }
  }

As you can see Location is creates an instance of Fox & Warren. So if you remove the instance of location then the Fox & Warren instances for that location will also be destroyed.

Other Examples

Warrens & Rabbits - warren creates and destroys rabbits:

class Warren
  {
    private const int MaxRabbitsInWarren = 99;
    private Rabbit[] Rabbits;
    private int RabbitCount = 0;

The Warren class declares an array of Rabbit. The constructor method for Warren creates each rabbit:

public Warren(int Variability)
    {
      this.Variability = Variability;
      Rabbits = new Rabbit[MaxRabbitsInWarren];
      RabbitCount = (int)(CalculateRandomValue((int)(MaxRabbitsInWarren / 4), this.Variability));
      for (int r = 0; r < RabbitCount; r++)
      {
        Rabbits[r] = new Rabbit(Variability);
      }
    }

So if a Warren is destroyed it will destroy all of the rabbits in that warren also.

Conclusion

The following are therefore examples of composition (Composition shown with Filled Diamond):

  • Location to Fox
  • Location to Warren
  • Warren to Rabbit
  • Simulation to Location