Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Decorator pattern

From Wikipedia, the free encyclopedia
Design pattern in object-oriented programming
Not to be confused withthe concept of "decorators" in Python.

Inobject-oriented programming, thedecorator pattern is adesign pattern that allows behavior to be added to an individualobject, dynamically, without affecting the behavior of other instances of the sameclass.[1] The decorator pattern is often useful for adhering to theSingle Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern[2] as well as to theOpen-Closed Principle, by allowing the functionality of a class to be extended without being modified.[3] Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.

Overview

[edit]

Thedecorator[4] design pattern is one of the twenty-three well-knowndesign patterns; these describe how to solve recurring design problems and design flexible and reusable object-oriented software—that is, objects which are easier to implement, change, test, and reuse.

The decorator pattern provides a flexible alternative to subclassing for extending functionality. When using subclassing, different subclasses extend a class in different ways. However, an extension is bound to the class at compile-time and can't be changed at run-time. The decorator pattern allows responsibilities to be added (and removed from) an object dynamically at run-time. It is achieved by definingDecorator objects that

  • implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it.
  • perform additional functionality before or after forwarding a request.

This allows working with differentDecorator objects to extend the functionality of an object dynamically at run-time.[5]

Intent

[edit]
DecoratorUML class diagram

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases atrun-time, independently of other instances of the sameclass, provided some groundwork is done at design time. This is achieved by designing a newDecorator class thatwraps the original class. This wrapping could be achieved by the following sequence of steps:

  1. Subclass the originalComponent class into aDecorator class (see UML diagram);
  2. In theDecorator class, add aComponent pointer as a field;
  3. In theDecorator class, pass aComponent to theDecorator constructor to initialize theComponent pointer;
  4. In theDecorator class,forward allComponent methods to theComponent pointer; and
  5. In the ConcreteDecorator class, override anyComponent method(s) whose behavior needs to be modified.

This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).

Note that decorators and the original class object share a common set of features. In the previous diagram, the operation() method was available in both the decorated and undecorated versions.

The decoration features (e.g., methods, properties, or other members) are usually defined by an interface,mixin (a.k.a.trait) or class inheritance which is shared by the decorators and the decorated object. In the previous example, the classComponent is inherited by both the ConcreteComponent and the subclasses that descend fromDecorator.

The decorator pattern is an alternative tosubclassing. Subclassing adds behavior atcompile time, and the change affects all instances of the original class; decorating can provide new behavior atrun-time for selected objects.[5]

This difference becomes most important when there are severalindependent ways of extending functionality. In someobject-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of bothJava and the.NET Framework incorporate the decorator pattern.[5]

Motivation

[edit]
UML diagram for the window example

As an example, consider a window in awindowing system. To allowscrolling of the window's contents, one may wish to add horizontal or verticalscrollbars to it, as appropriate. Assume windows are represented by instances of theWindow interface, and assume this class has no functionality for adding scrollbars. One could create a subclassScrollingWindow that provides them, or create aScrollingWindowDecorator that adds this functionality to existingWindow objects. At this point, either solution would be fine.

Now, assume one also desires the ability to add borders to windows. Again, the originalWindow class has no support. TheScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If one wishes to add border support to many but notall windows, one must create subclassesWindowWithBorder andScrollingWindowWithBorder, etc. This problem gets worse with every new feature or window subtype to be added. For the decorator solution, a newBorderedWindowDecorator is created. Any combination ofScrollingWindowDecorator orBorderedWindowDecorator can decorate existing windows. If the functionality needs to be added to all Windows, the base class can be modified. On the other hand, sometimes (e.g., using external frameworks) it is not possible, legal, or convenient to modify the base class.

In the previous example, theSimpleWindow andWindowDecorator classes implement theWindow interface, which defines thedraw() method and thegetDescription() method that are required in this scenario, in order to decorate a window control.

Common usecases

[edit]

Applying decorators

[edit]

Adding or removing decorators on command (like a button press) is a common UI pattern, often implemented along with theCommand design pattern. For example, a text editing application might have a button to highlight text. On button press, the individual text glyphs currently selected will all be wrapped in decorators that modify their draw() function, causing them to be drawn in a highlighted manner (a real implementation would probably also use a demarcation system to maximize efficiency).

