Example
The following example, written in Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In algebraic form,
Graphic = ellipse | GraphicList GraphicList = empty | Graphic GraphicListIt could be extended to implement several other shapes (rectangle, etc.) and methods (translate, etc.).
/** "Component" */ interface Graphic { //Prints the graphic. public void print; } /** "Composite" */ import java.util.List; import java.util.ArrayList; class CompositeGraphic implements Graphic { //Collection of child graphics. private ListThe following example, written in C#.
namespace CompositePattern { using System; using System.Collections.Generic; using System.Linq; //Client class Program { static void Main(string args) { // initialize variables var compositeGraphic = new CompositeGraphic; var compositeGraphic1 = new CompositeGraphic; var compositeGraphic2 = new CompositeGraphic; //Add 1 Graphic to compositeGraphic1 compositeGraphic1.Add(new Ellipse); //Add 2 Graphic to compositeGraphic2 compositeGraphic2.AddRange(new Ellipse, new Ellipse); /*Add 1 Graphic, compositeGraphic1, and compositeGraphic2 to compositeGraphic */ compositeGraphic.AddRange(new Ellipse, compositeGraphic1, compositeGraphic2); /*Prints the complete graphic (four times the string "Ellipse").*/ compositeGraphic.Print; Console.ReadLine; } } //Component public interface IGraphic { void Print; } //Leaf public class Ellipse : IGraphic { //Prints the graphic public void Print { Console.WriteLine("Ellipse"); } } //Composite public class CompositeGraphic : IGraphic { //Collection of Graphics. private readonly ListRead more about this topic: Composite Pattern
Famous quotes containing the word example:
“Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.”
—Marcel Proust (18711922)