Composite pattern

In computer programming, composite pattern is one of design patternss to decompose objects into their parts, and reassemble them in whichever combination you need with "has-a" relationships. That is to say, break things into the largest parts that still let you reuse the parts, and build your objects of those.

The other definition is to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

When: Any time there is partial overlap in the capabilities of objects.

Objects may be members of a number of linked lists in our system. The linked lists organize the objects by different criteria.

 package LinkedList;
 use ImplictThis; ImplicitThis::imply();

sub new { my $type = shift; bless { next=>, previous=> }, $type; }

sub next { return $next; } sub set_next { $next = shift; return 1; } sub previous { return $previous; } sub set_previous { $previous = shift; return 1; } sub append { my $ob = shift; $ob->isa(__PACKAGE__) or die; $next or do { $next = $ob; $ob->set_previous($this); return 1; } $ob->set_next($next); $next->set_previous($ob); $ob->set_previous($this); $this->set_next($ob); return 1; }

We can inherit this, but inheriting it multiple times doesn't do us any good: we only ever have one instance of the LinkedList this way - ourselves. Using composition gives us what we want:

 package TriceQueuedObject;
 use LinkedList;
 use ImplicitThis; ImplicitThis::imply();

sub new { my $type = shift; my $me = { sort_order => new LinkedList, size_order => new LinkedList, save_order => new LinkedList, @_ }; bless $me, $type; }

# create accessors that defer the action to each object, for each object composing us: # method A: see text below

sub next_sort { return $sort_order->next(); } sub previous_sort { return $sort_order->previous(); } sub set_next_sort { return $sort_order->set_next(@_); } sub append_sort { return $sort_order->append(@_); }

sub next_size { return $size_order->next(); } sub previous_size { return $size_order->previous(); } sub set_next_size { return $size_order->set_next(@_); } sub append_size { return $size_order->append(@_); }

sub next_save { return $save_order->next(); } sub previous_save { return $save_order->previous(); } sub set_next_save { return $save_order->set_next(@_); } sub append_save { return $save_order->append(@_); }

# directly return references to objects that compose us: # method B: see text below

sub get_sort_order { return $sort_order; } sub get_size_order { return $size_order; } sub get_save_order { return $save_order; }

Where it says "method A" and "method B" illustrate two very different approaches to giving users of our object access to the our parts. "Method A" creates all new accessors which do their work by calling accessors in the composing objects. "Method B" simply returns the composing objects and lets the user call the methods directly. For example:

 # using method A:

$ob->next_sort($ob2);

# using method B:

$ob->get_sort_order()->set_next($ob2);

Which is better? Well, it depends. If your object is merely a container for other objects, B makes more sense. If your object is a Facade, providing a new interface to several objects, A makes more sense. If you consider the objects you contain to be implementation dependent, and you don't want to have to support returning intermediate objects in the future, A lets you hide your implementation better. B makes for shorter code and less typing when the relationship between the objects isn't likely to change.

Each LinkedList instance is a "delegate" in this example. The methods that propogate requests to them are "delegate methods".

Compose means a special thing: it refers to building objects using DelegationConcept. Delegation-composition hangs onto constituent parts using references. By contrast, MixIns inherit from each part. MixIns prevent returning a WholeObject in responce to requests for information, and they prevent you from having a more than one of any given part.

External Links

The article is originally from Perl Design Patterns Book


See Also:


In the News

No Real Increase In Obesity Among Adults; But Levels Still High, CDC S
After a quarter century of increases, obesity prevalence has not measurably increased in the past few years but levels are still high -- at 34 percent of U.S. adults aged 20 and over, according to a new study released by the Centers for Disease Control and Prevention (CDC). The report, "Obesity Among Adults in the U.S.: No Significant Change in 2005-06,"is the latest analysis based on the National Health and Nutrition Examination Survey, conducted by CDC's National Center for Health Statistics.

Hubble Captures Outburst From Comet Targeted By Deep Impact
In a dress rehearsal for the rendezvous between NASA's Deep Impact spacecraft and comet 9P/Tempel 1, the Hubble Space Telescope captured dramatic images of a new jet of dust streaming from the icy comet. The images are a reminder that Tempel 1's icy nucleus, roughly the size of central Paris, is dynamic and volatile. Astronomers hope the eruption of dust seen in these observations is a preview of the fireworks that may come 4 July, when a probe from the Deep Impact spacecraft will slam into the comet, possibly blasting off material and giving rise to a similar dust plume.

Tropics Play More Active Role Than Was Thought In Controlling Earth's
A million years ago, global climate changes occurred due to changes in tropical circulation in the Pacific similar to those caused by "El NiƱo" today. Changes in atmospheric circulation triggered a large expansion of the polar ice sheets. The discovery shows that local climate changes in the tropics can create global climate changes, and emphasises the hypothesis that the tropics play a more active role than was thought in controlling the Earth's climate.

Diet, Exercise, Stimulating Environment Helps Old Dogs Learn
According to conventional wisdom, old dogs and new tricks aren't a good match. But a new study of beagles finds that regular physical activity, mental stimulation, and a diet rich in antioxidants can help keep aging canine -- and perhaps human--brains in tip-top shape.

Turkish Health Workers Condone Wife Beating, Study Says
Domestic violence is an inherent problem in Turkey, and healthcare workers are doing little to combat the prevalence of wife beating, according to research published in the online open access journal, BMC Public Health. A survey of medical personnel reveals that a lack of training and a cultural acceptance of domestic violence may prevent victims from obtaining the support they desperately require.

Ajax Powers Text-Translation Tool
AjaxTrans works with six languages. Plus:The 10 best tech podcasts of 2005. From the Wired News blog Monkey Bites.

Recovered King Of Beasts Returns To His Home, Thanks To Unique Operati
Samson the lion from the Hai-Kef zoo in Rishon Lezion, Israel, who had undergone a brain operation -- unique in the world -- at the Veterinary Teaching Hospital of the Hebrew University of Jerusalem, has recuperated and has returned to his cage and to his sister, Delilah.

New Research Suggests Heart Bypass Surgery Increases Risk Of Alzheimer
Boston University School of Medicine (BUSM) researchers have discovered that patients who have either coronary artery bypass graft surgery or coronary angioplasty are at an increased risk of developing Alzheimer's disease.

Ape To Human: Walking Upright May Have Protected Heavy Human Babies
The transition from apes to humans may have been partially triggered by the need to stand on two legs, in order to safely carry heavier babies. For safety, all nonhuman primates carry their young clinging to their fur from birth, and species survival depends on it. The carrying pattern changes as the infant grows.

Gas On Your Mind: Snail's Brain Provides Insights Into Human Learning
Scientists at the University of Leicester are to gain a greater insight into the workings of the human mind -- through the study of a snail's brain.


MP3 Music Downloads

Preview songs, Download Free Music,Burn CDs at ITunes.com
iTunes_RGB_9mm

 


Google




InformationQuickFind.com - Find Information Fast

Links