Applying or removing decorators based on changes in state is another common use case. Depending on the scope of the state, decorators can be applied or removed in bulk. Similarly, theState design pattern can be implemented using decorators instead of subclassed objects encapsulating the changing functionality. The use of decorators in this manner makes the State object's internal state and functionality more compositional and capable of handling arbitrary complexity.

Usage in Flyweight objects

[edit]
Main article:Flyweight pattern

Decoration is also often used in theFlyweight design pattern. Flyweight objects are divided into two components: an invariant component that is shared between all flyweight objects; and a variant, decorated component that may be partially shared or completely unshared. This partitioning of the flyweight object is intended to reduce memory consumption. The decorators are typically cached and reused as well. The decorators will all contain a common reference to the shared, invariant object. If the decorated state is only partially variant, then the decorators can also be shared to some degree - though care must be taken not to alter their state while they're being used. iOS's UITableView implements the flyweight pattern in this manner - a tableview's reusable cells are decorators that contains a references to a common tableview row object, and the cells are cached / reused.

Obstacles of interfacing with decorators

[edit]

Applying combinations of decorators in diverse ways to a collection of objects introduces some problems interfacing with the collection in a way that takes full advantage of the functionality added by the decorators. The use of anAdapter orVisitor patterns can be useful in such cases. Interfacing with multiple layers of decorators poses additional challenges and logic of Adapters and Visitors must be designed to account for that.

Architectural relevance

[edit]

Decorators support acompositional rather than a top-down, hierarchical approach to extending functionality. A decorator makes it possible to add or alter behavior of an interface at run-time. They can be used to wrap objects in a multilayered, arbitrary combination of ways. Doing the same with subclasses means implementing complex networks of multiple inheritance, which is memory-inefficient and at a certain point just cannot scale. Likewise, attempting to implement the same functionality with properties bloats each instance of the object with unnecessary properties. For the above reasons decorators are often considered a memory-efficient alternative to subclassing.

Decorators can also be used to specialize objects which are not subclassable, whose characteristics need to be altered at runtime (as mentioned elsewhere), or generally objects that are lacking in some needed functionality.

Usage in enhancing APIs

[edit]

The decorator pattern also can augment theFacade pattern. A facade is designed to simply interface with the complex system it encapsulates, but it does not add functionality to the system. However, the wrapping of a complex system provides a space that may be used to introduce new functionality based on the coordination of subcomponents in the system. For example, a facade pattern may unify many different languages dictionaries under one multi-language dictionary interface. The new interface may also provide new functions for translating words between languages. This is a hybrid pattern - the unified interface provides a space for augmentation. Think of decorators as not being limited to wrapping individual objects, but capable of wrapping clusters of objects in this hybrid approach as well.

Alternatives to decorators

[edit]

As an alternative to the decorator pattern, theadapter can be used when the wrapper must respect a particular interface and must supportpolymorphic behavior, and theFacade when an easier or simpler interface to an underlying object is desired.[6]

PatternIntent
AdapterConverts one interface to another so that it matches what the client is expecting
DecoratorDynamically adds responsibility to the interface by wrapping the original code
FacadeProvides a simplified interface

Structure

[edit]

UML class and sequence diagram

[edit]
A sample UML class and sequence diagram for the Decorator design pattern.[7]

In the aboveUMLclass diagram, the abstractDecorator class maintains a reference (component) to the decorated object (Component) and forwards all requests to it(component.operation()). This makesDecorator transparent (invisible) to clients ofComponent.

Subclasses (Decorator1,Decorator2) implement additional behavior(addBehavior()) that should be added to theComponent (before/after forwarding a request to it).
The sequence diagram shows the run-time interactions: TheClient object works throughDecorator1 andDecorator2 objects toextend the functionality of aComponent1 object.
TheClient callsoperation() onDecorator1, which forwards the request toDecorator2.Decorator2 performsaddBehavior() after forwarding the request toComponent1 and returns toDecorator1, which performsaddBehavior() and returns to theClient.

Examples

[edit]

C++

[edit]

This implementation (which uses C++23 features) is based on the pre C++98 implementation in the book.

importstd;// Beverage interface.classBeverage{public:virtualvoiddrink()=0;virtual~Beverage()=default;};// Drinks which can be decorated.classCoffee:publicBeverage{public:virtualvoiddrink()override{std::print("Drinking Coffee");}};classSoda:publicBeverage{public:virtualvoiddrink()override{std::print("Drinking Soda");}};classBeverageDecorator:publicBeverage{public:BeverageDecorator()=delete;BeverageDecorator(std::unique_ptr<Beverage>component_):component(std::move(component_)){}virtualvoiddrink()=0;protected:voidcallComponentDrink(){if(component)component->drink();}private:std::unique_ptr<Beverage>component;};classMilk:publicBeverageDecorator{public:Milk(std::unique_ptr<Beverage>component_,floatpercentage_):BeverageDecorator(std::move(component_)),percentage(percentage_){}virtualvoiddrink()override{callComponentDrink();std::print(", with milk of richness {}%",percentage);}private:floatpercentage;};classIceCubes:publicBeverageDecorator{public:IceCubes(std::unique_ptr<Beverage>component_,intcount_):BeverageDecorator(std::move(component_)),count(count_){}virtualvoiddrink()override{callComponentDrink();std::print(", with {} ice cubes",count);}private:intcount;};classSugar:publicBeverageDecorator{public:Sugar(std::unique_ptr<Beverage>component_,intspoons_):BeverageDecorator(std::move(component_)),spoons(spoons_){}virtualvoiddrink()override{callComponentDrink();std::print(", with {} spoons of sugar",spoons);}private:intspoons=1;};intmain(intargc,char*argv[]){std::unique_ptr<Beverage>soda=std::make_unique<Soda>();soda=std::make_unique<IceCubes>(std::move(soda),3);soda=std::make_unique<Sugar>(std::move(soda),1);soda->drink();std::println();std::unique_ptr<Beverage>coffee=std::make_unique<Coffee>();coffee=std::make_unique<IceCubes>(std::move(coffee),16);coffee=std::make_unique<Milk>(std::move(coffee),3.);coffee=std::make_unique<Sugar>(std::move(coffee),2);coffee->drink();return0;}

The program output is like

DrinkingSoda,with3icecubes,with1spoonsofsugarDrinkingCoffee,with16icecubes,withmilkofrichness3%,with2spoonsofsugar

Full example can be tested on agodbolt page.

C++

[edit]

Two options are presented here: first, a dynamic, runtime-composable decorator (has issues with calling decorated functions unless proxied explicitly) and a decorator that uses mixin inheritance.

Dynamic decorator

[edit]
importstd;structShape{virtual~Shape()=default;virtualstd::stringgetName()const=0;};structCircle:Shape{voidresize(floatfactor){radius*=factor;}std::stringgetName()constoverride{returnstd::format("A circle of radius {}",radius);}floatradius=10.0f;};structColoredShape:Shape{ColoredShape(conststd::string&color,Shape&shape):color(color),shape(shape){}std::stringgetName()constoverride{returnstd::format("{} which is colored {}",shape.getName(),color);}std::stringcolor;Shape&shape;};intmain(){Circlecircle;ColoredShapecoloredShape{"red",circle};std::println("{}",coloredShape.getName());}
importstd;structWebPage{virtualvoiddisplay()=0;virtual~WebPage()=default;};structBasicWebPage:WebPage{std::stringhtml;voiddisplay()override{std::println("Basic WEB page");}};structWebPageDecorator:WebPage{WebPageDecorator(std::unique_ptr<WebPage>webPage):_webPage(std::move(webPage)){}voiddisplay()override{_webPage->display();}private:std::unique_ptr<WebPage>_webPage;};structAuthenticatedWebPage:WebPageDecorator{AuthenticatedWebPage(std::unique_ptr<WebPage>webPage):WebPageDecorator(std::move(webPage)){}voidauthenticateUser(){std::println("authentification done");}voiddisplay()override{authenticateUser();WebPageDecorator::display();}};structAuthorizedWebPage:WebPageDecorator{AuthorizedWebPage(std::unique_ptr<WebPage>webPage):WebPageDecorator(std::move(webPage)){}voidauthorizedUser(){std::println("authorized done");}voiddisplay()override{authorizedUser();WebPageDecorator::display();}};intmain(intargc,char*argv[]){std::unique_ptr<WebPage>myPage=std::make_unique<BasicWebPage>();myPage=std::make_unique<AuthorizedWebPage>(std::move(myPage));myPage=std::make_unique<AuthenticatedWebPage>(std::move(myPage));myPage->display();std::println();return0;}

Static decorator (mixin inheritance)

[edit]

This example demonstrates a static Decorator implementation, which is possible due to C++ ability to inherit from the template argument.

importstd;structCircle{voidresize(floatfactor){radius*=factor;}std::stringgetName()const{returnstd::format("A circle of radius {}",radius);}floatradius=10.0f;};template<typenameT>structColoredShape:publicT{ColoredShape(conststd::string&color):color(color){}std::stringgetName()const{returnstd::format("{} which is colored {}",T::getName(),color);}std::stringcolor;};intmain(){ColoredShape<Circle>redCircle{"red"};std::println("{}",redCircle.getName());redCircle.resize(1.5f);std::println("{}",redCircle.getName());}

Java

[edit]

First example (window/scrolling scenario)

[edit]

The following Java example illustrates the use of decorators using the window/scrolling scenario.

// The Window interface classpublicinterfaceWindow{voiddraw();// Draws the WindowStringgetDescription();// Returns a description of the Window}// Implementation of a simple Window without any scrollbarsclassSimpleWindowimplementsWindow{@Overridepublicvoiddraw(){// Draw window}@OverridepublicStringgetDescription(){return"simple window";}}

The following classes contain the decorators for allWindow classes, including the decorator classes themselves.

// abstract decorator class - note that it implements WindowabstractclassWindowDecoratorimplementsWindow{privatefinalWindowwindowToBeDecorated;// the Window being decoratedpublicWindowDecorator(WindowwindowToBeDecorated){this.windowToBeDecorated=windowToBeDecorated;}@Overridepublicvoiddraw(){windowToBeDecorated.draw();//Delegation}@OverridepublicStringgetDescription(){returnwindowToBeDecorated.getDescription();//Delegation}}// The first concrete decorator which adds vertical scrollbar functionalityclassVerticalScrollBarDecoratorextendsWindowDecorator{publicVerticalScrollBarDecorator(WindowwindowToBeDecorated){super(windowToBeDecorated);}@Overridepublicvoiddraw(){super.draw();drawVerticalScrollBar();}privatevoiddrawVerticalScrollBar(){// Draw the vertical scrollbar}@OverridepublicStringgetDescription(){returnsuper.getDescription()+", including vertical scrollbars";}}// The second concrete decorator which adds horizontal scrollbar functionalityclassHorizontalScrollBarDecoratorextendsWindowDecorator{publicHorizontalScrollBarDecorator(WindowwindowToBeDecorated){super(windowToBeDecorated);}@Overridepublicvoiddraw(){super.draw();drawHorizontalScrollBar();}privatevoiddrawHorizontalScrollBar(){// Draw the horizontal scrollbar}@OverridepublicStringgetDescription(){returnsuper.getDescription()+", including horizontal scrollbars";}}

Here's a test program that creates aWindow instance which is fully decorated (i.e., with vertical and horizontal scrollbars), and prints its description:

publicclassDecoratedWindowTest{publicstaticvoidmain(String[]args){// Create a decorated Window with horizontal and vertical scrollbarsWindowdecoratedWindow=newHorizontalScrollBarDecorator(newVerticalScrollBarDecorator(newSimpleWindow()));// Print the Window's descriptionSystem.out.println(decoratedWindow.getDescription());}}

The output of this program is "simple window, including vertical scrollbars, including horizontal scrollbars". Notice how thegetDescription method of the two decorators first retrieve the decoratedWindow's description anddecorates it with a suffix.

Below is the JUnit test class for the Test Driven Development

import staticorg.junit.Assert.assertEquals;importorg.junit.Test;publicclassWindowDecoratorTest{@TestpublicvoidtestWindowDecoratorTest(){WindowdecoratedWindow=newHorizontalScrollBarDecorator(newVerticalScrollBarDecorator(newSimpleWindow()));// assert that the description indeed includes horizontal + vertical scrollbarsassertEquals("simple window, including vertical scrollbars, including horizontal scrollbars",decoratedWindow.getDescription());}}


Second example (coffee making scenario)

[edit]

The next Java example illustrates the use of decorators using coffee making scenario.In this example, the scenario only includes cost and ingredients.

// The interface Coffee defines the functionality of Coffee implemented by decoratorpublicinterfaceCoffee{publicdoublegetCost();// Returns the cost of the coffeepublicStringgetIngredients();// Returns the ingredients of the coffee}// Extension of a simple coffee without any extra ingredientspublicclassSimpleCoffeeimplementsCoffee{@OverridepublicdoublegetCost(){return1;}@OverridepublicStringgetIngredients(){return"Coffee";}}

The following classes contain the decorators for allCoffee classes, including the decorator classes themselves.

// Abstract decorator class - note that it implements Coffee interfacepublicabstractclassCoffeeDecoratorimplementsCoffee{privatefinalCoffeedecoratedCoffee;publicCoffeeDecorator(Coffeec){this.decoratedCoffee=c;}@OverridepublicdoublegetCost(){// Implementing methods of the interfacereturndecoratedCoffee.getCost();}@OverridepublicStringgetIngredients(){returndecoratedCoffee.getIngredients();}}// Decorator WithMilk mixes milk into coffee.// Note it extends CoffeeDecorator.classWithMilkextendsCoffeeDecorator{publicWithMilk(Coffeec){super(c);}@OverridepublicdoublegetCost(){// Overriding methods defined in the abstract superclassreturnsuper.getCost()+0.5;}@OverridepublicStringgetIngredients(){returnsuper.getIngredients()+", Milk";}}// Decorator WithSprinkles mixes sprinkles onto coffee.// Note it extends CoffeeDecorator.classWithSprinklesextendsCoffeeDecorator{publicWithSprinkles(Coffeec){super(c);}@OverridepublicdoublegetCost(){returnsuper.getCost()+0.2;}@OverridepublicStringgetIngredients(){returnsuper.getIngredients()+", Sprinkles";}}

Here's a test program that creates aCoffee instance which is fully decorated (with milk and sprinkles), and calculate cost of coffee and prints its ingredients:

publicclassMain{publicstaticvoidprintInfo(Coffeec){System.out.println("Cost: "+c.getCost()+"; Ingredients: "+c.getIngredients());}publicstaticvoidmain(String[]args){Coffeec=newSimpleCoffee();printInfo(c);c=newWithMilk(c);printInfo(c);c=newWithSprinkles(c);printInfo(c);}}

The output of this program is given below:

Cost: 1.0; Ingredients: CoffeeCost: 1.5; Ingredients: Coffee, MilkCost: 1.7; Ingredients: Coffee, Milk, Sprinkles

PHP

[edit]
abstractclassComponent{protected$data;protected$value;abstractpublicfunctiongetData();abstractpublicfunctiongetValue();}classConcreteComponentextendsComponent{publicfunction__construct(){$this->value=1000;$this->data="Concrete Component:\t{$this->value}\n";}publicfunctiongetData(){return$this->data;}publicfunctiongetValue(){return$this->value;}}abstractclassDecoratorextendsComponent{}classConcreteDecorator1extendsDecorator{publicfunction__construct(Component$data){$this->value=500;$this->data=$data;}publicfunctiongetData(){return$this->data->getData()."Concrete Decorator 1:\t{$this->value}\n";}publicfunctiongetValue(){return$this->value+$this->data->getValue();}}classConcreteDecorator2extendsDecorator{publicfunction__construct(Component$data){$this->value=500;$this->data=$data;}publicfunctiongetData(){return$this->data->getData()."Concrete Decorator 2:\t{$this->value}\n";}publicfunctiongetValue(){return$this->value+$this->data->getValue();}}classClient{private$component;publicfunction__construct(){$this->component=newConcreteComponent();$this->component=$this->wrapComponent($this->component);echo$this->component->getData();echo"Client:\t\t\t";echo$this->component->getValue();}privatefunctionwrapComponent(Component$component){$component1=newConcreteDecorator1($component);$component2=newConcreteDecorator2($component1);return$component2;}}$client=newClient();// Result: #quanton81//Concrete Component:1000//Concrete Decorator 1:500//Concrete Decorator 2:500//Client:               2000

Python

[edit]

The following Python example, taken fromPython Wiki - DecoratorPattern, shows us how to pipeline decorators to dynamically add many behaviors in an object:

"""Demonstrated decorators in a world of a 10x10 grid of values 0-255."""importrandomdefs32_to_u16(x):ifx<0:sign=0xF000else:sign=0bottom=x&0x00007FFFreturnbottom|signdefseed_from_xy(x,y):returns32_to_u16(x)|(s32_to_u16(y)<<16)classRandomSquare:def__init__(s,seed_modifier):s.seed_modifier=seed_modifierdefget(s,x,y):seed=seed_from_xy(x,y)^s.seed_modifierrandom.seed(seed)returnrandom.randint(0,255)classDataSquare:def__init__(s,initial_value=None):s.data=[initial_value]*10*10defget(s,x,y):returns.data[(y*10)+x]# yes: these are all 10x10defset(s,x,y,u):s.data[(y*10)+x]=uclassCacheDecorator:def__init__(s,decorated):s.decorated=decorateds.cache=DataSquare()defget(s,x,y):ifs.cache.get(x,y)==None:s.cache.set(x,y,s.decorated.get(x,y))returns.cache.get(x,y)classMaxDecorator:def__init__(s,decorated,max):s.decorated=decorateds.max=maxdefget(s,x,y):ifs.decorated.get(x,y)>s.max:returns.maxreturns.decorated.get(x,y)classMinDecorator:def__init__(s,decorated,min):s.decorated=decorateds.min=mindefget(s,x,y):ifs.decorated.get(x,y)<s.min:returns.minreturns.decorated.get(x,y)classVisibilityDecorator:def__init__(s,decorated):s.decorated=decorateddefget(s,x,y):returns.decorated.get(x,y)defdraw(s):foryinrange(10):forxinrange(10):print("%3d"%s.get(x,y),end=' ')print()# Now, build up a pipeline of decorators:random_square=RandomSquare(635)random_cache=CacheDecorator(random_square)max_filtered=MaxDecorator(random_cache,200)min_filtered=MinDecorator(max_filtered,100)final=VisibilityDecorator(min_filtered)final.draw()

Note:

The Decorator Pattern (or an implementation of this design pattern in Python - as the above example) should not be confused withPython Decorators, a language feature of Python. They are different things.

Second to the Python Wiki:

The Decorator Pattern is a pattern described in the Design Patterns Book. It is a way of apparently modifying an object's behavior, by enclosing it inside a decorating object with a similar interface.This is not to be confused with Python Decorators, which is a language feature for dynamically modifying a function or class.[8]

Crystal

[edit]
abstractclassCoffeeabstractdefcostabstractdefingredientsend# Extension of a simple coffeeclassSimpleCoffee<Coffeedefcost1.0enddefingredients"Coffee"endend# Abstract decoratorclassCoffeeDecorator<Coffeeprotectedgetterdecorated_coffee:Coffeedefinitialize(@decorated_coffee)enddefcostdecorated_coffee.costenddefingredientsdecorated_coffee.ingredientsendendclassWithMilk<CoffeeDecoratordefcostsuper+0.5enddefingredientssuper+", Milk"endendclassWithSprinkles<CoffeeDecoratordefcostsuper+0.2enddefingredientssuper+", Sprinkles"endendclassProgramdefprint(coffee:Coffee)puts"Cost:#{coffee.cost}; Ingredients:#{coffee.ingredients}"enddefinitializecoffee=SimpleCoffee.newprint(coffee)coffee=WithMilk.new(coffee)print(coffee)coffee=WithSprinkles.new(coffee)print(coffee)endendProgram.new

Output:

Cost: 1.0; Ingredients: CoffeeCost: 1.5; Ingredients: Coffee, MilkCost: 1.7; Ingredients: Coffee, Milk, Sprinkles

C#

[edit]
namespaceWikiDesignPatterns;publicinterfaceIBike{stringGetDetails();doubleGetPrice();}publicclassAluminiumBike:IBike{publicdoubleGetPrice()=>100.0;publicstringGetDetails()=>"Aluminium Bike";}publicclassCarbonBike:IBike{publicdoubleGetPrice()=>1000.0;publicstringGetDetails()=>"Carbon";}publicabstractclassBikeAccessories:IBike{privatereadonlyIBike_bike;publicBikeAccessories(IBikebike){_bike=bike;}publicvirtualdoubleGetPrice()=>_bike.GetPrice();publicvirtualstringGetDetails()=>_bike.GetDetails();}publicclassSecurityPackage:BikeAccessories{publicSecurityPackage(IBikebike):base(bike){}publicoverridestringGetDetails()=>base.GetDetails()+" + Security Package";publicoverridedoubleGetPrice()=>base.GetPrice()+1;}publicclassSportPackage:BikeAccessories{publicSportPackage(IBikebike):base(bike){}publicoverridestringGetDetails()=>base.GetDetails()+" + Sport Package";publicoverridedoubleGetPrice()=>base.GetPrice()+10;}publicclassBikeShop{publicstaticvoidUpgradeBike(){varbasicBike=newAluminiumBike();BikeAccessoriesupgraded=newSportPackage(basicBike);upgraded=newSecurityPackage(upgraded);Console.WriteLine($"Bike: '{upgraded.GetDetails()}' Cost: {upgraded.GetPrice()}");}}

Output:

Bike: 'Aluminium Bike + Sport Package + Security Package' Cost: 111

Ruby

[edit]
classAbstractCoffeedefprintputs"Cost:#{cost}; Ingredients:#{ingredients}"endendclassSimpleCoffee<AbstractCoffeedefcost1.0enddefingredients"Coffee"endendclassWithMilk<SimpleDelegatordefcost__getobj__.cost+0.5enddefingredients__getobj__.ingredients+", Milk"endendclassWithSprinkles<SimpleDelegatordefcost__getobj__.cost+0.2enddefingredients__getobj__.ingredients+", Sprinkles"endendcoffee=SimpleCoffee.newcoffee.printcoffee=WithMilk.new(coffee)coffee.printcoffee=WithSprinkles.new(coffee)coffee.print


Output:

Cost: 1.0; Ingredients: CoffeeCost: 1.5; Ingredients: Coffee, MilkCost: 1.7; Ingredients: Coffee, Milk, Sprinkles

See also

[edit]

References

[edit]
  1. ^Gamma, Erich; et al. (1995).Design Patterns. Reading, MA: Addison-Wesley Publishing Co, Inc. pp. 175ff.ISBN 0-201-63361-2.
  2. ^"How to Implement a Decorator Pattern". Archived from the original on 2015-07-07.
  3. ^"The Decorator Pattern, Why We Stopped Using It, and the Alternative". 8 March 2022.
  4. ^Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994).Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 175ff.ISBN 0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link)
  5. ^abc"The Decorator design pattern - Problem, Solution, and Applicability".w3sDesign. Archived fromthe original on 2023-04-08. Retrieved2017-08-12.
  6. ^Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.).Head First Design Patterns(paperback). Vol. 1. O'Reilly. pp. 243, 252, 258, 260.ISBN 978-0-596-00712-6. Retrieved2012-07-02.
  7. ^"The Decorator design pattern - Structure and Collaboration".w3sDesign.com. Retrieved2017-08-12.
  8. ^"DecoratorPattern - Python Wiki".wiki.python.org.

External links

[edit]
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Decorator_pattern&oldid=1281443617"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp