<<

Software design 1 Software

In , a pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or . Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design are formalized best practices that the can use to solve common problems when designing an application or system. Object-oriented typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Patterns that imply mutable state may be unsuited for languages, some patterns can be rendered unnecessary in languages that have built-in support for solving the problem they are trying to solve, and object-oriented patterns are not necessarily suitable for non-object-oriented languages. Design patterns may be viewed as a structured approach to intermediate between the levels of a and a concrete .

History Patterns originated as an architectural concept by as early as 1966 (.f. "The Pattern of Streets," JOURNAL OF THE AIP, September, 1966, Vol. 32, No. 3, pp. 273-278). In 1987, and began experimenting with the idea of applying patterns to programming – specifically pattern languages – and presented their results at the OOPSLA conference that year. In the following years, Beck, Cunningham and others followed up on this work. Design patterns gained popularity in after the book Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994 by the so-called "Gang of Four" (Gamma et al.), which is frequently abbreviated as "GoF". That same year, the first Pattern Languages of Programming Conference was held, and the following year the Portland Pattern Repository was set up for documentation of design patterns. The of the term remains a matter of dispute. Notable books in the design pattern genre include: • Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 978-0-201-63361-0. • Brinch Hansen, Per (1995). Studies in Computational Science: Parallel Programming Paradigms. Prentice Hall. ISBN 978-0-13-439324-7. • Buschmann, Frank; Meunier, Regine; Rohnert, Hans; Sommerlad, Peter (1996). Pattern-Oriented , Volume 1: A System of Patterns. John Wiley & Sons. ISBN 978-0-471-95869-7. • Beck, Kent (1997). Best Practice Patterns. Prentice Hall. ISBN 978-0134769042. • Schmidt, Douglas C.; Stal, Michael; Rohnert, Hans; Buschmann, Frank (2000). Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects. John Wiley & Sons. ISBN 978-0-471-60695-6. • Fowler, Martin (2002). Patterns of Enterprise Application Architecture. Addison-Wesley. ISBN 978-0-321-12742-6. • Hohpe, Gregor; Woolf, Bobby (2003). Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley. ISBN 978-0-321-20068-6. 2

• Freeman, Eric T; Robson, Elisabeth; Bates, Bert; Sierra, Kathy (2004). Head First Design Patterns. O'Reilly Media. ISBN 978-0-596-00712-6. Although design patterns have been applied practically for a long time, formalization of the concept of design patterns languished for several years.

Practice Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Freshly written code can often have hidden subtle issues that take time to be detected, issues that sometimes can cause major problems down the road. Reusing design patterns helps to prevent such subtle issuesWikipedia:Citation needed, and it also improves code readability for coders and architects who are familiar with the patterns. In order to achieve flexibility, design patterns usually introduce additional levels of indirection, which in some cases may complicate the resulting designs and hurt application performance. By definition, a pattern must be programmed anew into each application that uses it. Since some authors see this as a step backward from software reuse as provided by components, researchers have worked to turn patterns into components. Meyer and Arnout were able to provide full or partial componentization of two-thirds of the patterns they attempted. Software design techniques are difficult to apply to a broader range of problems.Wikipedia:Citation needed Design patterns provide general solutions, documented in a format that does not require specifics tied to a particular problem.

Structure Design patterns are composed of several sections (see § Documentation below). Of particular interest are the Structure, Participants, and Collaboration sections. These sections describe a design motif: a prototypical micro-architecture that developers copy and adapt to their particular designs to solve the recurrent problem described by the design pattern. A micro-architecture is a set of program constituents (e.g., classes, methods...) and their relationships. Developers use the design pattern by introducing in their designs this prototypical micro-architecture, which means that micro-architectures in their designs will have structure and organization similar to the chosen design motif.

Domain-specific patterns Efforts have also been made to codify design patterns in particular domains, including use of existing design patterns as well as domain specific design patterns. Examples include user design patterns, information visualization, secure design, "secure usability", Web design and business model design. The annual Pattern Languages of Programming Conference proceedings [1] include many examples of domain-specific patterns.

Classification and list Design patterns had originally been categorized into 3 sub-classifications based on kind of problem they solve. Creational patterns provide the capability to create objects based on a required criteria and in a controlled way. Structural patterns are about organizing different classes and objects to form larger structures and provide new functionality. Finally, behavioral patterns are about identifying common communication patterns between objects and realize these patterns. Software design pattern 3

Creational patterns

Name Description In Design In Code Other Patterns Complete

Abstract factory Provide an interface for creating families of related or dependent objects without Yes Yes N/A specifying their concrete classes.

Builder Separate the construction of a complex object from its representation, allowing the Yes No N/A same construction process to create various representations.

Dependency Injection A class accepts the objects it requires from an injector instead of creating the objects No No N/A directly.

Factory method Define an interface for creating a single object, but let subclasses decide which class Yes Yes N/A to instantiate. Factory Method lets a class defer instantiation to subclasses.

Lazy initialization Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. This pattern appears in the GoF No No PoEAA catalog as "virtual proxy", an implementation strategy for the .

Multiton Ensure a class has only named instances, and provide a global point of access to them. No No N/A

Object pool Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and pool No No N/A patterns.

Prototype Specify the kinds of objects to create using a prototypical instance, and create new objects from the 'skeleton' of an existing object, thus boosting performance and Yes No N/A keeping memory footprints to a minimum.

Resource acquisition Ensure that resources are properly released by tying them to the lifespan of suitable No No N/A is initialization (RAII) objects.

Singleton Ensure a class has only one instance, and provide a global point of access to it. Yes Yes N/A

Structural patterns

Name Description In Design In Code Other Patterns Complete

Adapter, Convert the interface of a class into another interface clients expect. An Wrapper, or adapter lets classes work together that could not otherwise because of Yes Yes N/A Translator incompatible interfaces. The enterprise integration pattern equivalent is the translator.

Bridge Decouple an abstraction from its implementation allowing the two to Yes Yes N/A vary independently.

Composite Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of Yes Yes N/A objects uniformly.

Decorator Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing Yes Yes N/A for extending functionality.

Extension Adding functionality to a hierarchy without changing the hierarchy. Agile Software object No No Development, Principles, Patterns, and Practices

Facade Provide a unified interface to a set of interfaces in a subsystem. Facade Yes Yes N/A defines a higher-level interface that makes the subsystem easier to use.

Flyweight Use sharing to support large numbers of similar objects efficiently. Yes No N/A Software design pattern 4

Front controller The pattern relates to the design of Web applications. It provides a No No J2EE Patterns PoEAA centralized for handling requests.

Marker Empty interface to associate metadata with a class. No No Effective Java

Module Group several related elements, such as classes, singletons, methods, No No N/A globally used, into a single conceptual entity.

Proxy Provide a surrogate or placeholder for another object to control access to Yes No N/A it.

Twin Twin allows modeling of multiple inheritance in programming No No N/A languages that do not support this feature.

Behavioral patterns

Name Description In Design In Code Other Patterns Complete

Blackboard pattern for combining disparate sources of data (see blackboard No No N/A system)

Chain of Avoid coupling the sender of a request to its receiver by giving more than one object a responsibility chance to handle the request. Chain the receiving objects and pass the request along the Yes No N/A chain until an object handles it.

Command Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, and the queuing or logging of requests. It also allows for the Yes No N/A support of undoable operations.

Interpreter Given a language, define a representation for its grammar along with an that Yes No N/A uses the representation to interpret sentences in the language.

Iterator Provide a way to access the elements of an aggregate object sequentially without Yes Yes N/A exposing its underlying representation.

Mediator Define an object that encapsulates how a set of objects interact. Mediator promotes by keeping objects from referring to each other explicitly, and it allows their Yes No N/A interaction to vary independently.

Memento Without violating encapsulation, capture and externalize an object's internal state Yes No N/A allowing the object to be restored to this state later.

Null object Avoid references by providing a default object. No No N/A

Observer or Define a one-to-many dependency between objects where a state change in one object Yes Yes N/A Publish/subscribe results in all its dependents being notified and updated automatically.

Servant Define common functionality for a group of classes. The pattern is also frequently called or utility class implementation for a given set of classes. The helper No No N/A classes generally have no objects hence they have all static methods that act upon different kinds of class objects.

Specification Recombinable business logic in a Boolean fashion. No No N/A

State Allow an object to alter its behavior when its internal state changes. The object will Yes No N/A appear to change its class.

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

Template method Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing Yes Yes N/A the algorithm's structure. Software design pattern 5

Visitor Represent an operation to be performed on the elements of an object structure. Visitor lets a new operation be defined without changing the classes of the elements on which it Yes No N/A operates.

Concurrency patterns

Name Description In Other POSA2

Active Object Decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling Yes N/A requests.

Balking Only execute an action on an object when the object is in a particular state. No N/A

Binding properties Combining multiple observers to force properties in different objects to be synchronized or coordinated [2] No N/A in some way.

Compute kernel The same calculation many times in parallel, differing by integer parameters used with non-branching pointer math into shared arrays, such as GPU-optimized Matrix multiplication or Convolutional neural No N/A network.

Double-checked Reduce the overhead of acquiring a by first testing the locking criterion (the 'lock hint') in an unsafe locking manner; only if that succeeds does the actual locking logic proceed. Can be unsafe when implemented in Yes N/A some language/hardware combinations. It can therefore sometimes be considered an anti-pattern.

Event-based Addresses problems with the asynchronous pattern that occur in multithreaded programs. No N/A asynchronous

Guarded suspension Manages operations that require both a lock to be acquired and a precondition to be satisfied before the No N/A operation can be executed.

Join Join-pattern provides a way to write concurrent, parallel and distributed programs by . No N/A Compared to the use of threads and locks, this is a high-level programming model.

[3] Lock One thread puts a "lock" on a resource, preventing other threads from accessing or modifying it. No PoEAA

Messaging design Allows the interchange of information (i.e. messages) between components and applications. No N/A pattern (MDP)

Monitor object An object whose methods are subject to , thus preventing multiple objects from Yes N/A erroneously trying to use it at the same time.

Reactor A reactor object provides an asynchronous interface to resources that must be handled synchronously. Yes N/A

Read-write lock Allows concurrent read access to an object, but requires exclusive access for write operations. No N/A

Scheduler Explicitly control when threads may execute single-threaded code. No N/A

Thread pool A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool No N/A pattern.

Thread-specific Static or "global" memory local to a thread. Yes N/A storage Software design pattern 6

Documentation The documentation for a design pattern describes the context in which the pattern is used, the forces within the context that the pattern seeks to resolve, and the suggested solution. There is no single, standard format for documenting design patterns. Rather, a variety of different formats have been used by different pattern authors. However, according to Martin Fowler, certain pattern forms have become more well-known than others, and consequently become common starting points for new pattern-writing efforts. One example of a commonly used documentation format is the one used by , Richard Helm, Ralph Johnson, and John Vlissides in their book Design Patterns. It contains the following sections: • Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern. • Intent: A description of the goal behind the pattern and the reason for using it. • Also Known As: Other names for the pattern. • Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used. • Applicability: Situations in which this pattern is usable; the context for the pattern. • Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose. • Participants: A listing of the classes and objects used in the pattern and their roles in the design. • Collaboration: A description of how classes and objects used in the pattern interact with each other. • Consequences: A description of the results, side effects, and trade offs caused by using the pattern. • Implementation: A description of an implementation of the pattern; the solution part of the pattern. • Sample Code: An illustration of how the pattern can be used in a . • Known Uses: Examples of real usages of the pattern. • Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.

Criticism It has been observed that design patterns may just be a sign that some features are missing in a given programming language (Java or C++ for instance). Peter Norvig demonstrates that 16 out of the 23 patterns in the Design Patterns book (which is primarily focused on C++) are simplified or eliminated (via direct language support) in Lisp or Dylan. Related observations were made by Hannemann and Kiczales who implemented several of the 23 design patterns using an aspect-oriented programming language (AspectJ) and showed that code-level dependencies were removed from the implementations of 17 of the 23 design patterns and that aspect-oriented programming could simplify the implementations of design patterns.Wikipedia:Citation needed See also 's essay "Revenge of the Nerds". Inappropriate use of patterns may unnecessarily increase complexity. Software design pattern 7

References

[1] Pattern Languages of Programming, Conference proceedings (annual, 1994—) (http:/ / hillside. net/ plop/ pastconferences. html)

[2] Binding Properties (http:/ / c2. com/ cgi/ wiki?BindingProperties)

[3] Lock Pattern (http:/ / c2. com/ cgi/ wiki?LockPattern)

Further reading • Alexander, Christopher; Ishikawa, Sara; Silverstein, Murray; Jacobson, Max; Fiksdahl-King, Ingrid; Angel, Shlomo (1977). A : Towns, Buildings, Construction. New York: Oxford University Press. ISBN 978-0-19-501919-3. • Alur, Deepak; Crupi, John; Malks, Dan (May 2003). Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition). Prentice Hall. ISBN 978-0-13-142246-9. • Beck, Kent (October 2007). Implementation Patterns. Addison-Wesley. ISBN 978-0-321-41309-3. • Beck, Kent; Crocker, R.; Meszaros, G.; Coplien, J. O.; Dominick, L.; Paulisch, F.; Vlissides, J. (March 1996). Proceedings of the 18th International Conference on Software Engineering. pp. 25–30. • Borchers, Jan (2001). A Pattern Approach to Interaction Design. John Wiley & Sons. ISBN 978-0-471-49828-5. • Coplien, James O.; Schmidt, Douglas C. (1995). Pattern Languages of Program Design. Addison-Wesley. ISBN 978-0-201-60734-5. • Coplien, James O.; Vlissides, John M.; Kerth, Norman L. (1996). Pattern Languages of Program Design 2. Addison-Wesley. ISBN 978-0-201-89527-8. • Eloranta, Veli-Pekka; Koskinen, Johannes; Leppänen, Marko; Reijonen, Ville (2014). Designing Distributed Control Systems: Approach. Wiley. ISBN 978-1118694152. • Fowler, Martin (1997). Analysis Patterns: Reusable Object Models. Addison-Wesley. ISBN 978-0-201-89542-1. • Fowler, Martin (2003). Patterns of Enterprise Application Architecture. Addison-Wesley. ISBN 978-0-321-12742-6. • Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Head First Design Patterns. O'Reilly Media. ISBN 978-0-596-00712-6. • Hohmann, Luke; Fowler, Martin; Kawasaki, Guy (2003). Beyond Software Architecture. Addison-Wesley. ISBN 978-0-201-77594-5.

• Gabriel, Richard (1996). Patterns of Software: Tales From The Software Community (https:/ / web. archive. org/

web/ 20030801111358/ http:/ / dreamsongs. com/ NewFiles/ PatternsOfSoftware. pdf) (PDF). Oxford University

Press. p. 235. ISBN 978-0-19-512123-0. Archived from the original (http:/ / www. dreamsongs. com/

NewFiles/ PatternsOfSoftware. pdf) (PDF) on 2003-08-01. • Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 978-0-201-63361-0. • Hohpe, Gregor; Woolf, Bobby (2003). Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley. ISBN 978-0-321-20068-6.

src="Module:Citation/CS1/styles.css"> • Holub, Allen (2004). Holub on Patterns. Apress. ISBN 978-1-59059-388-2. • Kircher, Michael; Völter, Markus; Zdun, Uwe (2005). Remoting Patterns: Foundations of Enterprise,

and Realtime Distributed Object Middleware (https:/ / archive. org/ details/ remotingpatterns0000volt). John Wiley & Sons. ISBN 978-0-470-85662-8. • Larman, Craig (2005). Applying UML and Patterns. Prentice Hall. ISBN 978-0-13-148906-6. • Liskov, Barbara; Guttag, John (2000). Program Development in Java: Abstraction, Specification, and Object-Oriented Design. Addison-Wesley. ISBN 978-0-201-65768-5. • Manolescu, Dragos; Voelter, Markus; Noble, James (2006). Pattern Languages of Program Design 5. Addison-Wesley. ISBN 978-0-321-32194-7.

• Marinescu, Floyd (2002). EJB Design Patterns: Advanced Patterns, Processes and Idioms (https:/ / archive. org/

details/ ejbdesignpattern00mari). John Wiley & Sons. ISBN 978-0-471-20831-0. • Martin, Robert Cecil; Riehle, Dirk; Buschmann, Frank (1997). Pattern Languages of Program Design 3. Addison-Wesley. ISBN 978-0-201-31011-5. • Mattson, Timothy G; Sanders, Beverly A.; Massingill, Berna L. (2005). Patterns for Parallel Programming

(https:/ / archive. org/ details/ patternsforparal0000matt). Addison-Wesley. ISBN 978-0-321-22811-6. • Shalloway, Alan; Trott, James R. (2001). Design Patterns Explained, Second Edition: A New Perspective on

Object-Oriented Design (https:/ / archive. org/ details/ isbn_9780321247148). Addison-Wesley. ISBN 978-0-321-24714-8. • Vlissides, John M. (1998). Pattern Hatching: Design Patterns Applied. Addison-Wesley. ISBN 978-0-201-43293-0.

• Weir, Charles; Noble, James (2000). Small Memory Software: Patterns for systems with limited memory (https:/ /

web. archive. org/ web/ 20070617114432/ http:/ / www. cix. co. uk/ ~smallmemory). Addison-Wesley.

ISBN 978-0-201-59607-6. Archived from the original (http:/ / www. cix. co. uk/ ~smallmemory/ ) on 2007-06-17. 9 Abstract factory pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

UML The abstract factory software design patternpattern provides a way to encapsulate a group of individual factory objectfactories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic Interface (object-oriented programming)interface of the factory to create the concrete Object (computer science)objects that are part of the theme. The client (computing)client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on , as object creation is implemented in methods exposed in the factory interface.An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object (computer science)object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client (computing)client is aware. The client code would get an appropriate Instance (computer science)instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would only need to know how to handle the abstract Letter or Resume class, not the specific version that it got from the concrete factory. A factory is the location of a concrete class in the code at which object creationobjects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes. This allows for new Subtypederived types to be introduced with no change to the code that uses the base class.Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at Run time (program lifecycle phase)runtime. However, employment of this pattern, as with similar Design pattern (computer science)design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems that are more difficult to debug and maintain. Overview The Abstract Factory design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. The Abstract Factory design pattern solves problems like: How can an application be independent of how its objects are created? How can a class be independent of how the objects it requires are created? How can families of related or dependent objects be created? Creating objects directly within the class that requires the objects is inflexible because it commits the class to particular objects and makes it impossible to change the instantiation later independently from (without having to change) the class. It stops the class from being reusable if other objects are required, and it makes the class hard to test because real objects cannot be replaced with mock objects. The Abstract Factory design pattern describes how to solve such problems: Encapsulate object creation in a separate (factory) object. That is, define an interface (AbstractFactory) for creating objects, and implement the interface. A class delegates object creation to a factory object instead of creating objects directly. This makes a class independent of Abstract factory pattern 10

how its objects are created (which concrete classes are instantiated). A class can be configured with a factory object, which it uses to create objects, and even more, the factory object can be exchanged at run-time. Definition The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes.".Usage The factory determines the actual concrete type of object (computer science)object to be created, and it is here that the object is actually created (in C++, for instance, by the new operator (programming)operator). However, the factory only returns an abstract pointer (computer programming)pointer to the created object (computer science)concrete object.This insulates client code from object creation by having clients ask a factory object to create an object of the desired and to return an abstract pointer to the object.As the factory only returns an abstract pointer, the client code (that requested the object from the factory) does not know — and is not burdened by — the actual concrete type of the object that was just created. However, the type of a concrete object (and hence a concrete factory) is known by the abstract factory; for instance, the factory may read it from a configuration file. The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means: The client code has no knowledge whatsoever of the concrete Data typetype, not needing to include any header files or Class (computer science)class Declaration (computer science)declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface. Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before — thus insulating the client code from change. This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton patternsingleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.Structure UML diagram Class diagram example The method createButton on the GUIFactory interface returns objects of type Button. What implementation of Button is returned depends on which implementation of GUIFactory is handling the method call.Class diagram example The method createButton on the GUIFactory interface returns objects of type Button. What implementation of Button is returned depends on which implementation of GUIFactory is handling the method call. A sample UML class and for the Abstract Factory design pattern. A sample UML class and sequence diagram for the Abstract Factory design pattern. In the above Unified Modeling LanguageUML class diagram, the Client class that requires ProductA and ProductB objects does not instantiate the ProductA1 and ProductB1 classes directly. Instead, the Client refers to the AbstractFactory interface for creating objects, which makes the Client independent of how the objects are created (which concrete classes are instantiated). The Factory1 class implements the AbstractFactory interface by instantiating the ProductA1 and ProductB1 classes. The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: The Client object calls createProductA() on the Factory1 object, which creates and returns a ProductA1 object. Thereafter, the Client calls createProductB() on Factory1, which creates and returns a ProductB1 object. Lepus3 chart legend legendPython (programming language)Python example from abc import ABC, abstractmethod from sys import platform class Button(ABC): @abstractmethod def paint(self): pass class LinuxButton(Button): def paint(self): return 'Render a button in a style' class WindowsButton(Button): def paint(self): return 'Render a button in a Windows style' class MacOSButton(Button): def paint(self): return 'Render a button in a MacOS style' class GUIFactory(ABC): @abstractmethod def create_button(self): pass class LinuxFactory(GUIFactory): def create_button(self): return LinuxButton() class WindowsFactory(GUIFactory): def create_button(self): return WindowsButton() class MacOSFactory(GUIFactory): def create_button(self): return MacOSButton() if platform == 'linux': factory = LinuxFactory() elif platform == 'darwin': factory = MacOSFactory() elif platform == 'win32': factory = WindowsFactory() else: raise NotImplementedError( f'Not implemented for your Abstract factory pattern 11

platform: {platform}' ) button = factory.create_button() result = button.paint() print(result) Alternative implementation using the classes themselves as factories: from abc import ABC, abstractmethod from sys import platform class Button(ABC): @abstractmethod def paint(self): pass class LinuxButton(Button): def paint(self): return 'Render a button in a Linux style' class WindowsButton(Button): def paint(self): return 'Render a button in a Windows style' class MacOSButton(Button): def paint(self): return 'Render a button in a MacOS style' if platform == "linux": factory = LinuxButton elif platform == "darwin": factory = MacOSButton elif platform == "win32": factory = WindowsButton else: raise NotImplementedError( f'Not implemented for your platform: {platform}' ) button = factory() result = button.paint() print(result) ReferencesExternal linksclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Abstract Factory in action Abstract Factory implementation in Java class=noviewer Media related to Abstract factory at Wikimedia Commons Abstract Factory UML diagram + formal specification in LePUS3 and Class-Z (a Design Description Language) Abstract Factory Abstract Factory implementation example

Builder pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The is a Software design patterndesign pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to Separation of concernsseparate the construction of a complex object from its representation. It is one of the Design PatternsGang of Four design patterns.Overview The Builder design pattern is one of the Design PatternsGoF design patterns that describe how to solve recurring design problems in object-oriented software.The Builder design pattern solves problems like: How can a class (the same construction process) create different representations of a complex object? How can a class that includes creating a complex object be simplified? Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class. The Builder design pattern describes how to solve such problems: Encapsulate creating and assembling the parts of a complex object in a separate Builder object. A class delegates object creation to a Builder object instead of creating the objects directly. A class (the same construction process) can delegate to different Builder objects to create different representations of a complex object. Definition The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so the same construction process can create different representations.Advantages Advantages of the Builder pattern include: Allows you to vary a product's internal representation. Encapsulates code for construction and representation. Provides control over steps of construction process. Disadvantages Disadvantages of the Builder pattern include: Requires creating a separate ConcreteBuilder for each different type of product. Requires the builder classes to be mutable. may be less supported. StructureUML class and sequence diagram A sample UML class and sequence diagram for the Builder design pattern.In the above Unified Modeling LanguageUML class diagram, the Director class doesn't create and assemble the ProductA1 and ProductB1 objects directly. Instead, the Director refers to the Builder pattern 12

Builder interface for building (creating and assembling) the parts of a complex object, which makes the Director independent of which concrete classes are instantiated (which representation is created). The Builder1 class implements the Builder interface by creating and assembling the ProductA1 and ProductB1 objects. The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: The Director object calls buildPartA() on the Builder1 object, which creates and assembles the ProductA1 object. Thereafter, the Director calls buildPartB() on Builder1, which creates and assembles the ProductB1 object. Class diagram Builder StructureBuilder Abstract interface for creating objects (product). ConcreteBuilder Provides implementation for Builder. It is an factory (software concept)object able to construct other objects. Constructs and assembles parts to build the objects. Examples C Sharp (programming language)C# ///

/// Represents a product created by the builder /// public class Car { public string Make { get; set; } public string Model { get; set; } public int NumDoors { get; set; } public string Colour { get; set; } public Car(string make, string model, string colour, int numDoors) { Make = make; Model = model; Colour = colour; NumDoors = numDoors; } } /// /// The builder abstraction /// public interface ICarBuilder { string Colour { get; set; } int NumDoors { get; set; } Car GetResult(); } /// /// Concrete builder implementation /// public class FerrariBuilder : ICarBuilder { public string Colour { get; set; } public int NumDoors { get; set; } public Car GetResult() { return NumDoors == 2 ? new Car("Ferrari", "488 Spider", Colour, NumDoors) : null; } } /// /// The director /// public class SportsCarBuildDirector { private ICarBuilder _builder; public SportsCarBuildDirector(ICarBuilder builder) { _builder = builder; } public void Construct() { _builder.Colour = "Red"; _builder.NumDoors = 2; } } public class Client { public void DoSomethingWithCars() { var builder = new FerrariBuilder(); var director = new SportsCarBuildDirector(builder); director.Construct(); Car myRaceCar = builder.GetResult(); } } The Director assembles a car instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client. References External linksclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Builder implementations in various languages The JavaWorld article Build user interfaces without getters and setters (Allen Holub) shows the complete Java for a Builder. Dependency injection 13 Dependency injection

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, dependency injection is a technique in which an Object (computer science)object receives other objects that it depends on. These other objects are called dependencies. In the typical "using" relationshiphttps://www.sciencedirect.com/topics/computer-science/component-relationship the receiving object is called a Client (computing)client and the passed (that is, "injected") object is called a Service (systems architecture)service. The code that passes the service to the client can be many kinds of things and is called the injector. Instead of the client specifying which service it will use, the injector tells the client what service to use. The "injection" refers to the passing of a dependency (a service) into the object (a client) that would use it. The service is made part of the client's State (computer science)state. Passing the service to the client, rather than allowing a client to build or Service locator patternfind the service, is the fundamental requirement of the pattern. The intent behind dependency injection is to achieve of construction and use of objects. This can increase readability and . Dependency injection is one form of the broader technique of . A client who wants to call some services should not have to know how to construct those services. Instead, the client delegates the responsibility of providing its services to external code (the injector). The client is not allowed to call the injector code; it is the injector that constructs the services. The injector then injects (passes) the services into the client which might already exist or may also be constructed by the injector. The client then uses the services. This means the client does not need to know about the injector, how to construct the services, or even which actual services it is using. The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services. This separates the responsibility of "use" from the responsibility of "construction". IntentDependency Injection solves problems such as: How can an application or Class (computer programming)class be independent of how its objects are created? How can the way objects are created be specified in separate configuration files? How can an application support different configurations? Creating objects directly within the class is inflexible because it commits the class to particular objects and makes it impossible to change the instantiation later independently from (without having to change) the class. It stops the class from being reusable if other objects are required, and it makes the class hard to test because real objects can not be replaced with mock objects. A class is no longer responsible for creating the objects it requires, and it does not have to delegate instantiation to a factory object as in the Abstract_factory_patternAbstract Factory design pattern.See also the UML class and sequence diagram below. Overview Dependency injection for five-year-oldsWhen you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy don't want you to have. You might even be looking for something we don't even have or which has expired. What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.John Munsch, 28 October 2009.Dependency injection separates the creation of a client's dependencies from the client's behavior, which allows program designs to be Loose couplingloosely Coupling (computer programming)coupled and to follow the dependency inversion principledependency inversion and single responsibility principles.Niko Schwarz, Mircea Lungu, Oscar Nierstrasz, “Seuss: Decoupling responsibilities from static methods for fine-grained configurability”, Journal of Object Technology, Volume 11, no. 1 (April 2012), pp. 3:1-23 It directly contrasts with the , which allows clients to know about the system they use to find dependencies. An Dependency injection 14

injection, the basic unit of dependency injection, is not a new or a custom mechanism. It works in the same way that "Parameter (computer programming)parameter passing" works. Referring to "parameter passing" as an injection carries the added implication that it is being done to isolate the client from details. An injection is also about what is in control of the passing (never the client) and is independent of how the passing is accomplished, whether by passing a reference or a value. Dependency injection involves four roles: the service object(s) to be used the client object that is depending on the service(s) it uses the Interface (object-oriented programming)interfaces that define how the client may use the services the injector, which is responsible for constructing the services and injecting them into the clientAs an analogy, service - an electric, gas, hybrid, or diesel car client - a driver who uses the car the same way regardless of the engine interface - Automatic_transmissionautomatic, ensures driver does not have to understand engine details like gears injector - the parent who bought the kid the car and decided which kind Any object that may be used can be considered a service. Any object that uses other objects can be considered a client. The names have nothing to do with what the objects are for and everything to do with the role the objects play in any one injection.The interfaces are the types the client expects its dependencies to be. An issue is what they make accessible. They may truly be interface types implemented by the services but also may be abstract classes or even the Class (computer programming)#Abstract and Concreteconcrete services themselves, though this last would violate dependency inversion principleDIP and sacrifice the dynamic decoupling that enables testing. It is only required that the client does not know which they are and therefore never treats them as concrete, say by constructing or extending them.The client should have no concrete knowledge of the specific implementation of its dependencies. It should only know the interface's name and Application programming interfaceAPI. As a result, the client will not need to change even if what is behind the interface changes. However, if the interface is Code refactoringrefactored from being a class to an interface type (or vice versa) the client will need to be recompiled. This is significant if the client and services are published separately. This unfortunate coupling is one that dependency injection cannot resolve. The injector introduces the services into the client. Often, it also constructs the client. An injector may connect together a very complex object graph by treating an object like a client and later as a service for another client. The injector may actually be many objects working together but may not be the client. The injector may be referred to by other names such as: assembler, provider, container, factory, builder, spring, construction code, or main.Dependency injection can be applied as a discipline, one that asks that all objects separate construction and behavior. Relying on a DI framework to perform construction can lead to forbidding the use of the new keyword, or, less strictly, only allowing direct construction of value objects.TaxonomyInversion of control (IoC) is more general than dependency injection. Put simply, IoC means letting other code call you rather than insisting on doing the calling. An example of IoC without dependency injection is the . Here, Polymorphism (computer science)polymorphism is achieved through Inheritance (object-oriented programming)#Subclasses and superclassessubclassing, that is, Inheritance (object-oriented programming)inheritance.Dependency injection implements IoC through Object compositioncomposition so is often identical to that of the , but while the strategy pattern is intended for dependencies to be interchangeable throughout an object's Object lifetimelifetime, in dependency injection it may be that only a single instance of a dependency is used. This still achieves polymorphism, but through Delegation patterndelegation and Object compositioncomposition. Dependency injection frameworksApplication frameworks such as CDI and its implementation Weld, Spring FrameworkSpring, Guice, , Salta, HK2 DI KernelGlassfish HK2, Dagger, and Managed Extensibility Framework (MEF) support dependency injection but are not required to do dependency injection.Advantages Dependency injection allows a client the flexibility of being configurable. Only the client's behavior is fixed. The client may act on anything that supports the intrinsic interface the client expects.https://python.astrotech.io/design-patterns/structural/dependency-injection.html Dependency injection can be used to externalize a system's configuration details into configuration files, allowing the system to be reconfigured without recompilation. Separate configurations can be written for different situations that require different implementations of components. This includes, but is not limited to, testing.http://python-dependency-injector.ets-labs.org/introduction/di_in_python.html Because dependency injection Dependency injection 15

does not require any change in code behavior it can be applied to legacy code as a Code refactoringrefactoring. The result is clients that are more independent and that are easier to Unit testingunit test in isolation using Method stubstubs or mock objects that simulate other objects not under test. This ease of testing is often the first benefit noticed when using dependency injection.https://visualstudiomagazine.com/articles/2014/07/01/larger-applications.aspxDependency injection allows a client to remove all knowledge of a concrete implementation that it needs to use. This helps isolate the client from the impact of design changes and defects. It promotes , testability and maintainability.Reduction of boilerplate code in the application objects, since all work to initialize or set up dependencies is handled by a provider component.Dependency injection allows concurrent or independent development. Two developers can independently develop Class (computer programming)classes that use each other, while only needing to know the interface the classes will communicate through. Plug-in (computing)Plugins are often developed by third party shops that never even talk to the developers who created the product that uses the plugins.https://dzone.com/articles/how-dependency-injection-di-works-in-spring-java-aDependency Injection decreases coupling between a class and its dependency.Disadvantages Dependency injection creates clients that demand configuration details be supplied by construction code. This can be onerous when obvious defaults are available.https://dzone.com/articles/how-dependency-injection-di-works-in-spring-java-a Dependency injection can make code difficult to trace (read) because it separates behavior from construction. This means developers must refer to more files to follow how a system performs.https://dzone.com/articles/how-dependency-injection-di-works-in-spring-java-a Dependency injection frameworks are implemented with reflection or dynamic programming. This can hinder use of IDE automation, such as "find references", "show call hierarchy" and safe refactorings.https://www.freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/ Dependency injection typically requires more upfront development effort since one can not summon into being something right when and where it is needed but must ask that it be injected and then ensure that it has been injected.https://www.professionalqa.com/dependency-injection Dependency injection forces complexity to move out of classes and into the linkages between classes which might not always be desirable or easily managed. Dependency injection can encourage dependence on a dependency injection framework.Structure UML class and sequence diagram A sample UML class and sequence diagram for the Dependency Injection design pattern. In the above Unified Modeling LanguageUML class diagram, the Client class that requires ServiceA and ServiceB objects does not instantiate the ServiceA1 and ServiceB1 classes directly. Instead, an Injector class creates the objects and injects them into the Client, which makes the Client independent of how the objects are created (which concrete classes are instantiated). The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: The Injector object creates the ServiceA1 and ServiceB1 objects. Thereafter, the Injector creates the Client object and injects the ServiceA1 and ServiceB1 objects. ExamplesWithout dependency injection In the following Java (programming language)Java example, the Client class contains a Service member variable that is initialized by the Client Constructor (object-oriented programming)constructor. The client controls which implementation of service is used and controls its construction. In this situation, the client is said to have a hard-coded dependency on ExampleService. // An example without dependency injection public class Client { // Internal reference to the service used by this client private ExampleService service; // Constructor Client() { // Specify a specific implementation in the constructor instead of using dependency injection service = new ExampleService(); } // Method within this client that uses the services public String greet() { return "Hello " + service.getName(); } } Dependency injection is an alternative technique to initialize the member variable rather than explicitly creating a service object as shown above. We can adjust this example using the various techniques described and illustrated in the subsections below. Types of dependency injection There are at least three ways a client object can receive a reference to an external module:constructor injection The dependencies are provided through a client's class constructor. setter injection The client exposes a setter method that the injector uses to inject the dependency. interface injection The dependency's interface provides an injector method that will inject the dependency into any client passed to it. Clients must Dependency injection 16

implement an interface that exposes a setter method that accepts the dependency. Other types It is possible for DI frameworks to have other types of injection beyond those presented above.Testing frameworks may also use other types. Some modern testing frameworks do not even require that clients actively accept dependency injection thus making legacy code testable. In particular, in the Java language it is possible to use reflection to make private attributes public when testing and thus accept injections by assignment.Some attempts at Inversion of Control do not provide full removal of dependency, but instead simply substitute one form of dependency for another. As a rule of thumb, if a programmer can look at nothing but the client code and tell what framework is being used, then the client has a hard-coded dependency on the framework. Constructor injection This method requires the client to provide a parameter in a constructor (object-oriented programming)constructor for the dependency. // Constructor Client(Service service) { // Save the reference to the passed-in service inside this client this.service = service; } Setter injection This method requires the client to provide a setter method for the dependency. // Setter method public void setService(Service service) { // Save the reference to the passed-in service inside this client. this.service = service; } Interface injection This is simply the client publishing a role interface to the setter methods of the client's dependencies. It can be used to establish how the injector should talk to the client when injecting dependencies. // Service setter interface. public interface ServiceSetter { public void setService(Service service); } // Client class public class Client implements ServiceSetter { // Internal reference to the service used by this client. private Service service; // Set the service that this client is to use. @Override public void setService(Service service) { this.service = service; } } Constructor injection comparison Preferred when all dependencies can be constructed first because it can be used to ensure the client object is always in a valid state, as opposed to having some of its dependency references be null (not be set). However, on its own, it lacks the flexibility to have its dependencies changed later. This can be a first step towards making the client Immutable objectimmutable and therefore Thread safetythread safe. // Constructor Client(Service service, Service otherService) { if (service == null) { throw new InvalidParameterException("service must not be null"); } if (otherService == null) { throw new InvalidParameterException("otherService must not be null"); } // Save the service references inside this client this.service = service; this.otherService = otherService; } Setter injection comparison Requires the client to provide a setter method for each dependency. This gives the freedom to manipulate the state of the dependency references at any time. This offers flexibility, but if there is more than one dependency to be injected, it is difficult for the client to ensure that all dependencies are injected before the client could be provided for use. // Set the service to be used by this client public void setService(Service service) { if (service == null) { throw new InvalidParameterException("service must not be null"); } this.service = service; } // Set the other service to be used by this client public void setOtherService(Service otherService) { if (otherService == null) { throw new InvalidParameterException("otherService must not be null"); } this.otherService = otherService; } Because these injections happen independently there is no way to tell when the injector is finished wiring the client. A dependency can be left null simply by the injector failing to call its setter. This forces the check that injection was completed from when the client is assembled to whenever it is used. // Set the service to be used by this client public void setService(Service service) { this.service = service; } // Set the other service to be used by this client public void setOtherService(Service otherService) { this.otherService = otherService; } // Check the service references of this client private void validateState() { if (service == null) { throw new IllegalStateException("service must not be null"); } if (otherService == null) { throw new IllegalStateException("otherService must not be null"); } } // Method that uses the service references public void doSomething() { validateState(); service.doYourThing(); otherService.doYourThing(); } Interface injection comparison The advantage of interface injection is that dependencies can be completely ignorant of their clients yet can still receive a reference to a new client and, using it, send a reference-to-self back to the client. In this way, the dependencies become injectors. The key is that the injecting method (which could just be a classic setter method) is provided through an interface. An assembler is still needed to introduce the client and its dependencies. The assembler would take a reference to the client, cast it to the setter interface that sets that dependency, and pass it to that dependency object which would turn around and pass a reference-to-self back to the client. For interface injection to have value, the dependency must do something in Dependency injection 17

addition to simply passing back a reference to itself. This could be acting as a factory or sub-assembler to resolve other dependencies, thus abstracting some details from the main assembler. It could be reference-counting so that the dependency knows how many clients are using it. If the dependency maintains a collection of clients, it could later inject them all with a different instance of itself. // Service setter interface. public interface ServiceSetter { public void setService(Service service); } // Client class public class Client implements ServiceSetter { // Internal reference to the service used by this client. private Service service; // Set the service that this client is to use. @Override public void setService(Service service) { this.service = service; } } // Injector class public class ServiceInjector { Set clients; public void inject(ServiceSetter client) { clients.add(client); client.setService(new ServiceFoo()); } public void switchToBar() { for (Client client : clients) { client.setService(new ServiceBar()); } } } // Service classes public class ServiceFoo implements Service {} public class ServiceBar implements Service {} Assembling examples Manually assembling in main by hand is one way of implementing dependency injection. public class Injector { public static void main(String[] args) { // Build the dependencies first Service service = new ExampleService(); // Inject the service, constructor style Client client = new Client(service); // Use the objects System.out.println(client.greet()); } } The example above constructs the object graph manually and then invokes it at one point to start it working. Important to note is that this injector is not pure. It uses one of the objects it constructs. It has a purely construction-only relationship with ExampleService but mixes construction and using of Client. This should not be common. It is, however, unavoidable. Just like object oriented software needs a non-object oriented static method like main() to get started, a dependency injected object graph needs at least one (preferably only one) entry point to get the whole thing started. Manual construction in the main method may not be this straight forward and may involve calling Builder patternbuilders, Factory (object-oriented programming)factories, or other Creational patternconstruction patterns as well. This can be fairly advanced and abstract. The line is crossed from manual dependency injection to Software frameworkframework dependency injection once the constructing code is no longer custom to the application and is instead universal.Frameworks like Spring FrameworkSpring can construct these same objects and wire them together before returning a reference to client. All mention of the concrete ExampleService can be moved from the code to the configuration data. import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Injector { public static void main(String[] args) { // -- Assembling objects -- // BeanFactory beanfactory = new ClassPathXmlApplicationContext("Beans."); Client client = (Client) beanfactory.getBean("client"); // -- Using objects -- // System.out.println(client.greet()); } } Frameworks like Spring allow assembly details to be externalized in configuration files. This code (above) constructs objects and wires them together according to Beans.xml (below). ExampleService is still constructed even though it is only mentioned below. A long and complex object graph can be defined this way and the only class mentioned in code would be the one with the entry point method, which in this case is greet(). In the example above Client and Service have not had to undergo any changes to be provided by spring. They are allowed to remain simple Plain Old Java ObjectPOJOs. This shows how spring can connect services and clients that are completely ignorant of its existence. This could not be said if spring annotations are added to the classes. By keeping spring specific annotations and calls from spreading out among many classes, the system stays only loosely dependent on spring. This can be important if the system intends to outlive spring. The choice to keep POJOs pure does not come without cost. Rather than spending the effort to develop and maintain complex configuration files it is possible to simply use annotations to mark classes and let spring do the rest of the work. Resolving dependencies can be simple if they follow a convention such as matching by type or by name. This is Dependency injection 18

choosing convention over configuration. It is also arguable that, when refactoring to another framework, removing framework specific annotations would be a trivial part of the task and many injection annotations are now standardized. import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Injector { public static void main(String[] args) { // Assemble the objects BeanFactory beanfactory = new AnnotationConfigApplicationContext(MyConfiguration.class); Client client = beanfactory.getBean(Client.class); // Use the objects System.out.println(client.greet()); } } import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan public class MyConfiguration { @Bean public Client client(ExampleService service) { return new Client(service); } } @Component public class ExampleService { public String getName() { return "World!"; } } Assembly comparison The different injector implementations (factories, Service locator patternservice locators, and dependency injection containers) are not that different as far as dependency injection is concerned. What makes all the difference is where they are allowed to be used. Move calls to a factory or a service locator out of the client and into main and suddenly main makes a fairly good dependency injection container. By moving all knowledge of the injector out, a clean client, free of knowledge of the outside world, is left behind. However, any object that uses other objects can be considered a client. The object that contains main is no exception. This main object is not using dependency injection. It is actually using the service locator pattern. This can not be avoided because the choice of service implementations must be made somewhere. Externalizing the dependencies into configuration files does not change this fact. What makes this reality part of a good design is that the service locator is not spread throughout the code base. It is confined to one place per application. This leaves the rest of the code base free to use dependency injection to make clean clients. Dependency Injection Pattern The examples until now have been overly simple examples about constructing a string. However, the dependency injection pattern is most useful when constructing an object graph where objects communicate via messages. Objects constructed in main will last for the life of the program. The typical pattern is to construct the graph and then call one method on one object to send the flow of control into the object graph. Just as main is the entry point to the static code, this one method is the entry point to the applications non-static code. public static void main(String[] args) throws IOException { // Construction code. Greeter greeter = new Greeter(System.out); // This may be many lines that connect many objects // Behavior code. greeter.greet(); // This is one call to one method on one object in the object graph } class Greeter { public void greet() { this.out.println("Hello world!"); } public Greeter(PrintStream out) { this.out = out; } private PrintStream out; } AngularJS example In the AngularJS framework, there are only three ways a component (object or function) can directly access its dependencies: The component can create the dependency, typically using the new operator. The component can look up the dependency, by referring to a global variable. The component can have the dependency passed to it where it is needed. The first two options of creating or looking up dependencies are not optimal because they hard code the dependency to the component. This makes it difficult, if not impossible, to modify the dependencies. This is especially problematic in tests, where it is often desirable to provide mock dependencies for test isolation. The third option is the most viable, since it removes the responsibility of locating the dependency from the component. The dependency is simply handed to the component. function SomeClass(greeter) { this.greeter = greeter; } SomeClass.prototype.doSomething = function(name) { this.greeter.greet(name); } In the above example SomeClass is not concerned with creating or locating the greeter dependency, it is simply handed the greeter when it is instantiated. This is desirable, but it puts the responsibility of getting hold of the dependency on the code that constructs SomeClass. To manage the responsibility of dependency creation, each AngularJS application has an injector. The injector is a service locator that is responsible for construction and look-up of dependencies. Here is an example of using the injector service: // Provide the wiring information in a module var myModule = .module('myModule', []); // Teach the injector how to build a greeter service. // greeter is dependent on the $window service. // The greeter service is an object that // contains a greet method. myModule.factory('greeter', Dependency injection 19

function($window) { return { greet: function(text) { $window.alert(text); } }; }); Create a new injector that can provide components defined in the myModule module and request our greeter service from the injector. (This is usually done automatically by the AngularJS bootstrap). var injector = angular.injector(['myModule', 'ng']); var greeter = injector.get('greeter'); Asking for dependencies solves the issue of hard coding, but it also means that the injector needs to be passed throughout the application. Passing the injector breaks the Law of Demeter. To remedy this, we use a declarative notation in our HTML templates, to hand the responsibility of creating components over to the injector, as in this example:

function MyController($scope, greeter) { $scope.sayHello = function() { greeter.greet('Hello World'); }; } When AngularJS compiles the HTML, it processes the ng-controller directive, which in turn asks the injector to create an instance of the controller and its dependencies. injector.instantiate(MyController); This is all done behind the scenes. Because the ng-controller defers to the injector to instantiate the class, it can satisfy all of the dependencies of MyController without the controller ever knowing about the injector. The application code simply declares the dependencies it needs, without having to deal with the injector. This setup does not break the Law of Demeter. C Sharp (programming language)C# Example of the Constructor injection, Setter injection and Interface injection on C# using System; DependencyInjection { // An interface for the library interface IGamepadFunctionality { String GetGamepadName(); void SetVibrationPower(float InPower); } // Concrete implementation of the xbox controller functionality class XBoxGamepad : IGamepadFunctionality { readonly String GamepadName = "XBox Controller"; float VibrationPower = 1.0f; public String GetGamepadName() => GamepadName; public void SetVibrationPower(float InPower) => VibrationPower = Math.Clamp(InPower, 0.0f, 1.0f); } // Concrete implementation of the playstation controller functionality class PlaystationJoystick : IGamepadFunctionality { readonly String ControllerName = "Playstation controller"; float VibratingPower = 100.0f; public String GetGamepadName() => ControllerName; public void SetVibrationPower(float InPower) => VibratingPower = Math.Clamp(InPower * 100.0f, 0.0f, 100.0f); } // Concrete implementation of the steam controller functionality class SteamController : IGamepadFunctionality { readonly String JoystickName = "Steam controller"; double Vibrating = 1.0; public String GetGamepadName() => JoystickName; public void SetVibrationPower(float InPower) => Vibrating = Convert.ToDouble(Math.Clamp(InPower, 0.0f, 1.0f)); } // An interface for gamepad functionality injections interface IGamepadFunctionalityInjector { void InjectFunctionality(IGamepadFunctionality InGamepadFunctionality); } class CGamepad : IGamepadFunctionalityInjector { IGamepadFunctionality _GamepadFunctionality; public CGamepad() { } // Constructor injection public CGamepad(IGamepadFunctionality InGamepadFunctionality) => _GamepadFunctionality = InGamepadFunctionality; // Setter injection public void SetGamepadFunctionality(IGamepadFunctionality InGamepadFunctionality) => _GamepadFunctionality = InGamepadFunctionality; // Interface injection public void InjectFunctionality(IGamepadFunctionality InGamepadFunctionality) => _GamepadFunctionality = InGamepadFunctionality; public void Showcase() { String Message = String.Format("We're using the {0} right now, do you want to change the vibrating power?\r\n", _GamepadFunctionality.GetGamepadName()); Console.WriteLine(Message); } } enum EPlatforms: byte { Xbox, Playstation, Steam } class CGameEngine { EPlatforms _Platform; CGamepad _Gamepad; public void SetPlatform(EPlatforms InPlatform) { _Platform = InPlatform; switch(_Platform) { case EPlatforms.Xbox: // injects dependency on XBoxGamepad class through Constructor Injection _Gamepad = new CGamepad(new XBoxGamepad()); break; case EPlatforms.Playstation: _Gamepad = new CGamepad(); // injects dependency on PlaystationJoystick class through Setter Injection _Gamepad.SetGamepadFunctionality(new PlaystationJoystick()); break; case EPlatforms.Steam: _Gamepad = new CGamepad(); // injects dependency on SteamController class through Interface Injection _Gamepad.InjectFunctionality(new SteamController()); break; } _Gamepad.Showcase(); } } class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); CGameEngine Engine = new CGameEngine(); Engine.SetPlatform(EPlatforms.Steam); Engine.SetPlatform(EPlatforms.Xbox); Engine.SetPlatform(EPlatforms.Playstation); } } } ReferencesExternal linksclass=noviewerWikimedia Commons has media related to Dependency injection. Composition Root by Mark Seemann A beginners guide to Dependency Injection Dependency Injection & Testable Objects: Designing loosely coupled and testable objects - Jeremy Dependency injection 20

Weiskotten; Dr. Dobb's Journal, May 2006. Design Patterns: Dependency Injection -- MSDN Magazine, September 2005 Martin Fowler's original article that introduced the term Dependency Injection P of EAA: Plugin The Rich Engineering Heritage Behind Dependency Injection - Andrew McVeigh - A detailed history of dependency injection. What is Dependency Injection? - An alternative explanation - Jakob Jenkov Writing More Testable Code with Dependency Injection -- Developer.com, October 2006 Managed Extensibility Framework Overview -- MSDN Old fashioned description of the Dependency Mechanism by Hunt 1998 Refactor Your Way to a Dependency Injection Container Understanding DI in PHP You Don't Need a Dependency Injection Container

Factory method pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In class-based programming, the is a that uses factory methods to deal with the problem of object creationcreating objects without having to specify the exact class (computer programming)class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an Interface (object-oriented programming)interface and implemented by child classes, or implemented in a base class and optionally method overridingoverridden by derived classes—rather than by calling a Constructor (object-oriented programming)constructor.Overview The Factory Method design pattern is one of the Design Patterns"Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.The Factory Method design pattern is used instead of the regular class constructor for keeping within the SOLID principles of programming, decoupling the construction of objects from the objects themselves. This has the following advantages and is useful for the following cases, among others: Allows construction of classes with a component of a type that has not been predetermined, but only defined in an "interface", or which is defined as a dynamic type. Thus, for example, a class Vehicle that has a member Motor of interface IMotor, but no concrete type of Motor defined in advance, can be constructed by telling the Vehicle constructor to use an ElectricMotor or a GasolineMotor. The Vehicle constructor code then calls a Motor factory method, to create the desired Motor that complies with the IMotor interface. Allows construction of subclasses to a parent whose component type has not been predetermined, but only defined in an interface, or which is defined as a dynamic type. For example, a class Vehicle with a member Motor defined with a dynamic type, can have subclasses of type ElectricPlane and OldCar each constructed with a different type of Motor. This can be accomplished by constructing the subclasses with a Vehicle factory method, while supplying the motor type. In cases like this the constructor may be hidden. Allows for more readable code in cases where multiple constructors exist, each for a different reason. For example if there are two constructors Vehicle(make:string, motor:number) and Vehicle(make:string, owner:string, license:number, purchased:date) a more readable construction of the classes would be to use Vehicle.CreateOwnership(make:string, owner:string, license:number, purchased: date) vs Vehicle.Create(make:string, motor:number) Allows a class to defer instantiation to subclasses, and to prevent direct instantiation of an object of the parent class type. For example, a Vehicle can be prevented from being instantiated directly since it has no constructor, and only subclasses like Factory method pattern 21

ElectricPlane or OldCar can be created by calling the Vehicle (static) factory method in the subclass constructor or initializer. Creating an object directly within the class that requires or uses the object is inflexible because it commits the class to a particular object and makes it impossible to change the instantiation independently of the class. A change to the instantiator would require a change to the class code which we would rather not touch. This is referred to as code coupling and the Factory method pattern assists in decoupling the code. The Factory Method design pattern is used by first defining a separate operation, a factory method, for creating an object, and then using this factory method by calling it to create the object. This enables writing of subclasses that decide how a parent object is created and what type of objects the parent contains. See the UML class diagram below. Definition "Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses." (Gang of Four (software)Gang Of Four) Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concern (computer science)concerns. The factory method design pattern handles these problems by defining a separate method (computer science)method for creating the objects, which subclass (computer science)subclasses can then override to specify the Subtypederived type of product that will be created. The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.StructureUML class diagram A sample UML class diagram for the Factory Method design pattern. In the above Unified Modeling LanguageUML class diagram, the Creator class that requires a Product object doesn't instantiate the Product1 class directly. Instead, the Creator refers to a separate factoryMethod() to create a product object, which makes the Creator independent of which concrete class is instantiated. Subclasses of Creator can redefine which class to instantiate. In this example, the Creator1 subclass implements the abstract factoryMethod() by instantiating the Product1 class. Example A maze game may be played in two modes, one with regular rooms that are only connected with adjacent rooms, and one with magic rooms that allow players to be transported at random. Structure Room is the base class for a final product (MagicRoom or OrdinaryRoom). MazeGame declares the abstract factory method to produce such a base product. MagicRoom and OrdinaryRoom are subclasses of the base product implementing the final product. MagicMazeGame and OrdinaryMazeGame are subclasses of MazeGame implementing the factory method producing the final products. Thus factory methods decouple callers (MazeGame) from the implementation of the concrete classes. This makes the "new" Operator redundant, allows adherence to the Open/closed principle and makes the final product more flexible in the of change. Example implementations C Sharp (programming language)C# //Empty vocabulary of actual object public interface IPerson { string GetName(); } public class Villager : IPerson { public string GetName() { return "Village Person"; } } public class CityPerson : IPerson { public string GetName() { return "City Person"; } } public enum PersonType { Rural, Urban } ///

/// Implementation of Factory - Used to create objects /// public class Factory { public IPerson GetPerson(PersonType type) { switch (type) { case PersonType.Rural: return new Villager(); case PersonType.Urban: return new CityPerson(); default: throw new NotSupportedException(); } } } In the above code you can see the creation of one interface called IPerson and two implementations called Villager and CityPerson. Based on the type passed into the Factory object, we are returning the original concrete object as the interface IPerson. A factory method is just an addition to Factory class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass decide which class is instantiated. public interface IProduct { string GetName(); string SetPrice(double price); } public class Phone : IProduct { private double _price; public string GetName() { return "Apple TouchPad"; } public string SetPrice(double price) { this._price = price; return "success"; } } /* Almost same as Factory, just an additional exposure to do something with the created method */ public abstract class ProductAbstractFactory { protected abstract IProduct MakeProduct(); public IProduct GetObject() // Implementation of Factory Method. { return this.MakeProduct(); } } public class PhoneConcreteFactory : ProductAbstractFactory { protected override IProduct MakeProduct() { IProduct product = new Phone(); //Do something with the object after you get the object. product.SetPrice(20.30); return product; } } You can see we have used MakeProduct in concreteFactory. As a result, Factory method pattern 22

you can easily call MakeProduct() from it to get the IProduct. You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface. Java (programming language)Java This Java (programming language)Java example is similar to one in the book Design Patterns.The MazeGame uses Rooms but it puts the responsibility of creating Rooms to its subclasses which create the concrete classes. The regular game mode could use this template method: public abstract class Room { abstract void connect(Room room); } public class MagicRoom extends Room { public void connect(Room room) {} } public class OrdinaryRoom extends Room { public void connect(Room room) {} } public abstract class MazeGame { private final List rooms = new ArrayList<>(); public MazeGame() { Room room1 = makeRoom(); Room room2 = makeRoom(); room1.connect(room2); rooms.add(room1); rooms.add(room2); } abstract protected Room makeRoom(); } In the above snippet, the MazeGame constructor is a Template method patterntemplate method that makes some common logic. It refers to the makeRoom factory method that encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, it suffices to override the makeRoom method: public class MagicMazeGame extends MazeGame { @Override protected Room makeRoom() { return new MagicRoom(); } } public class OrdinaryMazeGame extends MazeGame { @Override protected Room makeRoom() { return new OrdinaryRoom(); } } MazeGame ordinaryGame = new OrdinaryMazeGame(); MazeGame magicGame = new MagicMazeGame(); PHP Another example in PHP follows, this time using interface implementations as opposed to subclassing (however the same can be achieved through subclassing). It is important to note that the factory method can also be defined as public and called directly by the client code (in contrast with the Java example above). /* Factory and car interfaces */ interface CarFactory { public function makeCar() : Car; } interface Car { public function getType() : string; } /* Concrete implementations of the factory and car */ class SedanFactory implements CarFactory { public function makeCar() : Car { return new Sedan(); } } class Sedan implements Car { public function getType() : string { return 'Sedan'; } } /* Client */ $factory = new SedanFactory(); $car = $factory->makeCar(); print $car->getType(); Python (programming language)Python Same as Java example. from abc import ABC, abstractmethod class MazeGame(ABC): def __init__(self) -> None: self.rooms = [] self._prepare_rooms() def _prepare_rooms(self) -> None: room1 = self.make_room() room2 = self.make_room() room1.connect(room2) self.rooms.append(room1) self.rooms.append(room2) def play(self) -> None: print('Playing using "{}"'.format(self.rooms[0])) @abstractmethod def make_room(self): raise NotImplementedError("You should implement this!") class MagicMazeGame(MazeGame): def make_room(self): return MagicRoom() class OrdinaryMazeGame(MazeGame): def make_room(self): return OrdinaryRoom() class Room(ABC): def __init__(self) -> None: self.connected_rooms = [] def connect(self, room) -> None: self.connected_rooms.append(room) class MagicRoom(Room): def __str__(self): return "Magic room" class OrdinaryRoom(Room): def __str__(self): return "Ordinary room" ordinaryGame = OrdinaryMazeGame() ordinaryGame.play() magicGame = MagicMazeGame() magicGame.play() Uses In ADO.NET, IDbCommand.CreateParameter is an example of the use of factory method to connect parallel class hierarchies. In (toolkit)Qt, QMainWindow::createPopupMenu is a factory method declared in a framework that can be overridden in application code. In Java (programming language)Java, several factories are used in the javax.xml.parsers package. e.g. javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory. In the HTML5 Document Object ModelDOM application programming interfaceAPI, the Document interface contains a createElement factory method for creating specific elements of the HTMLElement interface. ReferencesMartin Fowler (software engineer)Martin Fowler; Kent BeckKent Beck; John Brant (author)John Brant; William OpdykeWilliam Opdyke; Don Roberts (author)Don Roberts (June 1999). Refactoring: Improving the Design of Existing Code. Addison-Wesley. ISBN (identifier)ISBN 0-201-48567-2.Erich GammaGamma, Erich; Richard HelmHelm, Richard; Johnson, Ralph; Vlissides, John (1994). Design PatternsDesign Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN (identifier)ISBN 0-201-63361-2. Cox, Brad J. (1986). Object-oriented programmingObject-oriented programming: an evolutionary approach. Addison-Wesley. ISBN Factory method pattern 23

(identifier)ISBN 978-0-201-10393-9. Cohen, Tal; Gil, Joseph (2007). "Better Construction with Factories" (PDF). Journal of Object Technology. . 6 (6): 103. doi (identifier)doi: 10.5381/jot.2007.6.6.a3. Retrieved 2007-03-12.External linksclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Factory method examples Factory Design Pattern Implementation in Java Factory method in UML and in LePUS3 (a Design Description Language) Consider static factory methods by Joshua Bloch

Lazy initialization

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of that refers specifically to the instantiation of objects or other resources. This is typically accomplished by augmenting an accessor method (or property getter) to check whether a private member, acting as a , has already been initialized. If it has, it is returned straight away. If not, a new instance is created, placed into the member variable, and returned to the caller just-in-time for its first use. If objects have properties that are rarely used, this can improve startup speed. Mean average program performance may be slightly worse in terms of memory (for the condition variables) and execution cycles (to check them), but the impact of object instantiation is spread in time ("amortized") rather than concentrated in the startup phase of a system, and thus median response times can be greatly improved. In multithreaded code, access to lazy-initialized objects/state must be synchronized to guard against race conditions.

The "lazy factory" In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas: • Using a factory method to create instances of a class (factory method pattern) • Storing the instances in a map, and returning the same instance to each request for an instance with same parameters (multiton pattern) • Using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern)

Examples

ActionScript 3 The following is an example of a class with lazy initialization implemented in ActionScript:

package examples.lazyinstantiation { public class Fruit { private var _typeName:String; private static var instancesByTypeName:Dictionary = new Lazy initialization 24

Dictionary();

public function Fruit(typeName:String):void { this._typeName = typeName; }

public function get typeName():String { return _typeName; }

public static function getFruitByTypeName(typeName:String):Fruit { return instancesByTypeName[typeName] ||= new Fruit(typeName); }

public static function printCurrentTypes():void { for each (var fruit:Fruit in instancesByTypeName) { // iterates through each value trace(fruit.typeName); } } } }

Basic Usage:

package { import examples.lazyinstantiation;

public class Main { public function Main():void { Fruit.getFruitByTypeName("Banana"); Fruit.printCurrentTypes();

Fruit.getFruitByTypeName("Apple"); Fruit.printCurrentTypes();

Fruit.getFruitByTypeName("Banana"); Fruit.printCurrentTypes(); Lazy initialization 25

} } }

C In C, lazy evaluation would normally be implemented inside a single function, or a single source file, using static variables. In a function:

#include #include #include #include

struct fruit { char *name; struct fruit *next; int number; /* Other members */ };

struct fruit *get_fruit(char *name) { static struct fruit *fruit_list; static int seq; struct fruit *f; for (f = fruit_list; f; f = f->next) if (0 == strcmp(name, f->name)) return f; if (!(f = malloc(sizeof(struct fruit)))) return NULL; if (!(f->name = strdup(name))) { free(f); return NULL; } f->number = ++seq; f->next = fruit_list; fruit_list = f; return f; }

/* Example code */

int main(int argc, char *argv[]) { int i; struct fruit *f; if (argc < 2) { fprintf(stderr, "Usage: fruits fruit-name [...]\n"); Lazy initialization 26

exit(1); } for (i = 1; i < argc; i++) { if ((f = get_fruit(argv[i]))) { printf("Fruit %s: number %d\n", argv[i], f->number); } } return 0; }

Using a single source file instead allows the state to be shared between multiple functions, while still hiding it from non-related functions. fruit.h:

#ifndef _FRUIT_INCLUDED_ #define _FRUIT_INCLUDED_

struct fruit { char *name; struct fruit *next; int number; /* Other members */ };

struct fruit *get_fruit(char *name); void print_fruit_list(FILE *file);

#endif /* _FRUIT_INCLUDED_ */

fruit.c:

#include #include #include #include #include "fruit.h"

static struct fruit *fruit_list; static int seq;

struct fruit *get_fruit(char *name) { struct fruit *f; for (f = fruit_list; f; f = f->next) if (0 == strcmp(name, f->name)) return f; if (!(f = malloc(sizeof(struct fruit)))) return NULL; if (!(f->name = strdup(name))) { free(f); Lazy initialization 27

return NULL; } f->number = ++seq; f->next = fruit_list; fruit_list = f; return f; }

void print_fruit_list(FILE *file) { struct fruit *f; for (f = fruit_list; f; f = f->next) fprintf(file, "%4d %s\n", f->number, f->name); }

main.c:

#include #include #include "fruit.h"

int main(int argc, char *argv[]) { int i; struct fruit *f; if (argc < 2) { fprintf(stderr, "Usage: fruits fruit-name [...]\n"); exit(1); } for (i = 1; i < argc; i++) { if ((f = get_fruit(argv[i]))) { printf("Fruit %s: number %d\n", argv[i], f->number); } } printf("The following fruits have been generated:\n"); print_fruit_list(stdout); return 0; }

C# In .NET Framework 4.0 Microsoft has included a Lazy class that can be used to do . Below is some dummy code that does lazy loading of Class Fruit

var lazyFruit = new Lazy(); Fruit fruit = lazyFruit.Value;

Here is a dummy example in C#. The Fruit class itself doesn't do anything here, The class variable _typesDictionary is a Dictionary/Map used to store Fruit instances by typeName. Lazy initialization 28

using System; using System.Collections; using System.Collections.Generic;

public class Fruit { private string _typeName; private static IDictionary _typesDictionary = new Dictionary();

private Fruit(String typeName) { this._typeName = typeName; }

public static Fruit GetFruitByTypeName(string type) { Fruit fruit;

if (!_typesDictionary.TryGetValue(type, out fruit)) { // Lazy initialization fruit = new Fruit(type);

_typesDictionary.Add(type, fruit); } return fruit; }

public static void ShowAll() { if (_typesDictionary.Count > 0) { Console.WriteLine("Number of instances made = {0}", _typesDictionary.Count);

foreach (KeyValuePair kvp in _typesDictionary) { Console.WriteLine(kvp.Key); }

Console.WriteLine(); } }

public Fruit() { // required so the sample compiles Lazy initialization 29

} }

class Program { static void Main(string[] args) { Fruit.GetFruitByTypeName("Banana"); Fruit.ShowAll();

Fruit.GetFruitByTypeName("Apple"); Fruit.ShowAll();

// returns pre-existing instance from first // time Fruit with "Banana" was created Fruit.GetFruitByTypeName("Banana"); Fruit.ShowAll();

Console.ReadLine(); } }

A fairly straightforward 'fill-in-the-blanks' example of a Lazy Initialization design pattern, except that this uses an enumeration for the type

namespace DesignPatterns.LazyInitialization { public class LazyFactoryObject { //internal collection of items //IDictionaery makes sure they are unique private IDictionary _LazyObjectList = new Dictionary();

//enum for passing name of size required //avoids passing strings and is part of LazyObject ahead public enum LazyObjectSize { None, Small, Big, Bigger, Huge }

//standard type of object that will be constructed public struct LazyObject { Lazy initialization 30

public LazyObjectSize Size; public IList Result; }

//takes size and create 'expensive' list private IList Result(LazyObjectSize size) { IList result = null;

switch (size) { case LazyObjectSize.Small: result = CreateSomeExpensiveList(1, 100); break; case LazyObjectSize.Big: result = CreateSomeExpensiveList(1, 1000); break; case LazyObjectSize.Bigger: result = CreateSomeExpensiveList(1, 10000); break; case LazyObjectSize.Huge: result = CreateSomeExpensiveList(1, 100000); break; case LazyObjectSize.None: result = null; break; default: result = null; break; }

return result; }

//not an expensive item to create, but you get the point //delays creation of some expensive object until needed private IList CreateSomeExpensiveList(int start, int end) { IList result = new List();

for (int counter = 0; counter < (end - start); counter++) { result.Add(start + counter); }

return result; } Lazy initialization 31

public LazyFactoryObject() { //empty constructor }

public LazyObject GetLazyFactoryObject(LazyObjectSize size) { //yes, i know it is illiterate and inaccurate LazyObject noGoodSomeOne;

//retrieves LazyObjectSize from list via out, else creates one and adds it to list if (!_LazyObjectList.TryGetValue(size, out noGoodSomeOne)) { noGoodSomeOne = new LazyObject(); noGoodSomeOne.Size= size; noGoodSomeOne.Result = this.Result(size);

_LazyObjectList.Add(size, noGoodSomeOne); }

return noGoodSomeOne; } } }

C++ Here is an example in C++.

#include #include #include

class Fruit { public: static Fruit* GetFruit(const std::string& type); static void PrintCurrentTypes();

private: // Note: constructor private forcing one to use static |GetFruit|. Fruit(const std::string& type) : type_(type) {}

static std::map types;

std::string type_; }; Lazy initialization 32

// static std::map Fruit::types;

// Lazy Factory method, gets the |Fruit| instance associated with a certain // |type|. Creates new ones as needed. Fruit* Fruit::GetFruit(const std::string& type) { auto [it, inserted] = types.emplace(type, nullptr); if (inserted) { it->second = new Fruit(type); } return it->second; }

// For example purposes to see pattern in action. void Fruit::PrintCurrentTypes() { std::cout << "Number of instances made = " << types.size() << std::endl; for (const auto& [type, fruit] : types) { std::cout << type << std::endl; } std::cout << std::endl; }

int main() { Fruit::GetFruit("Banana"); Fruit::PrintCurrentTypes();

Fruit::GetFruit("Apple"); Fruit::PrintCurrentTypes();

// Returns pre-existing instance from first time |Fruit| with "Banana" was // created. Fruit::GetFruit("Banana"); Fruit::PrintCurrentTypes(); }

// OUTPUT: // // Number of instances made = 1 // Banana // // Number of instances made = 2 // Apple // Banana // // Number of instances made = 2 Lazy initialization 33

// Apple // Banana //

Crystal class Fruit private getter type : String @@types = {} of String => Fruit

def initialize(@type) end

def self.get_fruit_by_type(type : String) @@types[type] ||= Fruit.new(type) end

def self.show_all puts "Number of instances made: #{@@types.size}" @@types.each do |type, fruit| puts "#{type}" end puts end

def self.size @@types.size end end

Fruit.get_fruit_by_type("Banana") Fruit.show_all

Fruit.get_fruit_by_type("Apple") Fruit.show_all

Fruit.get_fruit_by_type("Banana") Fruit.show_all

Output:

Number of instances made: 1 Banana

Number of instances made: 2 Banana Apple

Number of instances made: 2 Lazy initialization 34

Banana Apple

Haxe Here is an example in

class Fruit { private static var _instances = new Map();

public var name(default, null):String;

public function new(name:String) { this.name = name; }

public static function getFruitByName(name:String):Fruit { if (!_instances.exists(name)) { _instances.set(name, new Fruit(name)); } return _instances.get(name); }

public static function printAllTypes() { trace([for(key in _instances.keys()) key]); } }

Usage

class Test { public static function main () { var banana = Fruit.getFruitByName("Banana"); var apple = Fruit.getFruitByName("Apple"); var banana2 = Fruit.getFruitByName("Banana");

trace(banana == banana2); // true. same banana

Fruit.printAllTypes(); // ["Banana","Apple"] } }

Java Here is an example in Java.

import java.util.HashMap; import java.util.Map; import java.util.Map.Entry;

public class Program { Lazy initialization 35

/** * @param args */ public static void main(String[] args) { Fruit.getFruitByTypeName(FruitType.banana); Fruit.showAll(); Fruit.getFruitByTypeName(FruitType.apple); Fruit.showAll(); Fruit.getFruitByTypeName(FruitType.banana); Fruit.showAll(); } }

enum FruitType { none, apple, banana, }

class Fruit {

private static Map types = new HashMap<>();

/** * Using a private constructor to force the use of the factory method. * @param type */ private Fruit(FruitType type) { }

/** * Lazy Factory method, gets the Fruit instance associated with a certain * type. Instantiates new ones as needed. * @param type Any allowed fruit type, e.g. APPLE * @return The Fruit instance associated with that type. */ public static Fruit getFruitByTypeName(FruitType type) { Fruit fruit; // This has concurrency issues. Here the read to types is not synchronized, // so types.put and types.containsKey might be called at the same time. // Don't be surprised if the data is corrupted. if (!types.containsKey(type)) { Lazy initialization 36

// Lazy initialisation fruit = new Fruit(type); types.put(type, fruit); } else { // OK, it's available currently fruit = types.get(type); }

return fruit; }

/** * Lazy Factory method, gets the Fruit instance associated with a certain * type. Instantiates new ones as needed. Uses double-checked locking * pattern for using in highly concurrent environments. * @param type Any allowed fruit type, e.g. APPLE * @return The Fruit instance associated with that type. */ public static Fruit getFruitByTypeNameHighConcurrentVersion(FruitType type) { if (!types.containsKey(type)) { synchronized (types) { // Check again, after having acquired the lock to make sure // the instance was not created meanwhile by another thread if (!types.containsKey(type)) { // Lazy initialisation types.put(type, new Fruit(type)); } } }

return types.get(type); }

/** * Displays all entered fruits. */ public static void showAll() { if (types.size() > 0) {

System.out.println("Number of instances made = " + types.size());

Lazy initialization 37

for (Entry entry : types.entrySet()) { String fruit = entry.getKey().toString(); fruit = Character.toUpperCase(fruit.charAt(0)) + fruit.substring(1); System.out.println(fruit); }

System.out.println(); } } }

Output

Number of instances made = 1 Banana

Number of instances made = 2 Banana Apple

Number of instances made = 2 Banana Apple

JavaScript Here is an example in JavaScript.

var Fruit = (function() { var types = {}; function Fruit() {};

// count own properties in object function count(obj) { return Object.keys(obj).length; }

var _static = { getFruit: function(type) { if (typeof types[type] == 'undefined') { types[type] = new Fruit; } return types[type]; }, printCurrentTypes: function () { console.log('Number of instances made: ' + count(types)); for (var type in types) { console.log(type); } Lazy initialization 38

} };

return _static;

})();

Fruit.getFruit('Apple'); Fruit.printCurrentTypes(); Fruit.getFruit('Banana'); Fruit.printCurrentTypes(); Fruit.getFruit('Apple'); Fruit.printCurrentTypes();

Output

Number of instances made: 1 Apple

Number of instances made: 2 Apple Banana

Number of instances made: 2 Apple Banana

PHP Here is an example of lazy initialization in PHP 7.4:

class Fruit { private string $type; private static array $types = array();

private function __construct(string $type) { $this->type = $type; }

public static function getFruit(string $type) { // Lazy initialization takes place here if (!isset(self::types[$type])) { self::types[$type] = new Fruit($type); } Lazy initialization 39

return self::types[$type]; }

public static function printCurrentTypes(): void { 'Number of instances made: ' . count(self::types) . "\n"; foreach (array_keys(self::types) as $key) { echo "$key\n"; } echo "\n"; } }

Fruit::getFruit('Apple'); Fruit::printCurrentTypes();

Fruit::getFruit('Banana'); Fruit::printCurrentTypes();

Fruit::getFruit('Apple'); Fruit::printCurrentTypes();

/* OUTPUT:

Number of instances made: 1 Apple

Number of instances made: 2 Apple Banana

Number of instances made: 2 Apple Banana */

Python Here is an example in Python.

class Fruit(object): def __init__(self, item: str) -> None: self.item = item

class Fruits(object): def __init__(self) -> None: self.items = {} Lazy initialization 40

def get_fruit(self, item: str) -> Fruit: if item not in self.items: self.items[item] = Fruit(item)

return self.items[item]

if __name__ == '__main__': fruits = Fruits() print(fruits.get_fruit('Apple')) print(fruits.get_fruit('Lime'))

Ruby Here is an example in Ruby, of lazily initializing an authentication token from a remote service like Google. The way that @auth_token is cached is also an example of .

require 'net/http' class Blogger def auth_token @auth_token ||= (res = Net::HTTP.post_form(uri, params)) && get_token_from_http_response(res) end

# get_token_from_http_response, uri and params are defined later in the class end

b = Blogger.new b.instance_variable_get(:@auth_token) # returns nil b.auth_token # returns token b.instance_variable_get(:@auth_token) # returns token

Scala Scala has built-in support for lazy variable initiation.

scala> val x = { println("Hello"); 99 } Hello x: Int = 99 scala> lazy val y = { println("Hello!!"); 31 } y: Int = scala> y Hello!! res2: Int = 31 scala> y res3: Int = 31 Lazy initialization 41

Smalltalk Here is an example in Smalltalk, of a typical accessor method to return the value of a variable using lazy initialization.

height ^height ifNil: [height := 2.0].

The 'non-lazy' alternative is to use an initialization method that is run when the object is created and then use a simpler accessor method to fetch the value.

initialize height := 2.0

height ^height

Note that lazy initialization can also be used in non-object-oriented languages.

Theoretical computer science In the field of theoretical computer science, lazy initialization (also called a lazy array) is a technique to design data structures that can work with memory that does not need to be initialized. Specifically, assume that we have access to a table T of n uninitialized memory cells (numbered from 1 to n), and want to assign m cells of this array, e.g., we want to assign T[k ] := v for pairs (k , v ), ..., (k , v ) with all k being different. The lazy initialization i i 1 1 m m i technique allows us to do this in just O(m) operations, rather than spending O(m+n) operations to first initialize all array cells. The technique is simply to allocate a table V storing the pairs (k , v ) in some arbitrary order, and to write i i for each i in the cell T[k ] the position in V where key k is stored, leaving the other cells of T uninitialized. This can i i be used to handle queries in the following fashion: when we look up cell T[k] for some k, we can check if k is in the range {1, ..., m}: if it is not, then T[k] is uninitialized. Otherwise, we check V[T[k]], and verify that the first component of this pair is equal to k. If it is not, then T[k] is uninitialized (and just happened by accident to fall in the range {1, ..., m}). Otherwise, we know that T[k] is indeed one of the initialized cells, and the corresponding value is the second component of the pair.

References

External links

• Article " Java Tip 67: Lazy instantiation (https:/ / www. infoworld. com/ article/ 2077568/

java-tip-67--lazy-instantiation. html) - Balancing performance and resource usage" by Philip Bishop and Nigel Warren

• Java code examples (http:/ / javapractices. com/ Topic34. cjp)

• Use Lazy Initialization to Conserve Resources (https:/ / web. archive. org/ web/ 20191202055631/ http:/ / devx.

com/ tips/ Tip/ 18007)

• Description from the Portland Pattern Repository (https:/ / wiki. c2. com/ ?LazyInitialization)

• Lazy Initialization of Services (https:/ / web. archive. org/ web/ 20060911223210/ http:/ /

weblogs. java. net/ blog/ binod/ archive/ 2005/ 09/ lazy_initializa. html)

• Lazy Inheritance in JavaScript (https:/ / sourceforge. net/ projects/ jsiner/ )

• Lazy Inheritance in C# (https:/ / kaliko. com/ blog/ lazy-loading-in-c-net/ ) Multiton pattern 42 Multiton pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

UML diagram of the multitonUML diagram of the multiton In software engineering, the multiton pattern is a design pattern (computer science)design pattern which generalizes the . Whereas the singleton pattern singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multiple instances, which it manages through the use of a associative arraymap.Rather than having a single instance per application (e.g. the java.lang.Runtime object in the Java (programming language)Java programming language) the multiton pattern instead ensures a single instance per key.Most people and textbooks consider this a singleton pattern. For example, multiton does not explicitly appear in the highly regarded object-oriented programming textbook Design Patterns (book)Design Patterns (it appears as a more flexible approach named registry of singletons).Description While it may appear that the multiton is a with synchronized access there are two important distinctions. First, the multiton does not allow clients to add mappings. Secondly, the multiton never returns a null or empty reference; instead, it creates and stores a multiton instance on the first request with the associated key. Subsequent requests with the same key return the original instance. A hash table is merely an implementation detail and not the only possible approach. The pattern simplifies retrieval of shared objects in an application. Since the object pool is created only once, being a member associated with the class (instead of the instance), the multiton retains its flat behavior rather than evolving into a Tree ()tree structure. The multiton is unique in that it provides centralized access to a single directory (i.e. all keys are in the same namespace, per se) of multitons, where each multiton instance in the pool may exist having its own state. In this manner, the pattern advocates indexed storage of essential objects for the system (such as would be provided by an LDAP system, for example). However, a multiton is limited to wide use by a single system rather than a myriad of distributed systems.Drawbacks This pattern, like the Singleton pattern, makes far more difficult, as it introduces global variablesglobal state into an application. With garbage collected languages it may become a source of memory leaks as it introduces global strong references to the objects. Implementations In Java, the multiton pattern can be implemented using an , with the values of the type corresponding to the instances. In the case of an enumerated type with a single value, this gives the singleton pattern. In C#, we can also use enums, as the following example shows: using System.Collections.Generic; public enum MultitonType { Zero, One, Two }; public class Multiton { private static readonly IDictionary instances = new Dictionary(); private int number; private Multiton(int number) { this.number = number; } public static Multiton getInstance(MultitonType type) { // Lazy init (not thread safe as written) // Recommend using Double Check Locking if needing if (!instances.ContainsKey(type)) { instances.Add(type, new Multiton((int)type)); } return instances[type]; } public override string toString() { return "My number is " + number.ToString(); } // Sample usage public static void main(string[] args) { Multiton m0 = Multiton.GetInstance(MultitonType.Zero); Multiton m1 = Multiton.GetInstance(MultitonType.One); Multiton m2 = Multiton.GetInstance(MultitonType.Two); System.Console.WriteLine(m0); System.Console.WriteLine(m1); System.Console.WriteLine(m2); } } ReferencesExternal links Multiton implementation in Ruby language Multiton usage in PureMVC Framework for ActionScript 3 Article with a C# Multiton implementation, example of use, and discussion of memory issues Multiton pattern 43

Object pool pattern

The is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object to the pool rather than destroying it; this can be done manually or automatically. Object pools are primarily used for performance: in some circumstances, object pools significantly improve performance. Object pools complicate , as objects obtained from and returned to a pool are not actually created or destroyed at this time, and thus require care in implementation.

Description When it is necessary to work with a large number of objects that are particularly expensive to instantiate and each object is only needed for a short period of time, the performance of an entire application may be adversely affected. An object pool design pattern may be deemed desirable in cases such as these. The object pool design pattern creates a set of objects that may be reused. When a new object is needed, it is requested from the pool. If a previously prepared object is available it is returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a new item is created and returned. When the object has been used and is no longer needed, it is returned to the pool, allowing it to be used again in the future without repeating the computationally expensive instantiation process. It is important to note that once an object has been used and returned, existing references will become invalid. In some object pools the resources are limited so a maximum number of objects is specified. If this number is reached and a new item is requested, an exception may be thrown, or the thread will be blocked until an object is released back into the pool. The object pool design pattern is used in several places in the standard classes of the .NET Framework. One example is the .NET Framework Data Provider for SQL Server. As SQL Server database connections can be slow to create, a pool of connections is maintained. Closing a connection does not actually relinquish the link to SQL Server. Instead, the connection is held in a pool from which it can be retrieved when requesting a new connection. This substantially increases the speed of making connections.

Benefits Object pooling can offer a significant performance boost in situations where the cost of initializing a class instance is high and the rate of instantiation and destruction of a class is high – in this case objects can frequently be reused, and each reuse saves a significant amount of time. Object pooling requires resources – memory and possibly other resources, such as network sockets, and thus it is preferable that the number of instances in use at any one time is low, but this is not required. The pooled object is obtained in predictable time when creation of the new objects (especially over network) may take variable time. These benefits are mostly true for objects that are expensive with respect to time, such as database connections, socket connections, threads and large graphic objects like fonts or bitmaps. In other situations, simple object pooling (that hold no external resources, but only occupy memory) may not be efficient and could decrease performance. In case of simple memory pooling, the slab allocation technique is more suited, as the only goal is to minimize the cost of memory allocation and deallocation Object pool pattern 44

by reducing fragmentation.

Implementation Object pools can be implemented in an automated fashion in languages like C++ via smart pointers. In the constructor of the smart pointer, an object can be requested from the pool, and in the destructor of the smart pointer, the object can be released back to the pool. In garbage-collected languages, where there are no destructors (which are guaranteed to be called as part of a stack unwind), object pools must be implemented manually, by explicitly requesting an object from the factory and returning the object by calling a dispose method (as in the ). Using a to do this is not a good idea, as there are usually no guarantees on when (or if) the finalizer will be run. Instead, "try ... finally" should be used to ensure that getting and releasing the object is exception-neutral. Manual object pools are simple to implement, but harder to use, as they require of pool objects.

Handling of empty pools Object pools employ one of three strategies to handle a request when there are no spare objects in the pool. 1. Fail to provide an object (and return an error to the client). 2. Allocate a new object, thus increasing the size of the pool. Pools that do this usually allow you to set the high water mark (the maximum number of objects ever used). 3. In a multithreaded environment, a pool may block the client until another thread returns an object to the pool.

Pitfalls When writing an object pool, the programmer has to be careful to make sure the state of the objects returned to the pool is reset back to a sensible state for the next use of the object. If this is not observed, the object will often be in some state that was unexpected by the client program and may cause the client program to fail. The pool is responsible for resetting the objects, not the clients. Object pools full of objects with dangerously stale state are sometimes called object cesspools and regarded as an anti-pattern. The presence of stale state is not always an issue; it becomes dangerous when the presence of stale state causes the object to behave differently. For example, an object that represents authentication details may break if the "successfully authenticated" flag is not reset before it is passed out, since it will indicate that a user is correctly authenticated (possibly as someone else) when they haven't yet attempted to authenticate. However, it will work just fine if you fail to reset some value only used for debugging, such as the identity of the last authentication server used. Inadequate resetting of objects may also cause an information leak. If an object contains confidential data (e.g. a user's credit card numbers) that isn't cleared before the object is passed to a new client, a malicious or buggy client may disclose the data to an unauthorized party. If the pool is used by multiple threads, it may need the means to prevent parallel threads from grabbing and trying to reuse the same object in parallel. This is not necessary if the pooled objects are immutable or otherwise thread-safe.

Criticism Some publications do not recommend using object pooling with certain languages, such as Java, especially for objects that only use memory and hold no external resources. Opponents usually say that object allocation is relatively fast in modern languages with garbage collectors; while the operator new needs only ten instructions, the classic new - delete pair found in pooling designs requires hundreds of them as it does more complex work. Also, most garbage collectors scan "live" object references, and not the memory that these objects use for their Object pool pattern 45

content. This means that any number of "dead" objects without references can be discarded with little cost. In contrast, keeping a large number of "live" but unused objects increases the duration of garbage collection.

Examples

Go The following Go code initializes a resource pool of a specified size (concurrent initialization) to avoid resource race issues through channels, and in the case of an empty pool, sets timeout processing to prevent clients from waiting too long.

// package pool package pool

import ( "errors" "log" "math/rand" "sync" "time" )

const getResMaxTime = 3 * time.Second

var ( ErrPoolNotExist = errors.New("pool not exist") ErrGetResTimeout = errors.New("get resource time out") )

//Resource type Resource struct { resId int }

//NewResource Simulate slow resource initialization creation // (e.g., TCP connection, SSL symmetric key acquisition, auth authentication are time-consuming) func NewResource(id int) *Resource { time.Sleep(500 * time.Millisecond) return &Resource{resId: id} }

//Do Simulation resources are time consuming and random consumption is 0~400ms func (r *Resource) Do(workId int) { time.Sleep(time.Duration(rand.Intn(5)) * 100 * time.Millisecond) log.Printf("using resource #%d finished work %d finish\n", r.resId, workId) Object pool pattern 46

}

//Pool based on Go channel implementation, to avoid resource race state problem type Pool chan *Resource

//New a resource pool of the specified size // Resources are created concurrently to save resource initialization time func New(size int) Pool { p := make(Pool, size) wg := new(sync.WaitGroup) wg.Add(size) for i := 0; i < size; i++ { go func(resId int) { p <- NewResource(resId) wg.Done() }(i) } wg.Wait() return p }

//GetResource based on channel, resource race state is avoided and resource acquisition timeout is set for empty pool func (p Pool) GetResource() (r *Resource, err error) { select { case r := <-p: return r, nil case <-time.After(getResMaxTime): return nil, ErrGetResTimeout } }

//GiveBackResource returns resources to the resource pool func (p Pool) GiveBackResource(r *Resource) error { if p == nil { return ErrPoolNotExist } p <- r return nil }

// package main package main

import ( Object pool pattern 47

"github.com/tkstorm/go-design/creational/object-pool/pool" "log" "sync" )

func main() { // Initialize a pool of five resources, // which can be adjusted to 1 or 10 to see the difference size := 5 p := pool.New(size)

// Invokes a resource to do the id job doWork := func(workId int, wg *sync.WaitGroup) { defer wg.Done() // Get the resource from the resource pool res, err := p.GetResource() if err != nil { log.Println(err) return } // Resources to return defer p.GiveBackResource(res) // Use resources to handle work res.Do(workId) }

// Simulate 100 concurrent processes to get resources from the asset pool num := 100 wg := new(sync.WaitGroup) wg.Add(num) for i := 0; i < num; i++ { go doWork(i, wg) } wg.Wait() }

C# In the .NET Base Class Library there are a few objects that implement this pattern. System.Threading.ThreadPool is configured to have a predefined number of threads to allocate. When the threads are returned, they are available for another computation. Thus, one can use threads without paying the cost of creation and disposal of threads. The following shows the basic code of the object pool design pattern implemented using C#. For brevity the properties of the classes are declared using C# 3.0 automatically implemented property syntax. These could be replaced with full property definitions for earlier versions of the language. Pool is shown as a static class, as it's unusual for multiple pools to be required. However, it's equally acceptable to use instance classes for object pools. Object pool pattern 48

namespace DesignPattern.Objectpool { // The PooledObject class is the type that is expensive or slow to instantiate, // or that has limited availability, so is to be held in the object pool. public class PooledObject { DateTime _createdAt = DateTime.Now;

public DateTime CreatedAt { get { return _createdAt; } }

public string TempData { get; set; } }

// The Pool class is the most important class in the object pool design pattern. It controls access to the // pooled objects, maintaining a list of available objects and a collection of objects that have already been // requested from the pool and are still in use. The pool also ensures that objects that have been released // are returned to a suitable state, ready for the next time they are requested. public static class Pool { private static List _available = new List(); private static List _inUse = new List();

public static PooledObject GetObject() { lock(_available) { if (_available.Count != 0) { PooledObject po = _available[0]; _inUse.Add(po); _available.RemoveAt(0); return po; } else { PooledObject po = new PooledObject(); _inUse.Add(po); return po; Object pool pattern 49

} } }

public static void ReleaseObject(PooledObject po) { CleanUp(po);

lock (_available) { _available.Add(po); _inUse.Remove(po); } }

private static void CleanUp(PooledObject po) { po.TempData = null; } } }

In the code above, the PooledObject includes two properties. One holds the time at which the object was first created. The other holds a string that can be modified by the client but that is reset when the PooledObject is released back to the pool. This shows the clean-up process on release of an object that ensures it is in a valid state before it can be requested from the pool again.

Java Java supports thread pooling via java.util.concurrent.ExecutorService and other related classes. The executor service has a certain number of "basic" threads that are never discarded. If all threads are busy, the service allocates the allowed number of extra threads that are later discarded if not used for the certain expiration time. If no more threads are allowed, the tasks can be placed in the queue. Finally, if this queue may get too long, it can be configured to suspend the requesting thread.

public class PooledObject { public String temp1; public String temp2; public String temp3;

public String getTemp1() { return temp1; } public void setTemp1(String temp1) { this.temp1 = temp1; } public String getTemp2() { return temp2; } Object pool pattern 50

public void setTemp2(String temp2) { this.temp2 = temp2; } public String getTemp3() { return temp3; } public void setTemp3(String temp3) { this.temp3 = temp3; }}

public class PooledObjectPool { private static long expTime = 6000;//6 seconds public static HashMap available = new HashMap(); public static HashMap inUse = new HashMap();

public synchronized static PooledObject getObject() { long now = System.currentTimeMillis(); if (!available.isEmpty()) { for (Map.Entry entry : available.entrySet()) { if (now - entry.getValue() > expTime) { //object has expired popElement(available); } else { PooledObject po = popElement(available, entry.getKey()); push(inUse, po, now); return po; } } }

// either no PooledObject is available or each has expired, so return a new one return createPooledObject(now); }

private synchronized static PooledObject createPooledObject(long now) { PooledObject po = new PooledObject(); push(inUse, po, now); return po; }

private synchronized static void push(HashMap map, PooledObject po, long now) { map.put(po, now); } Object pool pattern 51

public static void releaseObject(PooledObject po) { cleanUp(po); available.put(po, System.currentTimeMillis()); inUse.remove(po); }

private static PooledObject popElement(HashMap map) { Map.Entry entry = map.entrySet().().next(); PooledObject key= entry.getKey(); //Long value=entry.getValue(); map.remove(entry.getKey()); return key; }

private static PooledObject popElement(HashMap map, PooledObject key) { map.remove(key); return key; }

public static void cleanUp(PooledObject po) { po.setTemp1(null); po.setTemp2(null); po.setTemp3(null); } }

Notes

References

• Kircher, Michael; Prashant Jain (2002-07-04). "Pooling Pattern" (http:/ / www. kircher-schwanninger. de/

michael/ publications/ Pooling. pdf) (PDF). EuroPLoP 2002. Germany. Retrieved 2007-06-09. • Goldshtein, Sasha; Zurbalev, Dima; Flatow, Ido (2012). Pro .NET Performance: Optimize Your C# Applications

(http:/ / www. apress. com/ 9781430244585). Apress. ISBN 978-1-4302-4458-5. Object pool pattern 52

External links

• OODesign article (http:/ / www. oodesign. com/ object-pool-pattern. html)

• Improving Performance with Object Pooling (Microsoft Developer Network ) (http:/ / msdn2. microsoft. com/

en-us/ library/ ms682822. aspx)

• Developer.com article (http:/ / www. developer. com/ tech/ article. / 626171/ Pattern-Summaries-Object-Pool. htm)

• Portland Pattern Repository entry (http:/ / c2. com/ cgi-bin/ wiki?ObjectPoolPattern)

• Apache Commons Pool: A mini-framework to correctly implement object pooling in Java (http:/ / commons.

apache. org/ pool/ )

• Game Programming Patterns: Object Pool (http:/ / gameprogrammingpatterns. com/ object-pool. html)

Prototype pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The is a creational design pattern (computer science)design pattern in . It is used when the type of object (computer science)objects to create is determined by a prototypeprototypical instance (computer science)instance, which is cloned to produce new objects. This pattern is used to: avoid subclass (computer science)subclasses of an object creator in the client application, like the factory method pattern does. avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new (C++)new' keyword) when it is prohibitively expensive for a given application. To implement the pattern, declare an abstract base class that specifies a virtual method#Abstract classes and pure virtual functionspure virtual clone() method. Any class that needs a "polymorphism (computer science)polymorphic constructor (computer science)constructor" capability derives itself from the abstract base class, and implements the clone() operation.The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.The mitosismitotic division of a cell — resulting in two identical cells — is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.Duell, Michael (July 1997). "Non-Software Examples of Design Patterns". Object Magazine. 7 (5): 54. ISSN (identifier)ISSN 1055-3614.Overview The Prototype design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. The Prototype design pattern solves problems like: How can objects be created so that which objects to create can be specified at run-time? How can dynamically loaded classes be instantiated? Creating objects directly within the class that requires (uses) the objects is inflexible because it commits the class to particular objects at compile-time and makes it impossible to specify which objects to create at run-time. The Prototype design pattern describes how to solve such problems: Define a Prototype object that returns a copy of itself. Create new objects by copying a Prototype object. This enables configuration of a class with different Prototype objects, which are copied Prototype pattern 53

to create new objects, and even more, Prototype objects can be added and removed at run-time. See also the UML class and sequence diagram below. StructureUML class and sequence diagram A sample UML class and sequence diagram for the Prototype design pattern.In the above Unified Modeling LanguageUML Class diagramclass diagram, the Client class that requires a Product object doesn't instantiate the Product1 class directly. Instead, the Client refers to the Prototype interface for cloning an object. The Product1 class implements the Prototype interface by creating a copy of itself. The Unified Modeling LanguageUML Sequence diagramsequence diagram shows the run-time interactions: The Client object calls clone() on a prototype:Product1 object, which creates and returns a copy of itself (a product:Product1 object). UML class diagram Unified Modeling LanguageUML class diagram describing the prototype design patternRules of thumb Sometimes creational patterns overlap — there are cases when either prototype or abstract factory patternabstract factory would be appropriate. At other times they complement each other: abstract factory might store a set of prototypes from which to clone and return product objects (Gang of Four (software)GoF, p126). Abstract factory, builder patternbuilder, and prototype can use singleton patternsingleton in their implementations. (GoF, p81, 134). Abstract factory classes are often implemented with factory methods (creation through inheritance (computer science)inheritance), but they can be implemented using prototype (creation through delegation (programming)delegation). (GoF, p95) Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward abstract factory, prototype, or builder (more flexible, more complex) as the designer discovers where more flexibility is needed. (GoF, p136) Prototype does not require subclassing, but it does require an "initialize" operation. Factory method requires subclassing, but does not require initialization. (GoF, p116) Designs that make heavy use of the composite patterncomposite and decorator patterndecorator patterns often can benefit from Prototype as well. (GoF, p126) The rule of thumb could be that you would need to clone() an Object when you want to create another Object at runtime that is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have instantiated the class by using new instead, you would get an Object with all attributes as their initial values. For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object that holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone() instead of new. Code samples Pseudocode Let's write an occurrence browser class for a text. This class lists the occurrences of a word in a text. Such an object is expensive to create as the locations of the occurrences need an expensive process to find. So, to duplicate such an object, we use the prototype pattern: class WordOccurrences is field occurrences is The list of the index of each occurrence of the word in the text. constructor WordOccurrences(text, word) is input: the text in which the occurrences have to be found input: the word that should appear in the text Empty the occurrences list for each textIndex in text isMatching := true for each wordIndex in word if the current word character does not match the current text character then isMatching := false if isMatching is true then Add the current textIndex into the occurrences list method getOneOccurrenceIndex(n) is input: a number to point on the nth occurrence. output: the index of the nth occurrence. Return the nth item of the occurrences field if any. method clone() is output: a WordOccurrences object containing the same data. Call clone() on the super class. On the returned object, set the occurrences field with the value of the local occurrences field. Return the cloned object. text := "The prototype pattern is a creational design pattern in software development first described in design patterns, the book." word := "pattern"d searchEngine := new WordOccurrences(text, word) anotherSearchEngine := searchEngine.clone() (the search algorithm is not optimized; it is a basic algorithm to illustrate the pattern implementation)C# example This pattern creates the concrete type of object using its prototype. In other words, while creating the object of Prototype object, the class actually creates a clone of it and returns it as prototype. You can see here, we have used MemberwiseClone method to clone the prototype when required. public abstract class Prototype { // normal implementation public abstract Prototype Clone(); } public class ConcretePrototype1 : Prototype { public override Prototype Clone() { return (Prototype)this.MemberwiseClone(); // Clones the concrete class. } } public class ConcretePrototype2 : Prototype { public override Prototype Clone() { return (Prototype)this.MemberwiseClone(); // Clones the concrete class. } } C++ example Discussion of the design pattern Prototype pattern 54

along with a complete illustrative example implementation using polymorphic class design are provided in the C++ Annotations. Java example This pattern creates the kind of object using its prototype. In other words, while creating the object of Prototype object, the class creates a clone of it and returns it as prototype. The clone method has been used to clone the prototype when required. // Prototype pattern public abstract class Prototype implements Cloneable { public Prototype clone() throws CloneNotSupportedException{ return (Prototype) super.clone(); } } public class ConcretePrototype1 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype1)super.clone(); } } public class ConcretePrototype2 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype2)super.clone(); } } PHP example // The Prototype pattern in PHP is done with the use of built-in PHP function __clone() abstract class Prototype { public string $a; public string $b; public function displayCONS(): void { echo "CONS: {$this->a}\n"; echo "CONS: {$this->b}\n"; } public function displayCLON(): void { echo "CLON: {$this->a}\n"; echo "CLON: {$this->b}\n"; } abstract function __clone(); } class ConcretePrototype1 extends Prototype { public function __construct() { $this->a = "A1"; $this->b = "B1"; $this->displayCONS(); } function __clone() { $this->displayCLON(); } } class ConcretePrototype2 extends Prototype { public function __construct() { $this->a = "A2"; $this->b = "B2"; $this->displayCONS(); } function __clone() { $this->a = $this->a ."-C"; $this->b = $this->b ."-C"; $this->displayCLON(); } } $cP1 = new ConcretePrototype1(); $cP2 = new ConcretePrototype2(); $cP2C = clone $cP2; // RESULT: #quanton81 // CONS: A1 // CONS: B1 // CONS: A2 // CONS: B2 // CLON: A2-C // CLON: B2-C Python example Python version 3.8+ from abc import ABC, abstractmethod from typing import AnyStr class A(ABC): """Abstract class""" @abstractmethod def whois(self) -> AnyStr: pass class Concrete(A): """Concrete class""" def whois(self) -> AnyStr: """Overriding of whois() method of the abstract class A""" return f"Concrete: {self}" c = Concrete() print(c.whois()) Output: Concrete: <__main__.Concrete object at 0x1023bafd0> References Sources Erich GammaGamma, Erich; Helm, Richard; Ralph Johnson (computer scientist)Johnson, Ralph; John VlissidesVlissides, John (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN (identifier)ISBN 0-201-63361-2. Resource Acquisition Is Initialization 55 Resource Acquisition Is Initialization

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

Resource acquisition is initialization (RAII) is a programming idiom used in several Object-oriented programmingobject-oriented, Statically-typed programming languagestatically-typed programming languages to describe a particular language behavior. In RAII, holding a resource is a , and is tied to object lifetime: Resource allocation (computer)resource allocation (or acquisition) is done during object creation (specifically initialization), by the Constructor (object-oriented programming)constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the Destructor (computer programming)destructor. In other words, resource acquisition must succeed for initialization to succeed. Thus the resource is guaranteed to be held between when initialization finishes and finalization starts (holding the resources is a class invariant), and to be held only when the object is alive. Thus if there are no object leaks, there are no resource leaks.RAII is associated most prominently with C++ where it originated, but also D (programming language)D, Ada (programming language)Ada, Vala (programming language)Vala, and Rust (programming language)Rust. The technique was developed for Exception safetyexception-safe resource management (computing)resource management in C++#CITEREFStroustrup1994Stroustrup 1994, 16.5 Resource Management, pp. 388–89. during 1984–89, primarily by Bjarne Stroustrup and Andrew Koenig (programmer)Andrew Koenig,#CITEREFStroustrup1994Stroustrup 1994, 16.1 : Introduction, pp. 383–84. and the term itself was coined by Stroustrup.#CITEREFStroustrup1994Stroustrup 1994, p. 389. I called this technique "resource acquisition is initialization." RAII is generally pronounced as an initialism, sometimes pronounced as "R, A, double I".Other names for this idiom include Constructor Acquires, Destructor Releases (CADRe) and one particular style of use is called Scope-based Resource Management (SBRM). This latter term is for the special case of automatic variables. RAII ties resources to object lifetime, which may not coincide with entry and exit of a scope. (Notably variables allocated on the free store have lifetimes unrelated to any given scope.) However, using RAII for automatic variables (SBRM) is the most common use case.C++11 example The following C++11 example demonstrates usage of RAII for file access and mutex locking: #include #include #include #include #include void WriteToFile(const std::string& message) { // |mutex| is to protect access to |file| (which is shared across threads). static std::mutex mutex; // Lock |mutex| before accessing |file|. std::lock_guard lock(mutex); // Try to open file. std::ofstream file("example.txt"); if (!file.is_open()) { throw std::runtime_error("unable to open file"); } // Write |message| to |file|. file << message << std::endl; // |file| will be closed first when leaving scope (regardless of exception) // mutex will be unlocked second (from lock destructor) when leaving scope // (regardless of exception). } This code is exception-safe because C++ guarantees that all stack objects are destroyed at the end of the enclosing scope, known as stack unwinding. The destructors of both the lock and file objects are therefore guaranteed to be called when returning from the function, whether an exception has been thrown or not.Local variables allow easy management of multiple resources within a single function: they are destroyed in the reverse order of their construction, and an object is destroyed only if fully constructed—that is, if no exception propagates from its constructor.Using RAII greatly simplifies resource management, reduces overall code size and helps ensure program correctness. RAII is therefore highly recommended in C++, and most of the C++ standard library follows the idiom.Benefits The advantages of RAII as a resource management technique are that it provides encapsulation, exception safety (for stack resources), and locality (it allows acquisition and release logic to Resource Acquisition Is Initialization 56

be written next to each other). Encapsulation is provided because resource management logic is defined once in the class, not at each call site. Exception safety is provided for stack resources (resources that are released in the same scope as they are acquired) by tying the resource to the lifetime of a stack variable (a local variable declared in a given scope): if an Exception handlingexception is thrown, and proper exception handling is in place, the only code that will be executed when exiting the current Scope (computer science)scope are the destructors of objects declared in that scope. Finally, locality of definition is provided by writing the constructor and destructor definitions next to each other in the class definition. Resource management therefore needs to be tied to the lifespan of suitable objects in order to gain automatic allocation and reclamation. Resources are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors. Comparing RAII with the finally construct used in Java, Stroustrup wrote that “In realistic systems, there are far more resource acquisitions than kinds of resources, so the 'resource acquisition is initialization' technique leads to less code than use of a 'finally' construct.”Typical usesThe RAII design is often used for controlling mutex locks in thread (computing)#Multithreadingmulti-threaded applications. In that use, the object releases the lock when destroyed. Without RAII in this scenario the potential for deadlock would be high and the logic to lock the mutex would be far from the logic to unlock it. With RAII, the code that locks the mutex essentially includes the logic that the lock will be released when execution leaves the scope of the RAII object. Another typical example is interacting with files: We could have an object that represents a file that is open for writing, wherein the file is opened in the constructor and closed when execution leaves the object's scope. In both cases, RAII ensures only that the resource in question is released appropriately; care must still be taken to maintain exception safety. If the code modifying the data structure or file is not exception-safe, the mutex could be unlocked or the file closed with the data structure or file corrupted. Ownership of dynamically allocated objects (memory allocated with new in C++) can also be controlled with RAII, such that the object is released when the RAII (stack-based) object is destroyed. For this purpose, the C++11 standard library defines the smart pointer classes Smart pointer#unique_ptrstd::unique_ptr for single-owned objects and Smart_pointer#shared_ptr_and_weak_ptrstd::shared_ptr for objects with shared ownership. Similar classes are also available through auto ptrstd::auto_ptr in C++98, and boost::shared_ptr in the Boost (C++ libraries)Boost libraries. Clang and GCC "cleanup" extension for C Both Clang and GNU Collection implement a non-standard extension to the C (programming language)C language to support RAII: the "cleanup" variable attribute. The following macro (computer science)macro annotates a variable with a given destructor function that it will call when the variable goes out of scope: static inline void fclosep(FILE **fp) { if (*fp) fclose(*fp); } #define _cleanup_fclose_ __attribute__((cleanup(fclosep))) This macro can then be used as follows: void example_usage() { _cleanup_fclose_ FILE *logfile = fopen("logfile.txt", "w+"); fputs("hello logfile!", logfile); } In this example, the compiler arranges for the fclosep function to be called on logfile before example_usage returns.Limitations RAII only works for resources acquired and released (directly or indirectly) by stack-allocated objects, where there is a well-defined static object lifetime. Heap-allocated objects which themselves acquire and release resources are common in many languages, including C++. RAII depends on heap-based objects to be implicitly or explicitly deleted along all possible execution paths, in order to trigger its resource-releasing destructor (or equivalent).:8:27 This can be achieved by using smart pointers to manage all heap objects, with weak-pointers for cyclically referenced objects. In C++, stack unwinding is only guaranteed to occur if the exception is caught somewhere. This is because "If no matching handler is found in a program, the function terminate() is called; whether or not the stack is unwound before this call to terminate() is implementation-defined (15.5.1)." (C++03 standard, §15.3/9). This behavior is usually acceptable, since the operating system releases remaining resources like memory, files, sockets, etc. at program termination. , Python (programming language)Python (in the CPython implementation), and PHP manage object lifetime by reference counting, which makes it possible to use RAII. Objects that are no longer referenced are immediately destroyed or finalized and released, so a Destructor (computer programming)destructor or finalizer can release the resource at that time. However, it is not always idiomatic in such languages, and is specifically discouraged in Python (in favor of context managers and from the weakref Resource Acquisition Is Initialization 57

package).However, object lifetimes are not necessarily bound to any scope, and objects may be destroyed non-deterministically or not at all. This makes it possible to accidentally leak resources that should have been released at the end of some scope. Objects stored in a (notably a global variable) may not be finalized when the program terminates, so their resources are not released; CPython makes no guarantee of finalizing such objects, for instance. Further, objects with circular references will not be collected by a simple reference counter, and will live indeterminately long; even if collected (by more sophisticated garbage collection), destruction time and destruction order will be non-deterministic. In CPython there is a cycle detector which detects cycles and finalizes the objects in the cycle, though prior to CPython 3.4, cycles are not collected if any object in the cycle has a finalizer.References Further reading Bjarne StroustrupStroustrup, Bjarne (1994). The Design and Evolution of C++The Design and Evolution of C++. Addison-Wesley. Bibcode (identifier)Bibcode: 1994dec..book.....S. ISBN (identifier)ISBN 978-0-201-54330-8. External linksclass=noviewerThe Wikibook C++ Programming has a page on the topic of: RAIIclass=noviewerThe Wikibook More C++ Idioms has a page on the topic of: Resource Acquisition Is Initialization Sample Chapter: " Gotcha #67: Failure to Employ Resource Acquisition Is Initialization" by Stephen C. Dewhurst Interview: " A Conversation with Bjarne Stroustrup" by Bill Venners Article: " The Law of The Big Two" by Bjorn Karlsson and Matthew Wilson Article: " Implementing the 'Resource Acquisition is Initialization' Idiom" by Danny Kalev Article: " RAII, Dynamic Objects, and Factories in C++" by Roland Pibinger RAII in : " One-liner RAII in Delphi" by Barry Kelly

Singleton pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

Class diagram exemplifying the singleton pattern. In software engineering, the singleton pattern is a software design pattern that restricts the Instantiation (computer science)instantiation of a Class (computer programming)class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the Singleton (mathematics)mathematical concept of a singleton.Critics consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global variablesglobal state into an application.Scott Densmore. Why singletons are evil, May 2004Steve Yegge. Singletons considered stupid, September 2004 Clean Code Talks - Global State and SingletonsMaximiliano Contieri. Singleton Pattern: The Root of all Evil, Jun 2020Overview The singleton design pattern is one of the twenty-three well-known Design Patterns"Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. The singleton design pattern solves problems like: How can it be ensured that a class has only one instance? How can the sole instance of a class be accessed easily? How can a class control its instantiation? How can the number of instances of a class be restricted? How can a global variable be accessed? The singleton design pattern describes how to solve such problems: Hide the constructor of the class. Define a public static operation (getInstance()) that returns the sole Singleton pattern 58

instance of the class. The key idea in this pattern is to make the class itself responsible for controlling its instantiation (that it is instantiated only once). The hidden constructor (declared private) ensures that the class can never be instantiated from outside the class. The public static operation can be accessed easily by using the class name and operation name (Singleton.getInstance()). Common uses The Abstract factory patternabstract factory, factory method, Builder patternbuilder, and Prototype patternprototype patterns can use singletons in their implementation. Facade patternFacade objects are often singletons because only one facade object is required. State patternState objects are often singletons. Singletons are often preferred to global variables because: They do not pollute the global namespace (or, in languages with nested , their containing namespace) with unnecessary variables. They permit Lazy evaluationlazy allocation and initialization, whereas global variables in many languages will always consume resources. Implementation An implementation of the singleton pattern must: ensure that only one instance of the singleton class ever exists; and provide Global scopeglobal access to that instance.Typically, this is done by: declaring all Constructor (object-oriented programming)constructors of the class to be Private memberprivate; and providing a static method that returns a Reference (computer science)reference to the instance. The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java (programming language)Java. public final class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } C# implementation public sealed class Singleton { private static readonly Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton Instance { get { return INSTANCE; } } } In C# you can also use static classes to create singletons, where the class itself is the singleton. public static class Singleton { private static readonly MyOtherClass INSTANCE = new MyOtherClass(); public static MyOtherClass Instance { get { return INSTANCE; } } } Lazy initialization A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple Thread (computing)threads simultaneously, measures may need to be taken to prevent Race conditionrace conditions that could result in the creation of multiple instances of the class. The following is a Thread safetythread-safe sample implementation, using lazy initialization with double-checked locking, written in Java.In Java, to avoid the synchronization overhead while keeping lazy initialization with thread safety, the preferred approach is to use the initialization-on-demand holder idiom. public final class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } Dart implementation class Singleton { static Singleton _instance; static Singleton get instance => _instance ?? Singleton._(); Singleton._() => _instance = this; } PHP implementation class Singleton { private static $instance = null; private function __construct(){} public static function getInstance(): self { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } } Java Implementation public class Coin { private static final int ADD_MORE_COIN = 10; private int coin; private static Coin instance = new Coin(); // Eagerly Loading of singleton instance private Coin(){ // private to prevent anyone else from instantiating } public static Coin getInstance(){ return instance; } public int getCoin(){ return coin; } public void addMoreCoin(){ coin += ADD_MORE_COIN; } public void deductCoin(){ coin--; } } Kotlin Implementation Kotlin object keyword declares a singleton class object Coin{ private var coin: Int = 0 fun getCoin():Int{ return coin } fun addCoin(){ coin += 10 } fun deductCoin(){ coin-- } } Delphi and Free Pascal implementation GetInstance is thread safe implementation of Singleton. unit SingletonPattern; interface type TTest = class sealed strict private FCreationTime: TDateTime; public constructor Create; property CreationTime: TDateTime read FCreationTime; end; function GetInstance: TTest; implementation uses SysUtils , SyncObjs ; var FCriticalSection: TCriticalSection; FInstance: TTest; function GetInstance: TTest; begin FCriticalSection.Acquire; try if not Assigned(FInstance) then FInstance := TTest.Create; Result := FInstance; finally FCriticalSection.Release; end; end; constructor TTest.Create; begin inherited Create; FCreationTime := Now; end; initialization FCriticalSection := TCriticalSection.Create; finalization FreeAndNil(FCriticalSection); end. Usage: procedure TForm3.btnCreateInstanceClick(Sender: TObject); var i: integer; begin for i := 0 to 5 do ShowMessage(DateTimeToStr(GetInstance.CreationTime)); end; Notes References Singleton pattern 59

External links class=noviewerThe Wikibook Computer Science/Design Patterns has a page on the topic of: Singleton implementations in various languagesclass=noviewerWikimedia Commons has media related to Singleton pattern. Complete article " Java Singleton Pattern Explained" Four different ways to implement singleton in Java " Ways to implement singleton in Java" Book extract: Implementing the Singleton Pattern in C# by Jon Skeet Singleton at Microsoft patterns & practices Developer Center IBM article " Double-checked locking and the Singleton pattern" by Peter Haggar IBM article " Use your singletons wisely" by J. B. RainsbergerGeary, David (April 25, 2003). "How to navigate the deceptively simple Singleton pattern". Java Design Patterns. JavaWorld. Retrieved 2020-07-21. Google article " Why Singletons Are Controversial" Google Singleton Detector (analyzes Java bytecode to detect singletons)

Adapter pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the is a software design pattern (also known as wrapper, an alternative naming shared with the ) that allows the interface (computer science)interface of an existing class (computer science)class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.An example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed. Overview The adapter design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.The adapter design pattern solves problems like: How can a class be reused that does not have an interface that a client requires? How can classes that have incompatible interfaces work together? How can an alternative interface be provided for a class? Often an (already existing) class can't be reused only because its interface doesn't conform to the interface clients require. The adapter design pattern describes how to solve such problems: Define a separate adapter class that converts the (incompatible) interface of a class (adaptee) into another interface (target) clients require. Work through an adapter to work with (reuse) classes that do not have the required interface. The key idea in this pattern is to work through a separate adapter that adapts the interface of an (already existing) class without changing it. Clients don't know whether they work with a target class directly or through an adapter with a class that does not have the target interface. See also the UML class diagram below. Definition An adapter allows two incompatible interfaces to work together. This is the real-world definition for an adapter. Interfaces may be incompatible, but the inner functionality should suit the need. The adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients. Usage An adapter can be used when the wrapper must respect a particular interface and must support Polymorphism (computer science)polymorphic behavior. Alternatively, a decorator patterndecorator makes it possible to add or alter behavior of an interface at run-time, and a facade patternfacade is used when an easier or simpler interface to an underlying object is desired. Pattern Intent Adapter or wrapper Converts one interface to another so that it matches what the client is expecting Decorator patternDecorator Dynamically adds responsibility to Adapter pattern 60

the interface by wrapping the original code Delegation patternDelegation Support "composition over inheritance" Facade patternFacade Provides a simplified interface StructureUML class diagram A sample UML class diagram for the adapter design pattern.In the above Unified Modeling LanguageUML class diagram, the client class that requires a target interface cannot reuse the adaptee class directly because its interface doesn't conform to the target interface. Instead, the client works through an adapter class that implements the target interface in terms of adaptee: The object adapter way implements the target interface by delegating to an adaptee object at run-time (adaptee.specificOperation()). The class adapter way implements the target interface by inheriting from an adaptee class at compile-time (specificOperation()). Object adapter pattern In this adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped object (computing)object. The object adapter pattern expressed in Unified Modeling LanguageUMLThe object adapter pattern expressed in Lepus3LePUS3Class adapter pattern This adapter pattern uses multiple Subtypingpolymorphic interfaces implementing or inheriting both the interface that is expected and the interface that is pre-existing. It is typical for the expected interface to be created as a pure Interface (Java)interface class, especially in programming languagelanguages such as Java (programming language)Java (before JDK 1.8) that do not support multiple inheritance of classes.The class adapter pattern expressed in Unified Modeling LanguageUML.The class adapter pattern expressed in Lepus3LePUS3A further form of runtime adapter patternMotivation from compile time solution It is desired for classA to supply classB with some data, let us suppose some String data. A compile time solution is: classB.setStringData(classA.getStringData()); However, suppose that the format of the string data must be varied. A compile time solution is to use inheritance: public class Format1ClassA extends ClassA { @Override public String getStringData() { return format(toString()); } } and perhaps create the correctly "formatting" object at runtime by means of the factory pattern. Run-time adapter solution A solution using "adapters" proceeds as follows: (i) Define an intermediary "provider" interface, and write an implementation of that provider interface that wraps the source of the data, ClassA in this example, and outputs the data formatted as appropriate: public interface StringProvider { public String getStringData(); } public class ClassAFormat1 implements StringProvider { private ClassA classA = null; public ClassAFormat1(final ClassA a) { classA = a; } public String getStringData() { return format(classA.getStringData()); } private String format(final String sourceValue) { // Manipulate the source string into a format required // by the object needing the source object's data return sourceValue.trim(); } } (ii) Write an adapter class that returns the specific implementation of the provider: public class ClassAFormat1Adapter extends Adapter { public Object adapt(final Object anObject) { return new ClassAFormat1((ClassA) anObject); } } (iii) Register the adapter with a global registry, so that the adapter can be looked up at runtime: AdapterFactory.getInstance().registerAdapter(ClassA.class, ClassAFormat1Adapter.class, "format1"); (iv) In code, when wishing to transfer data from ClassA to ClassB, write: Adapter adapter = AdapterFactory.getInstance() .getAdapterFromTo(ClassA.class, StringProvider.class, "format1"); StringProvider provider = (StringProvider) adapter.adapt(classA); String string = provider.getStringData(); classB.setStringData(string); or more concisely: classB.setStringData( ((StringProvider) AdapterFactory.getInstance() .getAdapterFromTo(ClassA.class, StringProvider.class, "format1") .adapt(classA)) .getStringData()); (v) The advantage can be seen in that, if it is desired to transfer the data in a second format, then look up the different adapter/provider: Adapter adapter = AdapterFactory.getInstance() .getAdapterFromTo(ClassA.class, StringProvider.class, "format2"); (vi) And if it is desired to output the data from ClassA as, say, image data in Class C: Adapter adapter = AdapterFactory.getInstance() .getAdapterFromTo(ClassA.class, ImageProvider.class, "format2"); ImageProvider provider = (ImageProvider) adapter.adapt(classA); classC.setImage(provider.getImage()); (vii) In this way, the use of adapters and providers allows multiple "views" by ClassB and ClassC into ClassA without having to alter the class hierarchy. In general, it permits a mechanism for arbitrary data flows between objects that can be retrofitted to an existing object hierarchy. Implementation of the adapter pattern When implementing the adapter pattern, for clarity one can apply the class name [ClassName]To[Interface]Adapter to the provider implementation, for example DAOToProviderAdapter. It should have a constructor method with an adaptee class variable as a parameter. This parameter will be passed to an instance member of [ClassName]To[Interface]Adapter. When the clientMethod is Adapter pattern 61

called, it will have access to the adaptee instance that allows for accessing the required data of the adaptee and performing operations on that data that generates the desired output. Java interface LightningPhone { void recharge(); void useLightning(); } interface MicroUsbPhone { void recharge(); void useMicroUsb(); } class Iphone implements LightningPhone { private boolean connector; @Override public void useLightning() { connector = true; System.out.println("Lightning connected"); } @Override public void recharge() { if (connector) { System.out.println("Recharge started"); System.out.println("Recharge finished"); } else { System.out.println("Connect Lightning first"); } } } class Android implements MicroUsbPhone { private boolean connector; @Override public void useMicroUsb() { connector = true; System.out.println("MicroUsb connected"); } @Override public void recharge() { if (connector) { System.out.println("Recharge started"); System.out.println("Recharge finished"); } else { System.out.println("Connect MicroUsb first"); } } } /* exposing the target interface while wrapping source object */ class LightningToMicroUsbAdapter implements MicroUsbPhone { private final LightningPhone lightningPhone; public LightningToMicroUsbAdapter(LightningPhone lightningPhone) { this.lightningPhone = lightningPhone; } @Override public void useMicroUsb() { System.out.println("MicroUsb connected"); lightningPhone.useLightning(); } @Override public void recharge() { lightningPhone.recharge(); } } public class AdapterDemo { static void rechargeMicroUsbPhone(MicroUsbPhone phone) { phone.useMicroUsb(); phone.recharge(); } static void rechargeLightningPhone(LightningPhone phone) { phone.useLightning(); phone.recharge(); } public static void main(String[] args) { Android android = new Android(); Iphone iPhone = new Iphone(); System.out.println("Recharging android with MicroUsb"); rechargeMicroUsbPhone(android); System.out.println("Recharging iPhone with Lightning"); rechargeLightningPhone(iPhone); System.out.println("Recharging iPhone with MicroUsb"); rechargeMicroUsbPhone(new LightningToMicroUsbAdapter (iPhone)); } } Output Recharging android with MicroUsb MicroUsb connected Recharge started Recharge finished Recharging iPhone with Lightning Lightning connected Recharge started Recharge finished Recharging iPhone with MicroUsb MicroUsb connected Lightning connected Recharge started Recharge finished Python """ Adapter pattern example. """ from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." RECHARGE = ["Recharge started.", "Recharge finished."] POWER_ADAPTERS = {"Android": "MicroUSB", "iPhone": "Lightning"} CONNECTED = "{} connected." CONNECT_FIRST = "Connect {} first." class RechargeTemplate: __metaclass__ = ABCMeta @abstractmethod def recharge(self): raise NotImplementedError(NOT_IMPLEMENTED) class FormatIPhone(RechargeTemplate): @abstractmethod def use_lightning(self): raise NotImplementedError(NOT_IMPLEMENTED) class FormatAndroid(RechargeTemplate): @abstractmethod def use_micro_usb(self): raise NotImplementedError(NOT_IMPLEMENTED) class IPhone(FormatIPhone): __name__ = "iPhone" def __init__(self): self.connector = False def use_lightning(self): self.connector = True print(CONNECTED.format(POWER_ADAPTERS[self.__name__])) def recharge(self): if self.connector: for state in RECHARGE: print(state) else: print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__name__])) class Android(FormatAndroid): __name__ = "Android" def __init__(self): self.connector = False def use_micro_usb(self): self.connector = True print(CONNECTED.format(POWER_ADAPTERS[self.__name__])) def recharge(self): if self.connector: for state in RECHARGE: print(state) else: print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__name__])) class IPhoneAdapter(FormatAndroid): def __init__(self, mobile): self.mobile = mobile def recharge(self): self.mobile.recharge() def use_micro_usb(self): print(CONNECTED.format(POWER_ADAPTERS["Android"])) self.mobile.use_lightning() class AndroidRecharger(object): def __init__(self): self.phone = Android() self.phone.use_micro_usb() self.phone.recharge() class IPhoneMicroUSBRecharger(object): def __init__(self): self.phone = IPhone() self.phone_adapter = IPhoneAdapter(self.phone) self.phone_adapter.use_micro_usb() self.phone_adapter.recharge() class IPhoneRecharger(object): def __init__(self): self.phone = IPhone() self.phone.use_lightning() self.phone.recharge() print("Recharging Android with MicroUSB recharger.") AndroidRecharger() print() print("Recharging iPhone with MicroUSB using adapter pattern.") IPhoneMicroUSBRecharger() print() Adapter pattern 62

print("Recharging iPhone with iPhone recharger.") IPhoneRecharger() References class=noviewerWikimedia Commons has media related to Adapter pattern.class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Adapter implementations in various languages

Bridge pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The is a software design patterndesign pattern used in software engineering that is meant to "decouple an Abstraction (computer science)abstraction from its implementation so that the two can vary independently", introduced by the Design PatternsGang of Four.Gamma, E, Helm, R, Johnson, R, Vlissides, J: Design Patterns, page 151. Addison-Wesley, 1995 The bridge uses encapsulation (computer science)encapsulation, Object composition#Aggregationaggregation, and can use inheritance (object-oriented programming)inheritance to separate responsibilities into different Class (computer science)classes.When a class varies often, the features of object-oriented programming become very useful because changes to a Computer programprogram's Source codecode can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class and what it does vary often. The class itself can be thought of as the abstraction and what the class can do as the implementation. The bridge pattern can also be thought of as two layers of abstraction.When there is only one fixed implementation, this pattern is known as the Pimpl idiom in the C++ world. The bridge pattern is often confused with the adapter pattern, and is often implemented using the Adapter_pattern#Object_adapter_patternobject adapter pattern, e.g. in the Java code below. Variant: The implementation can be decoupled even more by deferring the presence of the implementation to the point where the abstraction is utilized. Overview The Bridge design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Bridge design pattern solve? An abstraction and its implementation should be defined and extended independently from each other. A compile-time binding between an abstraction and its implementation should be avoided so that an implementation can be selected at run-time. When using subclassing, different subclasses implement an abstract class in different ways. But an implementation is bound to the abstraction at compile-time and cannot be changed at run-time. What solution does the Bridge design pattern describe? Separate an abstraction (Abstraction) from its implementation (Implementor) by putting them in separate class hierarchies. Implement the Abstraction in terms of (by delegating to) an Implementor object. This enables to configure an Abstraction with an Implementor object at run-time. See also the Unified Modeling Language class and sequence diagram below. StructureUML class and sequence diagram A sample UML class and sequence diagram for the Bridge design pattern. In the above Unified Modeling Language class diagram, an abstraction (Abstraction) is not implemented as usual in a single inheritance hierarchy. Instead, there is one hierarchy for an abstraction (Abstraction) and a separate hierarchy for its implementation (Implementor), which makes the two independent from each other. The Abstraction interface (operation()) is implemented in terms of (by delegating to) the Implementor interface (imp.operationImp()). The Unified Modeling LanguageUML sequence diagram shows the run-time Bridge pattern 63

interactions: The Abstraction1 object delegates implementation to the Implementor1 object (by calling operationImp() on Implementor1), which performs the operation and returns to Abstraction1. Class diagram Abstraction (abstract class) defines the abstract interface maintains the Implementor reference. RefinedAbstraction (normal class) extends the interface defined by Abstraction Implementor (interface) defines the interface for implementation classes ConcreteImplementor (normal class) implements the Implementor interface Bridge in Lepus3LePUS3 ( legend) Example C# Bridge pattern compose objects in tree structure. It decouples abstraction from implementation. Here abstraction represents the client from which the objects will be called. An example implemented in C# is given below // Helps in providing truly decoupled architecture public interface IBridge { void Function1(); void Function2(); } public class Bridge1 : IBridge { public void Function1() { Console.WriteLine("Bridge1.Function1"); } public void Function2() { Console.WriteLine("Bridge1.Function2"); } } public class Bridge2 : IBridge { public void Function1() { Console.WriteLine("Bridge2.Function1"); } public void Function2() { Console.WriteLine("Bridge2.Function2"); } } public interface IAbstractBridge { void CallMethod1(); void CallMethod2(); } public class AbstractBridge : IAbstractBridge { public IBridge bridge; public AbstractBridge(IBridge bridge) { this.bridge = bridge; } public void CallMethod1() { this.bridge.Function1(); } public void CallMethod2() { this.bridge.Function2(); } } The Bridge classes are the Implementation that uses the same interface-oriented architecture to create objects. On the other hand, the abstraction takes an instance of the implementation class and runs its method. Thus, they are completely decoupled from one another. Crystal abstract class DrawingAPI abstract def draw_circle(x : Float64, y : Float64, radius : Float64) end class DrawingAPI1 < DrawingAPI def draw_circle(x : Float, y : Float, radius : Float) "API1.circle at #{x}:#{y} - radius: #{radius}" end end class DrawingAPI2 < DrawingAPI def draw_circle(x : Float64, y : Float64, radius : Float64) "API2.circle at #{x}:#{y} - radius: #{radius}" end end abstract class Shape protected getter drawing_api : DrawingAPI def initialize(@drawing_api) end abstract def draw abstract def resize_by_percentage(percent : Float64) end class CircleShape < Shape getter x : Float64 getter y : Float64 getter radius : Float64 def initialize(@x, @y, @radius, drawing_api : DrawingAPI) super(drawing_api) end def draw @drawing_api.draw_circle(@x, @y, @radius) end def resize_by_percentage(percent : Float64) @radius *= (1 + percent/100) end end class BridgePattern def self.test shapes = [] of Shape shapes << CircleShape.new(1.0, 2.0, 3.0, DrawingAPI1.new) shapes << CircleShape.new(5.0, 7.0, 11.0, DrawingAPI2.new) shapes.each do |shape| shape.resize_by_percentage(2.5) puts shape.draw end end end BridgePattern.test Output API1.circle at 1.0:2.0 - radius: 3.075 API2.circle at 5.0:7.0 - radius: 11.275 C++ #include #include #include class DrawingAPI { public: virtual ~DrawingAPI() = default; virtual std::string DrawCircle(float x, float y, float radius) const = 0; }; class DrawingAPI01 : public DrawingAPI { public: std::string DrawCircle(float x, float y, float radius) const override { return "API01.circle at " + std::to_string(x) + ":" + std::to_string(y) + " - radius: " + std::to_string(radius); } }; class DrawingAPI02 : public DrawingAPI { public: std::string DrawCircle(float x, float y, float radius) const override { return "API02.circle at " + std::to_string(x) + ":" + std::to_string(y) + " - radius: " + std::to_string(radius); } }; class Shape { public: Shape(const DrawingAPI& drawing_api) : drawing_api_(drawing_api) {} virtual ~Shape() = default; virtual std::string Draw() const = 0; virtual float ResizeByPercentage(const float percent) = 0; protected: const DrawingAPI& drawing_api_; }; class CircleShape: public Shape { public: CircleShape(float x, float y, float radius, const DrawingAPI& drawing_api) : Shape(drawing_api), x_(x), y_(y), radius_(radius) {} std::string Draw() const override { return drawing_api_.DrawCircle(x_, y_, radius_); } float ResizeByPercentage(const float percent) override { return radius_ *= (1.0f + percent/100.0f); } private: float x_, y_, radius_; }; int main(int argc, char** argv) { std::vector shapes { CircleShape{1.0f, 2.0f, 3.0f, DrawingAPI01{}}, CircleShape{5.0f, 7.0f, 11.0f, DrawingAPI02{}} }; for (auto& shape: shapes) { shape.ResizeByPercentage(2.5); std::cout << shape.Draw() << std::endl; } return 0; } Output: API01.circle at 1.000000:2.000000 - radius: 3.075000 API02.circle at 5.000000:7.000000 - radius: 11.275000 Java The following Java (programming language)Java program defines a bank account that separates the account operations from the logging of these operations. // Logger has two implementations: info and warning @FunctionalInterface interface Logger { void log(String message); static Logger info() { return message -> System.out.println("info: " + message); } static Logger warning() { return message -> Bridge pattern 64

System.out.println("warning: " + message); } } abstract class AbstractAccount { private Logger logger = Logger.info(); public void setLogger(Logger logger) { this.logger = logger; } // the logging part is delegated to the Logger implementation protected void operate(String message, boolean result) { logger.log(message + " result " + result); } } class SimpleAccount extends AbstractAccount { private int balance; public SimpleAccount(int balance) { this.balance = balance; } public boolean isBalanceLow() { return balance < 50; } public void withdraw(int amount) { boolean shouldPerform = balance >= amount; if (shouldPerform) { balance -= amount; } operate("withdraw " + amount, shouldPerform); } } public class BridgeDemo { public static void main(String[] args) { SimpleAccount account = new SimpleAccount(100); account.withdraw(75); if (account.isBalanceLow()) { // you can also change the Logger implementation at runtime account.setLogger(Logger.warning()); } account.withdraw(10); account.withdraw(100); } } It will output: info: withdraw 75 result true warning: withdraw 10 result true warning: withdraw 100 result false PHP interface DrawingAPI { function drawCircle($x, $y, $radius); } class DrawingAPI1 implements DrawingAPI { public function drawCircle($x, $y, $radius) { echo "API1.circle at $x:$y radius $radius.\n"; } } class DrawingAPI2 implements DrawingAPI { public function drawCircle($x, $y, $radius) { echo "API2.circle at $x:$y radius $radius.\n"; } } abstract class Shape { protected $drawingAPI; public abstract function draw(); public abstract function resizeByPercentage($pct); protected function __construct(DrawingAPI $drawingAPI) { $this->drawingAPI = $drawingAPI; } } class CircleShape extends Shape { private $x; private $y; private $radius; public function __construct($x, $y, $radius, DrawingAPI $drawingAPI) { parent::__construct($drawingAPI); $this->x = $x; $this->y = $y; $this->radius = $radius; } public function draw() { $this->drawingAPI->drawCircle($this->x, $this->y, $this->radius); } public function resizeByPercentage($pct) { $this->radius *= $pct; } } class Tester { public static function main() { $shapes = array( new CircleShape(1, 3, 7, new DrawingAPI1()), new CircleShape(5, 7, 11, new DrawingAPI2()), ); foreach ($shapes as $shape) { $shape->resizeByPercentage(2.5); $shape->draw(); } } } Tester::main(); Output: API1.circle at 1:3 radius 17.5 API2.circle at 5:7 radius 27.5 Scala trait DrawingAPI { def drawCircle(x: Double, y: Double, radius: Double) } class DrawingAPI1 extends DrawingAPI { def drawCircle(x: Double, y: Double, radius: Double) = println(s"API #1 $x $y $radius") } class DrawingAPI2 extends DrawingAPI { def drawCircle(x: Double, y: Double, radius: Double) = println(s"API #2 $x $y $radius") } abstract class Shape(drawingAPI: DrawingAPI) { def draw() def resizePercentage(pct: Double) } class CircleShape(x: Double, y: Double, var radius: Double, drawingAPI: DrawingAPI) extends Shape(drawingAPI: DrawingAPI) { def draw() = drawingAPI.drawCircle(x, y, radius) def resizePercentage(pct: Double) { radius *= pct } } object BridgePattern { def main(args: Array[String]) { Seq ( new CircleShape(1, 3, 5, new DrawingAPI1), new CircleShape(4, 5, 6, new DrawingAPI2) ) foreach { x => x.resizePercentage(3) x.draw() } } } Python """ Bridge pattern example. """ from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." class DrawingAPI: __metaclass__ = ABCMeta @abstractmethod def draw_circle(self, x, y, radius): raise NotImplementedError(NOT_IMPLEMENTED) class DrawingAPI1(DrawingAPI): def draw_circle(self, x, y, radius): return "API1.circle at {0}:{1} - radius: {2}".format(x, y, radius) class DrawingAPI2(DrawingAPI): def draw_circle(self, x, y, radius): return "API2.circle at {0}:{1} - radius: {2}".format(x, y, radius) class DrawingAPI3(DrawingAPI): def draw_circle(self, x, y, radius): return "API3.circle at {0}:{1} - radius: {2}".format(x, y, radius) class Shape: __metaclass__ = ABCMeta drawing_api = None def __init__(self, drawing_api): self.drawing_api = drawing_api @abstractmethod def draw(self): raise NotImplementedError(NOT_IMPLEMENTED) @abstractmethod def resize_by_percentage(self, percent): raise NotImplementedError(NOT_IMPLEMENTED) class CircleShape(Shape): def __init__(self, x, y, radius, drawing_api): self.x = x self.y = y self.radius = radius super(CircleShape, self).__init__(drawing_api) def draw(self): return self.drawing_api.draw_circle( self.x, self.y, self.radius ) def resize_by_percentage(self, percent): self.radius *= (1 + percent/100) class BridgePattern(object): @staticmethod def test(): shapes = [ CircleShape(1.0, 2.0, 3.0, DrawingAPI1()), CircleShape(5.0, 7.0, 11.0, DrawingAPI2()), CircleShape(5.0, 4.0, 12.0, DrawingAPI3()) ] for shape in shapes: shape.resize_by_percentage(2.5) print(shape.draw()) BridgePattern.test() ReferencesExternal linksclass=noviewerThe Wikibook Computer Science/Design Patterns has a page on the topic of: Bridge pattern implementations in various languages Bridge in UML and in LePUS3 (a formal modelling language) C# Design Bridge pattern 65

Patterns: The Bridge Pattern. Sample Chapter. 2002-12-20. From: James W. Cooper (2003). C# Design Patterns: A Tutorial. Addison-Wesley. ISBN (identifier)ISBN 0-201-84453-2.

Composite pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the is a partitioning design pattern (computer science)design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.Overview The Composite design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Composite design pattern solve? A part-whole hierarchy should be represented so that clients can treat part and whole objects uniformly. A part-whole hierarchy should be represented as tree structure. When defining (1) Part objects and (2) Whole objects that act as containers for Part objects, clients must treat them separately, which complicates client code. What solution does the Composite design pattern describe? Define a unified Component interface for both part (Leaf) objects and whole (Composite) objects. Individual Leaf objects implement the Component interface directly, and Composite objects forward requests to their child components. This enables clients to work through the Component interface to treat Leaf and Composite objects uniformly: Leaf objects perform a request directly, and Composite objects forward the request to their child components recursively downwards the tree structure. This makes client classes easier to implement, change, test, and reuse. See also the UML class and object diagram below. Motivation When dealing with Tree-structured data, often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, more error prone. The solution is an interface that allows treating complex and primitive objects uniformly. In object-oriented programming, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality. This is known as a "has-a" relationship between objects. The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them. The operations you can perform on all the composite objects often have a least common denominator relationship. For example, if defining a system to portray grouped shapes on a screen, it would be useful to define resizing a group of shapes to have the same effect (in some sense) as resizing a single shape. When to use Composite should be used when clients ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous. StructureUML class and object diagram A sample UML class and object diagram for the Composite design pattern. In the above Unified Modeling LanguageUML class diagram, the Client class doesn't Composite pattern 66

refer to the Leaf and Composite classes directly (separately). Instead, the Client refers to the common Component interface and can treat Leaf and Composite uniformly. The Leaf class has no children and implements the Component interface directly. The Composite class maintains a container of child Component objects (children) and forwards requests to these children (for each child in children: child.operation()). The object collaboration diagram shows the run-time interactions: In this example, the Client object sends a request to the top-level Composite object (of type Component) in the tree structure. The request is forwarded to (performed on) all child Component objects (Leaf and Composite objects) downwards the tree structure.Defining Child-Related Operations Defining child-related operations in the Composite design pattern. There are two design variants for defining and implementing child-related operations like adding/removing a child component to/from the container (add(child)/remove(child)) and accessing a child component (getChild()): Design for uniformity: Child-related operations are defined in the Component interface. This enables clients to treat Leaf and Composite objects uniformly. But is lost because clients can perform child-related operations on Leaf objects. Design for type safety: Child-related operations are defined only in the Composite class. Clients must treat Leaf and Composite objects differently. But type safety is gained because clients can not perform child-related operations on Leaf objects. The Composite design pattern emphasizes uniformity over type safety. UML class diagram Composite pattern in Unified Modeling LanguageUML.Component is the abstraction for all components, including composite ones declares the interface for objects in the composition (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate Leaf represents leaf objects in the composition implements all Component methods Composite represents a composite Component (component having children) implements methods to manipulate children implements all Component methods, generally by delegating them to its children Composite pattern in Lepus3LePUS3.Variation As it is described in Design Patterns, the pattern also involves including the child-manipulation methods in the main Component interface, not just the Composite subclass. More recent descriptions sometimes omit these methods.Example The following example, written in Java (programming language)Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In Backus-Naur form, Graphic ::= ellipse | GraphicList GraphicList ::= empty | Graphic GraphicList It could be extended to implement several other shapes (rectangle, etc.) and methods (translation (geometry)translate, etc.). Java import java.util.ArrayList; /** "Component" */ interface Graphic { //Prints the graphic. public void print(); } /** "Composite" */ class CompositeGraphic implements Graphic { //Collection of child graphics. private final ArrayList childGraphics = new ArrayList<>(); //Adds the graphic to the composition. public void add(Graphic graphic) { childGraphics.add(graphic); } //Prints the graphic. @Override public void print() { for (Graphic graphic : childGraphics) { graphic.print(); //Delegation } } } /** "Leaf" */ class Ellipse implements Graphic { //Prints the graphic. @Override public void print() { System.out.println("Ellipse"); } } /** Client */ class CompositeDemo { public static void main(String[] args) { //Initialize four ellipses Ellipse ellipse1 = new Ellipse(); Ellipse ellipse2 = new Ellipse(); Ellipse ellipse3 = new Ellipse(); Ellipse ellipse4 = new Ellipse(); //Creates two composites containing the ellipses CompositeGraphic graphic2 = new CompositeGraphic(); graphic2.add(ellipse1); graphic2.add(ellipse2); graphic2.add(ellipse3); CompositeGraphic graphic3 = new CompositeGraphic(); graphic3.add(ellipse4); //Create another graphics that contains two graphics CompositeGraphic graphic1 = new CompositeGraphic(); graphic1.add(graphic2); graphic1.add(graphic3); //Prints the complete graphic (Four times the string "Ellipse"). graphic1.print(); } } References External links class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Composite implementations in various languages Composite Pattern implementation in Java Composite pattern description from the Portland Pattern Repository Composite pattern in UML and in LePUS3, a formal modelling language Class::Delegation on CPAN "The End of Inheritance: Automatic Run-time Interface Building for Aggregated Objects" by Paul Baranowski PerfectJPattern Open Source Project, Provides componentized implementation of the Composite Pattern in Java A persistent Java-based implementation Composite Design Pattern Composite pattern 67

Decorator pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In object-oriented programming, the decorator pattern is a design pattern (computer science)design pattern that allows behavior to be added to an individual Object (computer science)object, dynamically, without affecting the behavior of other objects from the same Class (computer science)class. The decorator pattern is often useful for adhering to the Single_responsibility_principleSingle Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern. The decorator pattern is structurally nearly identical to the chain of responsibility pattern, the difference being that in a chain of responsibility, exactly one of the classes handles the request, while for the decorator, all classes handle the request.Overview The decorator design pattern is one of the twenty-three well-known Design PatternsGoF design 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.What problems can it solve? Responsibilities should be added to (and removed from) an object dynamically at run-time. A flexible alternative to subclassing for extending functionality should be provided. When using subclassing, different subclasses extend a class in different ways. But an extension is bound to the class at compile-time and can't be changed at run-time. What solution does it describe?Define Decorator objects that implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it perform additional functionality before/after forwarding a request. This allows working with different Decorator objects to extend the functionality of an object dynamically at run-time. See also the UML class and sequence diagram below. IntentDecorator Unified Modeling LanguageUML class diagram The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at Run time (program lifecycle phase)run-time, independently of other instances of the same Class (computer science)class, provided some groundwork is done at design time. This is achieved by designing a new Decorator class that Wrapper patternwraps the original class. This wrapping could be achieved by the following sequence of steps: Subclass the original Component class into a Decorator class (see UML diagram); In the Decorator class, add a Component pointer as a field; In the Decorator class, pass a Component to the Decorator constructor to initialize the Component pointer; In the Decorator class, Forwarding (object-oriented programming)forward all Component methods to the Component pointer; and In the ConcreteDecorator class, override any Component 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, (a.k.a. Trait_(computer_programming)trait) or class inheritance which is shared by the decorators and the decorated object. In the previous example the class Component is inherited by both the ConcreteComponent and the subclasses that descend from Decorator.The decorator pattern is an alternative to Subclass (computer science)subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at Run time (program lifecycle phase)run-time for selected objects. This Decorator pattern 68

difference becomes most important when there are several independent ways of extending functionality. In some object-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 both Java Platform, Standard Edition#java.ioJava and the .NET Framework incorporate the decorator pattern.MotivationUML diagram for the window example As an example, consider a window in a windowing system. To allow scrolling of the window's contents, one may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window interface, and assume this class has no functionality for adding scrollbars. One could create a subclass ScrollingWindow that provides them, or create a ScrollingWindowDecorator that adds this functionality to existing Window objects. At this point, either solution would be fine.Now, assume one also desires the ability to add borders to windows. Again, the original Window class has no support. The ScrollingWindow 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 not all windows, one must create subclasses WindowWithBorder and ScrollingWindowWithBorder etc. This problem gets worse with every new feature or window subtype to be added. For the decorator solution, a new BorderedWindowDecorator is created. Any combination of ScrollingWindowDecorator or BorderedWindowDecorator 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, the SimpleWindow and WindowDecorator classes implement the Window interface, which defines the draw() method and the getDescription() method that are required in this scenario, in order to decorate a window control.Usage A decorator makes it possible to add or alter behavior of an interface at run-time. Alternatively, the Adapter patternadapter can be used when the wrapper must respect a particular interface and must support Polymorphism (computer science)polymorphic behavior, and the Facade patternFacade when an easier or simpler interface to an underlying object is desired. Pattern Intent Adapter patternAdapter Converts one interface to another so that it matches what the client is expecting Decorator Dynamically adds responsibility to the interface by wrapping the original code Facade patternFacade Provides a simplified interface StructureUML class and sequence diagram A sample UML class and sequence diagram for the Decorator design pattern. In the above Unified Modeling LanguageUML class diagram, the abstract Decorator class maintains a reference (component) to the decorated object (Component) and forwards all requests to it (component.operation()). This makes Decorator transparent (invisible) to clients of Component. Subclasses (Decorator1,Decorator2) implement additional behavior (addBehavior()) that should be added to the Component (before/after forwarding a request to it). The sequence diagram shows the run-time interactions: The Client object works through Decorator1 and Decorator2 objects to extend the functionality of a Component1 object. The Client calls operation() on Decorator1, which forwards the request to Decorator2. Decorator2 performs addBehavior() after forwarding the request to Component1 and returns to Decorator1, which performs addBehavior() and returns to the Client. ExamplesGo package decolog import ( "log" "time" ) //OperateFn represents operations that require decoration type OperateFn func() //Decorate the operation func Decorate(opFn OperateFn) { defer func(s time.Time) { log.Printf("elapsed time %0.2d ms", time.Since(s).Nanoseconds()/(1<<20)) }(time.Now()) // real operation function opFn() } // package main package main import ( "github.com/tkstorm/go-design/structural/decorator/decolog" "log" "math/rand" "time" ) //output: //2019/08/19 19:05:24 finish action a //2019/08/19 19:05:24 elpased time 77 ms //2019/08/19 19:05:24 finish action b //2019/08/19 19:05:24 elpased time 88 ms func main() { // decorate log a decolog.Decorate(decolog.OperateFn(DoActionA)) // decorate log b decolog.Decorate(decolog.OperateFn(DoActionB)) } func DoActionA() { time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond) log.Println("finish action a") } func DoActionB() { time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond) log.Println("finish action b") } C++ Two options are presented here, first a dynamic, runtime-composable decorator (has issues with calling decorated functions unless proxied explicitly) and a decorator Decorator pattern 69

that uses mixin inheritance. Dynamic Decorator #include #include struct Shape { virtual ~Shape() = default; virtual std::string GetName() const = 0; }; struct Circle : Shape { void Resize(float factor) { radius *= factor; } std::string GetName() const override { return std::string("A circle of radius ") + std::to_string(radius); } float radius = 10.0f; }; struct ColoredShape : Shape { ColoredShape(const std::string& color, Shape* shape) : color(color), shape(shape) {} std::string GetName() const override { return shape->GetName() + " which is colored " + color; } std::string color; Shape* shape; }; int main() { Circle circle; ColoredShape colored_shape("red", &circle); std::cout << colored_shape.GetName() << std::endl; } #include #include #include struct WebPage { virtual void display()=0; virtual ~WebPage() = default; }; struct BasicWebPage : WebPage { std::string html; void display() override { std::cout << "Basic WEB page" << std::endl; } ~BasicWebPage()=default; }; struct WebPageDecorator : WebPage { WebPageDecorator(std::unique_ptr webPage): _webPage(std::move(webPage)) { } void display() override { _webPage->display(); } ~WebPageDecorator()=default; private: std::unique_ptr _webPage; }; struct AuthenticatedWebPage : WebPageDecorator { AuthenticatedWebPage(std::unique_ptr webPage): WebPageDecorator(std::move(webPage)) {} void authenticateUser() { std::cout << "authentification done" << std::endl; } void display() override { authenticateUser(); WebPageDecorator::display(); } ~AuthenticatedWebPage()=default; }; struct AuthorizedWebPage : WebPageDecorator { AuthorizedWebPage(std::unique_ptr webPage): WebPageDecorator(std::move(webPage)) {} void authorizedUser() { std::cout << "authorized done" << std::endl; } void display() override { authorizedUser(); WebPageDecorator::display(); } ~AuthorizedWebPage()=default; }; int main(int argc, char* argv[]) { std::unique_ptr myPage = std::make_unique(); myPage = std::make_unique(std::move(myPage)); myPage = std::make_unique(std::move(myPage)); myPage->display(); std::cout << std::endl; return 0; } Static Decorator (Mixin Inheritance) This example demonstrates a static Decorator implementation, which is possible due to C++ ability to inherit from the template argument. #include #include struct Circle { void Resize(float factor) { radius *= factor; } std::string GetName() const { return std::string("A circle of radius ") + std::to_string(radius); } float radius = 10.0f; }; template struct ColoredShape : public T { ColoredShape(const std::string& color) : color(color) {} std::string GetName() const { return T::GetName() + " which is colored " + color; } std::string color; }; int main() { ColoredShape red_circle("red"); std::cout << red_circle.GetName() << std::endl; red_circle.Resize(1.5f); std::cout << red_circle.GetName() << std::endl; } Java First example (window/scrolling scenario) The following Java example illustrates the use of decorators using the window/scrolling scenario. // The Window interface class public interface Window { void draw(); // Draws the Window String getDescription(); // Returns a description of the Window } // Implementation of a simple Window without any scrollbars class SimpleWindow implements Window { @Override public void draw() { // Draw window } @Override public String getDescription() { return "simple window"; } } The following classes contain the decorators for all Window classes, including the decorator classes themselves. // abstract decorator class - note that it implements Window abstract class WindowDecorator implements Window { private final Window windowToBeDecorated; // the Window being decorated public WindowDecorator (Window windowToBeDecorated) { this.windowToBeDecorated = windowToBeDecorated; } @Override public void draw() { windowToBeDecorated.draw(); //Delegation } @Override public String getDescription() { return windowToBeDecorated.getDescription(); //Delegation } } // The first concrete decorator which adds vertical scrollbar functionality class VerticalScrollBarDecorator extends WindowDecorator { public VerticalScrollBarDecorator (Window windowToBeDecorated) { super(windowToBeDecorated); } @Override public void draw() { super.draw(); drawVerticalScrollBar(); } private void drawVerticalScrollBar() { // Draw the vertical scrollbar } @Override public String getDescription() { return super.getDescription() + ", including vertical scrollbars"; } } // The second concrete decorator which adds horizontal scrollbar functionality class HorizontalScrollBarDecorator extends WindowDecorator { public HorizontalScrollBarDecorator (Window windowToBeDecorated) { super(windowToBeDecorated); } @Override public void draw() { super.draw(); Decorator pattern 70

drawHorizontalScrollBar(); } private void drawHorizontalScrollBar() { // Draw the horizontal scrollbar } @Override public String getDescription() { return super.getDescription() + ", including horizontal scrollbars"; } } Here's a test program that creates a Window instance which is fully decorated (i.e., with vertical and horizontal scrollbars), and prints its description: public class DecoratedWindowTest { public static void main(String[] args) { // Create a decorated Window with horizontal and vertical scrollbars Window decoratedWindow = new HorizontalScrollBarDecorator ( new VerticalScrollBarDecorator (new SimpleWindow())); // Print the Window's description System.out.println(decoratedWindow.getDescription()); } } Below is the JUnit test class for the Test Driven Development import static org.junit.Assert.assertEquals; import org.junit.Test; public class WindowDecoratorTest { @Test public void testWindowDecoratorTest() { Window decoratedWindow = new HorizontalScrollBarDecorator(new VerticalScrollBarDecorator(new SimpleWindow())); // assert that the description indeed includes horizontal + vertical scrollbars assertEquals("simple window, including vertical scrollbars, including horizontal scrollbars", decoratedWindow.getDescription()) } } The output of this program is "simple window, including vertical scrollbars, including horizontal scrollbars". Notice how the getDescription method of the two decorators first retrieve the decorated Window's description and decorates it with a suffix.Second example (coffee making scenario) 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 decorator public interface Coffee { public double getCost(); // Returns the cost of the coffee public String getIngredients(); // Returns the ingredients of the coffee } // Extension of a simple coffee without any extra ingredients public class SimpleCoffee implements Coffee { @Override public double getCost() { return 1; } @Override public String getIngredients() { return "Coffee"; } } The following classes contain the decorators for all Coffee classes, including the decorator classes themselves. // Abstract decorator class - note that it implements Coffee interface public abstract class CoffeeDecorator implements Coffee { private final Coffee decoratedCoffee; public CoffeeDecorator(Coffee c) { this.decoratedCoffee = c; } @Override public double getCost() { // Implementing methods of the interface return decoratedCoffee.getCost(); } @Override public String getIngredients() { return decoratedCoffee.getIngredients(); } } // Decorator WithMilk mixes milk into coffee. // Note it extends CoffeeDecorator. class WithMilk extends CoffeeDecorator { public WithMilk(Coffee c) { super(c); } @Override public double getCost() { // Overriding methods defined in the abstract superclass return super.getCost() + 0.5; } @Override public String getIngredients() { return super.getIngredients() + ", Milk"; } } // Decorator WithSprinkles mixes sprinkles onto coffee. // Note it extends CoffeeDecorator. class WithSprinkles extends CoffeeDecorator { public WithSprinkles(Coffee c) { super(c); } @Override public double getCost() { return super.getCost() + 0.2; } @Override public String getIngredients() { return super.getIngredients() + ", Sprinkles"; } } Here's a test program that creates a Coffee instance which is fully decorated (with milk and sprinkles), and calculate cost of coffee and prints its ingredients: public class Main { public static void printInfo(Coffee c) { System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients()); } public static void main(String[] args) { Coffee c = new SimpleCoffee(); printInfo(c); c = new WithMilk(c); printInfo(c); c = new WithSprinkles(c); printInfo(c); } } The output of this program is given below: Cost: 1.0; Ingredients: Coffee Cost: 1.5; Ingredients: Coffee, Milk Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles PHP abstract class Component { protected $data; protected $value; abstract public function getData(); abstract public function getValue(); } class ConcreteComponent extends Component { public function __construct() { $this->value = 1000; $this->data = "Concrete Component:\t{$this->value}\n"; } public function getData() { return $this->data; } public function getValue() { return $this->value; } } abstract class Decorator extends Component { } class ConcreteDecorator1 extends Decorator { public function __construct(Component $data) { $this->value = 500; $this->data = $data; } public function getData() { return $this->data->getData() . "Concrete Decorator 1:\t{$this->value}\n"; } public function getValue() { return $this->value + $this->data->getValue(); } } class ConcreteDecorator2 extends Decorator { public function __construct(Component $data) { $this->value = 500; $this->data = $data; } public function getData() { return $this->data->getData() . "Concrete Decorator 2:\t{$this->value}\n"; } public function getValue() { return $this->value + $this->data->getValue(); } } class Client { private $component; public function Decorator pattern 71

__construct() { $this->component = new ConcreteComponent(); $this->component = $this->wrapComponent($this->component); echo $this->component->getData(); echo "Client:\t\t\t"; echo $this->component->getValue(); } private function wrapComponent(Component $component) { $component1 = new ConcreteDecorator1($component); $component2 = new ConcreteDecorator2($component1); return $component2; } } $client = new Client(); // Result: #quanton81 //Concrete Component: 1000 //Concrete Decorator 1: 500 //Concrete Decorator 2: 500 //Client: 2000 Python The following Python example, taken from Python Wiki - DecoratorPattern, shows us how to decorators to dynamically add many behaviors in an object: """ Demonstrated decorators in a world of a 10x10 grid of values 0-255. """ import random def s32_to_u16(x): if x < 0: sign = 0xf000 else: sign = 0 bottom = x & 0x00007fff return bottom | sign def seed_from_xy(x, y): return s32_to_u16(x) | (s32_to_u16(y) << 16) class RandomSquare: def __init__(s, seed_modifier): s.seed_modifier = seed_modifier def get(s, x, y): seed = seed_from_xy(x, y) ^ s.seed_modifier random.seed(seed) return random.randint(0, 255) class DataSquare: def __init__(s, initial_value=None): s.data = [initial_value] * 10 * 10 def get(s, x, y): return s.data[(y * 10) + x] # yes: these are all 10x10 def set(s, x, y, u): s.data[(y * 10) + x] = u class CacheDecorator: def __init__(s, decorated): s.decorated = decorated s.cache = DataSquare() def get(s, x, y): if s.cache.get(x, y) == None: s.cache.set(x, y, s.decorated.get(x, y)) return s.cache.get(x, y) class MaxDecorator: def __init__(s, decorated, max): s.decorated = decorated s.max = max def get(s, x, y): if s.decorated.get(x, y) > s.max: return s.max return s.decorated.get(x, y) class MinDecorator: def __init__(s, decorated, min): s.decorated = decorated s.min = min def get(s, x, y): if s.decorated.get(x, y) < s.min: return s.min return s.decorated.get(x, y) class VisibilityDecorator: def __init__(s, decorated): s.decorated = decorated def get(s, x, y): return s.decorated.get(x, y) def draw(s): for y in range(10): for x in range(10): print "%3d" % s.get(x, y), 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:Please do not confuse the Decorator Pattern (or an implementation of this design pattern in Python - as the above example) with Python syntax and #DecoratorsPython Decorators, a Python language feature. 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.Crystal abstract class Coffee abstract def cost abstract def ingredients end # Extension of a simple coffee class SimpleCoffee < Coffee def cost 1.0 end def ingredients "Coffee" end end # Abstract decorator class CoffeeDecorator < Coffee protected getter decorated_coffee : Coffee def initialize(@decorated_coffee) end def cost decorated_coffee.cost end def ingredients decorated_coffee.ingredients end end class WithMilk < CoffeeDecorator def cost super + 0.5 end def ingredients super + ", Milk" end end class WithSprinkles < CoffeeDecorator def cost super + 0.2 end def ingredients super + ", Sprinkles" end end class Program def print(coffee : Coffee) puts "Cost: #{coffee.cost}; Ingredients: #{coffee.ingredients}" end def initialize coffee = SimpleCoffee.new print(coffee) coffee = WithMilk.new(coffee) print(coffee) coffee = WithSprinkles.new(coffee) print(coffee) end end Program.new Output: Cost: 1.0; Ingredients: Coffee Cost: 1.5; Ingredients: Coffee, Milk Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles C# namespace WikiDesignPatterns { public interface IBike { string GetDetails(); double GetPrice(); } public class AluminiumBike : IBike { public double GetPrice() { return 100; } public string GetDetails() { return "Aluminium Bike"; } } public class CarbonBike : IBike { public double GetPrice() { return 1000; } public string GetDetails() { return "Carbon"; } } public abstract class BikeAccessories : IBike { private readonly IBike _bike; public BikeAccessories(IBike bike) { _bike = bike; } public virtual double GetPrice() { return _bike.GetPrice(); } public virtual string GetDetails() { return _bike.GetDetails(); } } public class SecurityPackage : BikeAccessories { public SecurityPackage(IBike bike):base(bike) { } public override string GetDetails() { return base.GetDetails() + " + Security Package"; } public override double GetPrice() { return base.GetPrice() + 1; } } public class SportPackage : BikeAccessories { public SportPackage(IBike bike) : base(bike) { } public override string GetDetails() { return base.GetDetails() + " + Sport Package"; } public override double GetPrice() { return base.GetPrice() + 10; } } public class BikeShop { public Decorator pattern 72

static void UpgradeBike() { var basicBike = new AluminiumBike(); BikeAccessories upgraded = new SportPackage(basicBike); upgraded = new SecurityPackage(upgraded); Console.WriteLine($"Bike: '{upgraded.GetDetails()}' Cost: {upgraded.GetPrice()}"); } } } Output: Bike: 'Aluminium Bike + Sport Package + Security Package' Cost: 111 References External linksclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Decorator implementations in various languages Decorator Pattern implementation in Java Decorator pattern description from the Portland Pattern Repository

Facade pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The (also spelled façade) is a software design pattern software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an Object (computer science)object that serves as a front-facing interface masking more complex underlying or structural code. A facade can: improve the readability and usability of a software library by masking interaction with more complex components behind a single (and often simplified) Application programming interfaceAPI provide a context-specific interface to more generic functionality (complete with context-specific input Data validationvalidation) serve as a launching point for a broader Code refactoringrefactor of Monolithic systemmonolithic or tightly-coupled systems in favor of more Loose couplingloosely-coupled code Developers often use the facade design pattern when a system is very complex or difficult to understand because the system has many interdependent classes or because its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class that contains a set of members required by the client. These members access the system on behalf of the facade client and hide the implementation details. Overview The Facade design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Facade design pattern solve? To make a complex subsystem easier to use, a simple interface should be provided for a set of interfaces in the subsystem. The dependencies on a subsystem should be minimized. Clients that access a complex subsystem directly refer to (depend on) many different objects having different interfaces (tight coupling), which makes the clients hard to implement, change, test, and reuse. What solution does the Facade design pattern describe? Define a Facade object that implements a simple interface in terms of (by delegating to) the interfaces in the subsystem and may perform additional functionality before/after forwarding a request. This enables to work through a Facade object to minimize the dependencies on a subsystem. See also the UML class and sequence diagram below. Usage A Facade is used when an easier or simpler interface to an underlying object is desired. Alternatively, an Adapter patternadapter can be used when the wrapper must respect a particular interface and must support Polymorphism (computer science)polymorphic behavior. A Decorator patterndecorator makes it possible to add or alter behavior of an interface at run-time. Pattern Intent Adapter_patternAdapter Converts one interface to another so that it matches what the client is expecting Decorator_patternDecorator Dynamically adds responsibility to the interface by wrapping the original code Facade Facade pattern 73

Provides a simplified interface The facade pattern is typically used when a simple interface is required to access a complex system, a system is very complex or difficult to understand, an entry point is needed to each level of layered software, or the abstractions and implementations of a subsystem are tightly coupled. StructureUML class and sequence diagram A sample UML class and sequence diagram for the Facade design pattern. In this Unified Modeling LanguageUML class diagram, the Client class doesn't access the subsystem classes directly. Instead, the Client works through a Facade class that implements a simple interface in terms of (by delegating to) the subsystem classes (Class1, Class2, and Class3). The Client depends only on the simple Facade interface and is independent of the complex subsystem.The sequence diagram shows the run-time interactions: The Client object works through a Facade object that delegates the request to the Class1, Class2, and Class3 instances that perform the request. UML class diagram Facade The facade class abstracts Packages 1, 2, and 3 from the rest of the application. Clients The objects are using the Facade Pattern to access resources from the Packages. Example This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive). C++ struct CPU { void Freeze(); void Jump(long position); void Execute(); }; struct HardDrive { char* Read(long lba, int size); }; struct Memory { void Load(long position, char* data); }; class ComputerFacade { public: void Start() { cpu_.Freeze(); memory_.Load(kBootAddress, hard_drive_.Read(kBootSector, kSectorSize)); cpu_.Jump(kBootAddress); cpu_.Execute(); } private: CPU cpu_; Memory memory_; HardDrive hard_drive_; }; int main() { ComputerFacade computer; computer.Start(); } ReferencesExternal linksclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Facade implementations in various languagesclass=noviewerWikimedia Commons has media related to Facade pattern. Description from the Portland Pattern Repository 74 Flyweight pattern

In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the objects temporarily when they are used. A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning. In other contexts the idea of sharing identical data structures is called hash consing.

Overview The Flyweight design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Flyweight design pattern solve? • Large numbers of objects should be supported efficiently. • Creating large numbers of objects should be avoided. When representing large text documents, for example, creating an object for each character in the document would result in a huge number of objects that could not be processed efficiently. What solution does the Flyweight design pattern describe? Define Flyweight objects that • store intrinsic (invariant) state that can be shared and • provide an interface through which extrinsic (variant) state can be passed in. This enables clients to (1) reuse (share) Flyweight objects (instead of creating a new object each time) and (2) pass in extrinsic state when they invoke a Flyweight operation. This greatly reduces the number of physically created objects. Intrinsic state is invariant (context independent) and therefore can be shared (for example, the code of character 'A' in a given character set). Extrinsic state is variant (context dependent) and therefore can not be shared and must be passed in (for example, the position of character 'A' in a text document). See also the UML class and sequence diagram below. Flyweight pattern 75

History According to the textbook Design Patterns: Elements of Reusable Object-Oriented Software, the flyweight pattern was first coined and extensively explored by Paul Calder and Mark Linton in 1990 to efficiently handle glyph information in a WYSIWYG document editor, although similar techniques were already used in other systems, e.g., an application framework by Weinand et al. (1988).

Structure

UML class and sequence diagram

A sample UML class and sequence diagram for the Flyweight design pattern.

In the above UML class diagram, the Client class refers (1) to the FlyweightFactory class to create/share Flyweight objects and (2) to the Flyweight interface to perform an operation by passing in extrinsic (variant) state (flyweight.operation(extrinsicState)). The Flyweight1 class implements the Flyweight interface and stores intrinsic (invariant) state that can be shared. The sequence diagram shows the run-time interactions: The Client object calls getFlyweight(key) on the FlyweightFactory that creates and returns a Flyweight1 object. After calling operation(extrinsicState) on the returned Flyweight1 object, the Client again calls getFlyweight(key) on the FlyweightFactory, which now shares and returns the already existing Flyweight1 object.

Immutability and equality To enable safe sharing, between clients and threads, Flyweight objects must be immutable. Flyweight objects are by definition value objects. The identity of the object instance is of no consequence therefore two Flyweight instances of the same value are considered equal. Example in C# (note Equals and GetHashCode overrides as well as == and != operator overloads):

public class CoffeeFlavour { public CoffeeFlavour(string flavour) { this.Flavour = flavour; }

public string Flavour { get; }

public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is CoffeeFlavour && Equals((CoffeeFlavour)obj); }

public bool Equals(CoffeeFlavour other) { return string.Equals(this.Flavour, other.Flavour); Flyweight pattern 76

}

public override int GetHashCode() { return this.Flavour.GetHashCode(); }

public static bool operator ==(CoffeeFlavour a, CoffeeFlavour b) { return Equals(a, b); }

public static bool operator !=(CoffeeFlavour a, CoffeeFlavour b) { return !Equals(a, b); } }

Concurrency Special consideration must be made in scenarios where Flyweight objects are created on multiple threads. If the list of values is finite and known in advance the Flyweights can be instantiated ahead of time and retrieved from a container on multiple threads with no contention. If Flyweights are instantiated on multiple threads there are two options: 1. Make Flyweight instantiation single threaded thus introducing contention and ensuring one instance per value. 2. Allow concurrent threads to create multiple Flyweight instances thus eliminating contention and allowing multiple instances per value. This option is only viable if the equality criterion is met.

Example in C#

using System.Collections.Concurrent;

using System.Collections.Generic;

using System.Threading;

public interface ICoffeeFlavourFactory {

CoffeeFlavour GetFlavour(string flavour);

}

public class ReducedMemoryFootprint : ICoffeeFlavourFactory {

private readonly object _cacheLock = new object();

private readonly IDictionary _cache = new Dictionary();

public CoffeeFlavour GetFlavour(string flavour) {

if (_cache.TryGetValue(flavour, out CoffeeFlavour

cachedCoffeeFlavour))

return cachedCoffeeFlavour;

var coffeeFlavour = new CoffeeFlavour(flavour);

ThreadPool.QueueUserWorkItem(AddFlavourToCache, coffeeFlavour);

return coffeeFlavour;

} Flyweight pattern 77

private void AddFlavourToCache(object state) {

var coffeeFlavour = (CoffeeFlavour)state;

if (!_cache.ContainsKey(coffeeFlavour.Flavour)) {

lock (_cacheLock) {

_cache[coffeeFlavour.Flavour] = coffeeFlavour;

}

}

}

}

public class MinimumMemoryFootprint : ICoffeeFlavourFactory {

private readonly ConcurrentDictionary _cache = new

ConcurrentDictionary();

public CoffeeFlavour GetFlavour(string flavour) {

return _cache.GetOrAdd(flavour, flv => new CoffeeFlavour(flv));

}

}

Simple implementation Flyweight allows you to share bulky data that are common to each object. In other words, if you think that same data is repeating for every object, you can use this pattern to point to the single object and hence can easily save space. Here the FlyweightPointer creates a static member Company, which is used for every object of MyObject.

// Defines Flyweight object that repeats itself. public class FlyWeight { public string CompanyName { get; set; } public string CompanyLocation { get; set; } public string CompanyWebSite { get; set; } //Bulky Data public byte[] CompanyLogo { get; set; } }

public static class FlyWeightPointer { public static readonly FlyWeight Company = new FlyWeight { CompanyName = "Abc", CompanyLocation = "XYZ", CompanyWebSite = "www.abc.com" // Load CompanyLogo here }; }

public class MyObject { public string Name { get; set; } Flyweight pattern 78

public string Company { get { return FlyWeightPointer.Company.CompanyName; } } }

Example in Java import java.util.ArrayList; import java.util.WeakHashMap;

class CoffeeFlavour { private final String name; private static final WeakHashMap CACHE = new WeakHashMap<>();

// only intern() can call this constructor private CoffeeFlavour(String name) { this.name = name; }

@Override public String toString() { return name; }

public static CoffeeFlavour intern(String name) { synchronized (CACHE) { return CACHE.computeIfAbsent(name, CoffeeFlavour::new); } }

public static int flavoursInCache() { synchronized (CACHE) { return CACHE.size(); } } }

@FunctionalInterface interface Order { void serve();

static Order of(String flavourName, int tableNumber) { CoffeeFlavour flavour = CoffeeFlavour.intern(flavourName); return () -> System.out.println("Serving " + flavour + " to Flyweight pattern 79

table " + tableNumber); } }

class CoffeeShop { private final ArrayList orders = new ArrayList<>();

public void takeOrder(String flavour, int tableNumber) { orders.add(Order.of(flavour, tableNumber)); }

public void service() { orders.forEach(Order::serve); } }

public class FlyweightExample { public static void main(String[] args) { CoffeeShop shop = new CoffeeShop(); shop.takeOrder("", 2); shop.takeOrder("Frappe", 1); shop.takeOrder("Espresso", 1); shop.takeOrder("Frappe", 897); shop.takeOrder("Cappuccino", 97); shop.takeOrder("Frappe", 3); shop.takeOrder("Espresso", 3); shop.takeOrder("Cappuccino", 3); shop.takeOrder("Espresso", 96); shop.takeOrder("Frappe", 552); shop.takeOrder("Cappuccino", 121); shop.takeOrder("Espresso", 121);

shop.service(); System.out.println("CoffeeFlavor objects in cache: " + CoffeeFlavour.flavoursInCache()); } }

The execution of this code will give the following :

Serving Cappuccino to table 2 Serving Frappe to table 1 Serving Espresso to table 1 Serving Frappe to table 897 Serving Cappuccino to table 97 Serving Frappe to table 3 Serving Espresso to table 3 Serving Cappuccino to table 3 Flyweight pattern 80

Serving Espresso to table 96 Serving Frappe to table 552 Serving Cappuccino to table 121 Serving Espresso to table 121 CoffeeFlavor objects in cache: 3

Example in Scala /* run as a script using `scala flyweight.scala` expected output: Serving CoffeeFlavour(Espresso) to table 121 Serving CoffeeFlavour(Cappuccino) to table 121 Serving CoffeeFlavour(Frappe) to table 552 Serving CoffeeFlavour(Espresso) to table 96 Serving CoffeeFlavour(Cappuccino) to table 3 Serving CoffeeFlavour(Espresso) to table 3 Serving CoffeeFlavour(Frappe) to table 3 Serving CoffeeFlavour(Cappuccino) to table 97 Serving CoffeeFlavour(Frappe) to table 897 Serving CoffeeFlavour(Espresso) to table 1 Serving CoffeeFlavour(Frappe) to table 1 Serving CoffeeFlavour(Cappuccino) to table 2 total CoffeeFlavour objects made: 3 */

/* the `private` constructor ensures that only interned * values of type `CoffeeFlavour` can be obtained. */ class CoffeeFlavour private (val name: String){ override def toString = s"CoffeeFlavour($name)" }

object CoffeeFlavour { import scala.collection.mutable import scala.ref.WeakReference private val cache = mutable.Map.empty[String, ref.WeakReference[CoffeeFlavour]]

def apply(name: String): CoffeeFlavour = synchronized { cache.get(name) match { case Some(WeakReference(flavour)) => flavour case _ => val newFlavour = new CoffeeFlavour(name) cache.put(name, WeakReference(newFlavour)) newFlavour } } Flyweight pattern 81

def totalCoffeeFlavoursMade = cache.size }

case class Order(tableNumber: Int, flavour: CoffeeFlavour){

def serve: Unit = println(s"Serving $flavour to table $tableNumber") }

object CoffeeShop { var orders = List.empty[Order]

def takeOrder(flavourName: String, table: Int) { val flavour = CoffeeFlavour(flavourName) val order = Order(table, flavour) orders = order :: orders }

def service: Unit = orders.foreach(_.serve)

def report = s"total CoffeeFlavour objects made: ${CoffeeFlavour.totalCoffeeFlavoursMade}" }

CoffeeShop.takeOrder("Cappuccino", 2) CoffeeShop.takeOrder("Frappe", 1) CoffeeShop.takeOrder("Espresso", 1) CoffeeShop.takeOrder("Frappe", 897) CoffeeShop.takeOrder("Cappuccino", 97) CoffeeShop.takeOrder("Frappe", 3) CoffeeShop.takeOrder("Espresso", 3) CoffeeShop.takeOrder("Cappuccino", 3) CoffeeShop.takeOrder("Espresso", 96) CoffeeShop.takeOrder("Frappe", 552) CoffeeShop.takeOrder("Cappuccino", 121) CoffeeShop.takeOrder("Espresso", 121)

CoffeeShop.service println(CoffeeShop.report) Flyweight pattern 82

Example in Ruby # Flyweight Object class Lamp attr_reader :color #attr_reader makes color attribute available outside #of the class by calling .color on a Lamp instance

def initialize(color) @color = color end end

class TreeBranch def initialize(branch_number) @branch_number = branch_number end

def hang(lamp) puts "Hang #{lamp.color} lamp on branch #{@branch_number}" end end

# Flyweight Factory class LampFactory def initialize @lamps = {} end

def find_lamp(color) if @lamps.has_key?(color) # if the lamp already exists, reference it instead of creating a new one lamp = @lamps[color] else lamp = Lamp.new(color) @lamps[color] = lamp end lamp end

def total_number_of_lamps_made @lamps.size end end

class ChristmasTree def initialize Flyweight pattern 83

@lamp_factory = LampFactory.new @lamps_hung = 0

dress_up_the_tree end

def hang_lamp(color, branch_number) TreeBranch.new(branch_number).hang(@lamp_factory.find_lamp(color)) @lamps_hung += 1 end

def dress_up_the_tree hang_lamp('red', 1) hang_lamp('blue', 1) hang_lamp('yellow', 1) hang_lamp('red', 2) hang_lamp('blue', 2) hang_lamp('yellow', 2) hang_lamp('red', 3) hang_lamp('blue', 3) hang_lamp('yellow', 3) hang_lamp('red', 4) hang_lamp('blue', 4) hang_lamp('yellow', 4) hang_lamp('red', 5) hang_lamp('blue', 5) hang_lamp('yellow', 5) hang_lamp('red', 6) hang_lamp('blue', 6) hang_lamp('yellow', 6) hang_lamp('red', 7) hang_lamp('blue', 7) hang_lamp('yellow', 7) puts "Made #{@lamp_factory.total_number_of_lamps_made} total lamps" puts "Hung #{@lamps_hung} total lamps" end end

Example in Python Attributes can be defined at the class-level instead of only for instances in Python because classes are first-class objects in the language—meaning there are no restrictions on their use as they are the same as any other object. New-style class instances store instance data in a special attribute dictionary instance.__dict__. By default, accessed attributes are first looked up in this __dict__, and then fall back to the instance's class attributes next. In this way, a class can effectively be a kind of Flyweight container for its instances. Although Python classes are mutable by default, immutability can be emulated by overriding the class's __setattr__ method so that it disallows changes to any Flyweight attributes. Flyweight pattern 84

# Instances of CheeseBrand will be the Flyweights class CheeseBrand(object): def __init__(self, brand: str, cost: float) -> None: self.brand = brand self.cost = cost self._immutable = True # Disables future attributions

def __setattr__(self, name, value): if getattr(self, '_immutable', False): # Allow initial attribution raise RuntimeError('This object is immutable') else: super().__setattr__(name, value)

class CheeseShop(object): menu = {} # Shared container to access the Flyweights

def __init__(self) -> None: self.orders = {} # per-instance container with private attributes

def stock_cheese(self, brand: str, cost: float) -> None: cheese = CheeseBrand(brand, cost) self.menu[brand] = cheese # Shared Flyweight

def sell_cheese(self, brand: str, units: int) -> None: self.orders.setdefault(brand, 0) self.orders[brand] += units # Instance attribute

def total_units_sold(self): return sum(self.orders.values())

def total_income(self): income = 0 for brand, units in self.orders.items(): income += self.menu[brand].cost * units return income

shop1 = CheeseShop() shop2 = CheeseShop()

shop1.stock_cheese('white', 1.25) shop1.stock_cheese('blue', 3.75) # Now every CheeseShop have 'white' and 'blue' on the inventory # The SAME 'white' and 'blue' CheeseBrand Flyweight pattern 85

shop1.sell_cheese('blue', 3) # Both can sell shop2.sell_cheese('blue', 8) # But the units sold are stored per-instance

assert shop1.total_units_sold() == 3 assert shop1.total_income() == 3.75 * 3

assert shop2.total_units_sold() == 8 assert shop2.total_income() == 3.75 * 8

Example in Swift // Instances of CoffeeFlavour will be the Flyweights struct CoffeeFlavor : CustomStringConvertible { var flavor: String var description: String { flavor } }

// Menu acts as a factory and cache for CoffeeFlavour flyweight objects struct Menu { private var flavors: [String: CoffeeFlavor] = [:]

mutating func lookUp(flavor: String) -> CoffeeFlavor { if let existing = flavors[flavor] { return existing } let newFlavor = CoffeeFlavor(flavor: flavor) flavors[flavor] = newFlavor return newFlavor } }

struct CoffeeShop { private var orders: [Int: CoffeeFlavor] = [:] private var menu = Menu()

mutating func takeOrder(flavor: String, table: Int) { orders[table] = menu.lookUp(flavor: flavor) }

func serve() { for (table, flavor) in orders { print("Serving \(flavor) to table \(table)") } } }

var coffeeShop = CoffeeShop() coffeeShop.takeOrder(flavor: "Cappuccino", table: 1) Flyweight pattern 86

coffeeShop.takeOrder(flavor: "Frappe", table: 3) coffeeShop.takeOrder(flavor: "Espresso", table: 2) coffeeShop.takeOrder(flavor: "Frappe", table: 15) coffeeShop.takeOrder(flavor: "Cappuccino", table: 10) coffeeShop.takeOrder(flavor: "Frappe", table: 8) coffeeShop.takeOrder(flavor: "Espresso", table: 7) coffeeShop.takeOrder(flavor: "Cappuccino", table: 4) coffeeShop.takeOrder(flavor: "Espresso", table: 9) coffeeShop.takeOrder(flavor: "Frappe", table: 12) coffeeShop.takeOrder(flavor: "Cappuccino", table: 13) coffeeShop.takeOrder(flavor: "Espresso", table: 5) coffeeShop.serve()

Example in Crystal # Instances of CoffeeFlavor will be the Flyweights class CoffeeFlavor def initialize(new_flavor : String) @name = new_flavor end

def to_s(io) io << @name end end

# Menu acts as a factory and cache for CoffeeFlavor flyweight objects class Menu def initialize @flavors = {} of String => CoffeeFlavor end

def lookup(flavor_name : String) @flavors[flavor_name] ||= CoffeeFlavor.new(flavor_name) end

def total_flavors_made @flavors.size end end

# Order is the context of the CoffeeFlavor flyweight. class Order private getter table_number : Int32, flavor : CoffeeFlavor

def initialize(@table_number, @flavor) end Flyweight pattern 87

def serve puts "Serving #{flavor} to table #{table_number}" end end

class CoffeeShop private getter orders private getter menu

def initialize @orders = [] of Order @menu = Menu.new end

def take_order(flavor_name : String, table : Int32) flavor = menu.lookup(flavor_name) order = Order.new(table, flavor) @orders << order end

def service orders.each do |order| order.serve end end

def report "Total CoffeeFlavor made: #{menu.total_flavors_made}" end end

# Program shop = CoffeeShop.new shop.take_order("Cappuchino", 2) shop.take_order("Frappe", 1) shop.take_order("Espresso", 1) shop.take_order("Frappe", 897) shop.take_order("Cappuccino", 97) shop.take_order("Frappe", 3) shop.take_order("Espresso", 3) shop.take_order("Cappuccino", 3) shop.take_order("Espresso", 96) shop.take_order("Frappe", 552) shop.take_order("Cappuccino", 121) shop.take_order("Espresso", 121)

shop.service Flyweight pattern 88

puts shop.report

Output

Serving Cappuchino to table 2 Serving Frappe to table 1 Serving Espresso to table 1 Serving Frappe to table 897 Serving Cappuccino to table 97 Serving Frappe to table 3 Serving Espresso to table 3 Serving Cappuccino to table 3 Serving Espresso to table 96 Serving Frappe to table 552 Serving Cappuccino to table 121 Serving Espresso to table 121 Total CoffeeFlavor made: 4

References

Front controller

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The front controller software design pattern is listed in several pattern catalogs and related to the design of web applications. It is "a Model–view–controllercontroller that handles all requests for a ", which is a useful structure for developers to achieve the flexibility and reuse without code redundancy.InstructionA typical front controller structure. Front controllers are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation. The front controller may be implemented as a Java (programming language)Java object, or as a script in a script language like PHP, Raku (programming language)Raku, Python (programming language)Python or Ruby (programming language)Ruby that is called on every request of a web Session (computer science)session. This script, for example an index.php, would handle all tasks that are common to the application or the framework, such as session handling, Caching (computing)caching, and input filtering. Based on the specific request, it would then instantiate further objects and call methods to handle the particular task(s) required.The alternative to a front controller would be individual scripts like login.php and order.php that would each then satisfy the type of request. Each script would have to duplicate code or objects that are common to all tasks. However, each script might also have more flexibility to implement the particular task required.Examples Several web-tier application frameworks implement the front controller pattern, among them: Apache StrutsASP.NET MVCCairngorm (Flex framework)Cairngorm framework in Adobe Flex Cro or Bailador frameworks in Raku (programming Front controller 89

language)RakuDrupalmodel–view–controllerMVC frameworks written in PHP. For example, , Cake PHPCakePHP, , , CodeIgniter and Zend FrameworkSpring FrameworkYesod () written in Haskell (programming language)HaskellImplementation To better understand front controller pattern, there is an example to implement front controller in Java. It can be defined in 3 components: XML Mapping: files that map requests to the class that will handle the request processing. Request Processor: used for dealing with the request processing (and modifying or retrieving the appropriate model). Flow Manager: first get the request and the output of the processing, then determine what will show on the next page. Participants and responsibilitiesController Dispatcher Helper View The controller is an entrance for users to handle requests in the system. It realizes authentication by playing the role of delegating helper or initiate contact retrieval. Dispatchers can be used for navigation and managing the view output. Users will receive next view that is determined by the dispatcher. Dispatchers are also flexible: they can be encapsulated within the controller directly or separated to another component. The dispatcher provides a static view along with the dynamic mechanism. It also uses the RequestDispatcher object (supported in the servlet specification) and encapsulates some additional processing. A helper helps view or controller to process. Thus helper can achieve various goals. At view side, the helper collects data and sometimes stores data as an intermediate station. Before view's process, helpers serve to adapt the data model for it. Helpers do certain pre-processes such as formatting the data to web content or providing direct access to the raw data. Multiple helpers can collaborate with one view for most conditions. They are implemented as JavaBeans Activation FrameworkJavaBeans components in JavaServer PagesJSP 1.0+ and custom tags in JSP 1.1+. Additionally, a helper also works as a transformer that is used to adapt and convert the model into the suitable format. With the collaboration of helpers, view displays information to the client. It processes data from a model. The view will display if the processing succeeds and vice versa. Demo implementation in Java Here is part of a demo code to implement front controller. private void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... try { getRequestProcessor().processRequest(request); getScreenFlowManager().forwardToNextScreen(request, response); } catch (Throwable ex) { String className = ex.getClass().getName(); nextScreen = getScreenFlowManager().getExceptionScreen(ex); // Put the exception in the request request.setAttribute("javax.servlet.jsp.jspException", ex); if (nextScreen == null) { // Send to general error screen ex.printStackTrace(); throw new ServletException("MainServlet: unknown exception: " + className); } } Benefits and liabilities There are three benefits for using front controller pattern.Centralized control. Front controller handles all the requests to the web application. This implementation of centralized control that avoids using multiple controllers is desirable for enforcing application-wide policies such as users tracking and security.Thread-safety. A new command object arises when receiving a new request and the command objects are not meant to be thread safe. Thus, it will be safe in the command classes. Though safety is not guaranteed when threading issues are gathered, codes that act with command is still thread safe.Configurability. Since only one front controller is needed in web application, the configuration of web applications implementation is largely simplified. The handler accomplishes the rest of dispatching so that it is not required to change anything before adding new commands with dynamic ones.In terms of liability, front controllers that determine the following activities by searching the database or XML documents, performance might be decreased. And implementation of front controller to existed systems always involving replacing the current ones, which makes it harder for beginners to start with. Relationship with MVC pattern In order to improve system reliability and maintainability, duplicated codes should be avoided and centralized when they are of the same common logic through the whole system. The data for the application is better to be handled in one location, thus there will be no need to duplicate database retrieval code. Different roles in the MVC pattern should be separated to increase testability, which is also true for controller part in the MVC pattern. Comparison Page controller is an alternative to front controller in MVC model. Page Controller Front Controller Base class Base class is needed and will grow simultaneously with the development of the application. The centralization of solving all requests is easier to modify than base class method. Security Low security because various objects react differently without consistency. High. The controller is implemented in coordinated fashion, making the application safer. Logical Page Single object on each logical page. Only one controller handles all Front controller 90

requests. Complexity Low High ReferencesNotesAlur, Deepak; John Crup; Dan Malks (2003). Core J2EE Patterns, Best Practices and Design Strategies, 2nd Ed. Press. pp. 650pp. ISBN (identifier)ISBN 0-13-142246-4.Martin Fowler (software engineer)Fowler, Martin (2003). Patterns of Enterprise Application Architecture. pp. 560pp. ISBN (identifier)ISBN 978-0-321-12742-6. External links Bear Bibeault's Front Man™, a lightweight Java implementation.

Marker interface pattern

The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface (also called tagging interface), and methods that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. An example of the application of marker interfaces from the Java programming language is the Serializable [1] interface. A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream [2]. The ObjectOutputStream private method writeObject0(Object,boolean) contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.

Critique A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot "unimplement" a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException (per ObjectOutputStream docs) Another solution is for the language to support metadata directly: • Both the .NET Framework and Java (as of Java 5 (1.5)) provide support for such metadata. In .NET, they are called "custom attributes", in Java they are called "annotations". Despite the different name, they are conceptually the same thing. They can be defined on classes, member variables, methods, and method parameters and may be accessed using reflection. • In Python, the term "marker interface" is common in Zope and Plone. Interfaces are declared as metadata and subclasses can use implementsOnly to declare they do not implement everything from their super classes. Marker interface pattern 91

References

Module pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the is a design pattern (computer science)design pattern used to implement the concept of software modules, defined by , in a programming language with incomplete direct support for the concept.This pattern can be implemented in several ways depending on the host programming language, such as the singleton patternsingleton design pattern, object-oriented static members in a class (software)class and procedural global functions. In Python, the pattern is built into the language, and each .py file is automatically a module. Definition & Structure The module software design pattern provides the features and syntactic structure defined by the modular programming paradigm to programming languages that have incomplete support for the concept.The object module pattern expressed in Unified Modeling LanguageUML.Concept In software development, source code can be organized into components that accomplish a particular function or contain everything necessary to accomplish a particular task. Modular programming is one of those approaches. The concept of a "module" is not fully supported in many common programming languages. Features In order to consider that a Singleton or any group of related code implements this pattern, the following features must be supplied: A portion of the code must have global or public access and be designed for use as global/public code. Additional private or protected code can be executed by the main public code. A module must have an initializer function that is equivalent to, or complementary to an object constructor method. This feature is not supported by regular namespaces. A module must have a finalizer function that is equivalent to, or complementary to an object destructor method. This feature is not supported by regular namespaces. Supporting members may require initialization/finalization code that is executed by the module's initializer/finalizer function. Most members are functions that perform operations on elements external to the class, provided as arguments by calling functions. Such functions are "utilities", "tools" or "libraries". Implementations The semantics and syntax of each programming language may affect the implementation of this pattern. Object-oriented programming languages Java Although Java (language)Java supports the notion of a namespace, a reduced version of a module, some scenarios benefit from employing the design pattern instead of using namespaces.The following example uses the singleton pattern. Definition package consoles; import java.io.InputStream; import java.io.PrintStream; public final class MainModule { private static MainModule singleton = null; public InputStream input = null; public PrintStream output = null; public PrintStream error = null; private MainModule() { // does nothing on purpose !!! } // ... public static MainModule getSingleton() { if (MainModule.singleton == null) { MainModule.singleton = new MainModule(); } return MainModule.singleton; } // ... public void prepare() { //System.out.println("consoles::prepare();"); this.input = new InputStream(); this.output = new PrintStream(); this.error = new PrintStream(); } public void unprepare() { this.output = null; this.input = null; this.error = null; //System.out.println("consoles::unprepare();"); } // ... public void printNewLine() { System.out.println(); } public void printString(String value) { System.out.print(value); } public void printInteger(int value) { System.out.print(value); } public void printBoolean(boolean value) { System.out.print(value); } public void scanNewLine() { // to-do: ... } public void scanString(String value) { // to-do: ... } public void scanInteger(int value) { // to-do: ... } public void scanBoolean(boolean value) { // to-do: ... } // ... } Module pattern 92

Implementation import consoles.*; class ConsoleDemo { public static MainModule console = null; public static void prepare() { console = MainModule.getSingleton(); console.prepare(); } public static void unprepare() { console.unprepare(); } public static void execute(String[] args) { console.printString("Hello World"); console.printNewLine(); console.scanNewLine(); } public static void main(String[] args) { prepare(); execute(args); unprepare(); } } C# (C Sharp .NET) C Sharp (programming language)C#, like Java, supports namespaces although the pattern remains useful in specific cases. The following example uses the singleton pattern. Definition using System; using System.IO; using System.Text; namespace Consoles { public sealed class MainModule { private static MainModule Singleton = null; public InputStream input = null; public OutputStream output = null; public ErrorStream error = null; // ... public MainModule () { // does nothing on purpose !!! } // ... public static MainModule GetSingleton() { if (MainModule.Singleton == null) { MainModule.Singleton = new MainModule(); } return MainModule.Singleton; } // ... public void Prepare() { //System.WriteLine("console::prepare();"); this.input = new InputStream(); this.output = new OutputStream(); this.error = new ErrorStream(); } public void Unprepare() { this.output = null; this.input = null; this.error = null; //System.WriteLine("console::unprepare();"); } // ... public void PrintNewLine() { System.Console.WriteLine(""); } public void PrintString(String Value) { System.Console.Write(Value); } public void PrintInteger(Integer Value) { System.Console.Write(Value); } public void PrintBoolean(Boolean Value) { System.Console.Write(Value); } public void ScanNewLine() { // to-do: ... } public void ScanString(String Value) { // to-do: ... } public void ScanInteger(Integer Value) { // to-do: ... } public void ScanBoolean(Boolean Value) { // to-do: ... } // ... } } Implementation class ConsoleDemo { public static Consoles.MainModule Console = null; public static void Prepare() { Console = Consoles.MainModule.GetSingleton(); Console.Prepare(); } public static void Unprepare() { Console.Unprepare(); } public static void Execute() { Console.PrintString("Hello World"); Console.PrintNewLine(); Console.ScanNewLine(); } public static void Main() { Prepare(); Execute(args); Unprepare(); } } Prototype-based programming languages JavaScript JavaScript is commonly used to automate web pages. Definition function ConsoleClass() { var Input = null; var Output = null; var Error = null; // ... this.prepare = function() { this.Input = new InputStream(); this.Output = new OutputStream(); this.Error = new ErrorStream(); } this.unprepare = function() { this.Input = null; this.Output = null; this.Error = null; } // ... var printNewLine = function() { // code that prints a new line } var printString = function(params) { // code that prints parameters } var printInteger = function(params) { // code that prints parameters } var printBoolean = function(params) { // code that prints parameters } var ScanNewLine = function() { // code that looks for a newline } var ScanString = function(params) { // code that inputs data into parameters } var ScanInteger = function(params) { // code that inputs data into parameters } var ScanBoolean = function(params) { // code that inputs data into parameters } // ... } Implementation function ConsoleDemo() { var Console = null; var prepare = function() { Console = new ConsoleClass(); Console.prepare(); } var unprepare = function() { Console.unprepare(); } var run = function() { Console.printString("Hello World"); Console.printNewLine(); } var main = function() { this.prepare(); this.run(); this.unprepare(); } } languages This pattern may be seen as a procedural extension to object-oriented languages. Although the procedural and modular programming paradigms are often used together, there are cases where a procedural programming language may not fully support modules, hence requiring a design pattern implementation. PHP (procedural) This example applies to procedural PHP before namespaces (introduced in version 5.3.0). It is recommended that each member of a module is given a prefix related to the filename or module name in order to avoid identifier collisions. Definition

consoledemo.php require_once("console.php"); function consoledemo_prepare() { console_prepare(); } function consoledemo_unprepare() { console_unprepare(); } function consoledemo_execute() { console_printString("Hello World"); console_printNewLine(); console_scanNewLine(); } function consoledemo_main() { consoledemo_prepare(); consoledemo_execute(); consoledemo_unprepare(); } C Note that this example applies to procedural C (language)C without namespaces. It is recommended that each member of a module is given a prefix related to the filename or module name in order to avoid identifier collisions. Definition header module // filename: "consoles.h" #include #include #include void consoles_prepare(); void consoles_unprepare(); // ... void consoles_printNewLine(); void consoles_printString(char* Value); void consoles_printInteger(int Value); void consoles_printBoolean(bool Value); void consoles_scanNewLine(); void consoles_scanString(char* Value); void consoles_scanInteger(int* Value); void consoles_scanBoolean(bool* Value); Definition body module // filename: "consoles.c" #include #include #include #include void consoles_prepare() { // code that prepares console } void consoles_unprepare() { // code that unprepares console } // ... void consoles_printNewLine() { printf("\n"); } void consoles_printString(char* Value) { printf("%s", Value); } void consoles_printInteger(int Value) { printf("%d", &Value); } void consoles_printBoolean(bool Value) { if (Value) { printf("true"); } else { printf("false"); } } void consoles_scanNewLine() { getch(); } void consoles_scanString(char* Value) { scanf("%s", Value); } void consoles_scanInteger(int* Value) { scanf("%d", Value); } void consoles_scanBoolean(bool* Value) { char temp[512]; scanf("%s", temp); *Value = (strcmp(Temp, "true") == 0); } Implementation // filename: "consoledemo.c" #include #include #include #include void consoledemo_prepare() { consoles_prepare(); } void consoledemo_unprepare() { consoles_unprepare(); } int consoledemo_execute() { consoles_printString("Hello World"); consoles_printNewLine(); consoles_scanNewLine(); return 0; } int main() { ErrorCode Result = 0; consoledemo_prepare(); ErrorCode = consoledemo_execute(); consoledemo_unprepare(); return ErrorCode; } Procedural Pascal Note that this example applies to procedural non-modular Pascal. Many Pascal dialects have namespace support, called "unit (s)". Some dialects also support initialization and finalization. If namespaces are not supported, it is recommended to give all member names a prefix related to the filename or module name in order to prevent identifier collisions. Definition unit consoles; (* filename: "consoles.pas" *) uses crt; procedure prepare(); begin (* code that prepares console *) end; procedure unprepare(); begin (* code that unprepares console *) end; // ... procedure printNewLine(); begin WriteLn(); end; procedure printString(Value: string); begin Write(Value); end; procedure printInteger(Value: integer); begin Write(Value); end; procedure printBoolean(Value: boolean); begin if (Value) then begin Write('true'); end else begin Write('false'); end; end; procedure scanNewLine(); begin SeekEoLn(); end; procedure scanString(Value: string); begin ReadLn(Value); end; procedure scanInteger(Value: Integer); begin ReadLn(Value); end; procedure scanBoolean(Value: Boolean); var temp: string; begin ReadLn(temp); if (Temp = 'true') then begin Value := true; end else begin Value := false; end; end; Implementation program consoledemo; // filename: "consoles.pas" uses consoles; procedure prepare(); begin consoles.prepare(); end; procedure unprepare(); begin consoles.unprepare(); end; function execute(): Integer; begin consoles.printString('Hello World'); consoles.printNewLine(); consoles.scanNewLine(); execute := 0; end; begin prepare(); execute(); unprepare(); end. Comparisons to other concepts Namespaces Both namespaces and modules allow to group several related entities by a single identifier, and in some situations, used interchangeably. Those entities can be globally accessed. The main purpose of both concepts is the same.In some scenarios a namespace requires that the global elements that compose it are initialized and finalized by a function or method call. In many programming languages, namespaces are not directly intended to support an initialization process nor a finalization process, and are therefore not equivalent to modules. That limitation can be worked around in two ways. In namespaces that support global functions, a function for initialization and a function for finalization are coded directly, and called directly in the main program code.Classes and namespaces Classes are used sometimes used as or with namespaces. In programming languages that don't support namespaces (e.g., JavaScript) but do support classes and objects, classes are often used to substitute for namespaces. These classes are usually not instantiated and consist exclusively of static members.Singleton classes and namespaces In object-oriented programming languages Module pattern 94

where namespaces are incompletely supported, the singleton pattern may be used instead of static members within a non-instantiable class. Relationship with other design patterns The module pattern can be implemented using a specialization of the singleton pattern. However, other design patterns may be applied and combined, in the same class. This pattern can be used as a decorator patterndecorator, a flyweight patternflyweight, or an adapter patternadapter.Module as a design pattern The Module pattern can be considered a creational pattern and a . It manages the creation and organization of other elements, and groups them as the structural pattern does. An object that applies this pattern can provide the equivalent of a namespace, providing the initialization and finalization process of a static class or a class with static members with cleaner, more concise syntax and semantics.It supports specific cases where a class or object can be considered structured, procedural data. And, vice versa, migrate structured, procedural data, and considered as object-oriented.

Proxy pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In computer programming, the proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be Forwarding (object-oriented programming)forwarding to the real object, or can provide additional logic. In the proxy, extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.Overview The Proxy design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Proxy design pattern solve? The access to an object should be controlled. Additional functionality should be provided when accessing an object. When accessing sensitive objects, for example, it should be possible to check that clients have the needed access rights. What solution does the Proxy design pattern describe?Define a separate Proxy object that can be used as substitute for another object (Subject) and implements additional functionality to control the access to this subject. This enables to work through a Proxy object to perform additional functionality when accessing a subject. For example, to check the access rights of clients accessing a sensitive object. To act as substitute for a subject, a proxy must implement the Subject interface. Clients can't tell whether they work with a subject or its proxy. See also the UML class and sequence diagram below. StructureUML class and sequence diagram A sample UML class and sequence diagram for the Proxy design pattern. In the above Unified Modeling LanguageUML Class diagramclass diagram, the Proxy class implements the Subject interface so that it can act as substitute for Subject objects. It maintains a reference (realSubject) to the substituted object (RealSubject) so that it can forward requests to it (realSubject.operation()). The sequence diagram shows the run-time interactions: The Client object works Proxy pattern 95

through a Proxy object that controls the access to a RealSubject object. In this example, the Proxy forwards the request to the RealSubject, which performs the request. Class diagram Proxy in Unified Modeling LanguageUMLProxy in Lepus3LePUS3 ( legend)Possible usage scenarios Remote proxy In distributed object communication, a local object represents a remote object (one that belongs to a different address space). The local object is a proxy for the remote object, and method invocation on the local object results in remote method invocation on the remote object. An example would be an Automated teller machineATM implementation, where the ATM might hold proxy objects for bank information that exists in the remote server. Virtual proxy In place of a complex or heavy object, a skeleton representation may be advantageous in some cases. When an underlying image is huge in size, it may be represented using a virtual proxy object, loading the real object on demand. Protection proxy A protection proxy might be used to control access to a resource based on access rights. Exampleclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Proxy implementations in various languagesPHP filename = $filename; $this->loadImageFromDisk(); } /** * Loads the image from the disk */ private function loadImageFromDisk() { echo "Loading {$this->filename}" . \PHP_EOL; } /** * Displays the image */ public function displayImage() { echo "Displaying {$this->filename}" . \PHP_EOL; } } // On System B class ProxyImage implements Image { private ?Image $image = null; private string $filename = null; public function __construct(string $filename) { $this->filename = $filename; } /** * Displays the image */ public function displayImage() { if ($this->image === null) { $this->image = new RealImage($this->filename); } $this->image->displayImage(); } } $image1 = new ProxyImage("HiRes_10MB_Photo1"); $image2 = new ProxyImage("HiRes_10MB_Photo2"); $image1->displayImage(); // Loading necessary $image1->displayImage(); // Loading unnecessary $image2->displayImage(); // Loading necessary $image2->displayImage(); // Loading unnecessary $image1->displayImage(); // Loading unnecessary The program's output is: Loading HiRes_10MB_Photo1 Displaying HiRes_10MB_Photo1 Displaying HiRes_10MB_Photo1 Loading HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo1 C# interface ICar { void DriveCar(); } // Real Object public class Car : ICar { public void DriveCar() { Console.WriteLine("Car has been driven!"); } } // Proxy Object public class ProxyCar : ICar { private Driver driver; private ICar realCar; public ProxyCar(Driver driver) { this.driver = driver; this.realCar = new Car(); } public void DriveCar() { if (driver.Age < 16) Console.WriteLine("Sorry, the driver is too young to drive."); else this.realCar.DriveCar(); } } public class Driver { public int Age { get; set; } public Driver(int age) { this.Age = age; } } // How to use above Proxy class? private void btnProxy_Click(object sender, EventArgs e) { ICar car = new ProxyCar(new Driver(15)); car.DriveCar(); car = new ProxyCar(new Driver(25)); car.DriveCar(); } Output Sorry, the driver is too young to drive. Car has been driven! Notes: A proxy may hide information about the real object to the client. A proxy may perform optimization like on demand loading. A proxy may do additional house-keeping job like audit tasks. Proxy design pattern is also known as surrogate design pattern. C++ #include #include class ICar { public: virtual ~ICar() { std::cout << "ICar destructor!" << std::endl; } virtual void DriveCar() = 0; }; class Car : public ICar { public: void DriveCar() override { std::cout << "Car has been driven!" << std::endl; } }; class ProxyCar : public ICar { public: ProxyCar(int driver_age) : driver_age_(driver_age) {} void DriveCar() override { if (driver_age_ > 16) { real_car_->DriveCar(); } else { std::cout << "Sorry, the driver is too young to drive." << std::endl; } } private: std::unique_ptr real_car_ = std::make_unique(); int driver_age_; }; int main() { std::unique_ptr car = std::make_unique(16); car->DriveCar(); car = std::make_unique(25); car->DriveCar(); } Crystal abstract class AbstractCar abstract def drive end class Car < AbstractCar def drive puts "Car has been driven!" end end class Driver getter age : Int32 def initialize(@age) end end class ProxyCar < AbstractCar private getter driver : Driver private getter real_car : AbstractCar def initialize(@driver) @real_car = Car.new end def drive if driver.age <= 16 puts "Sorry, the driver is too young to drive." else @real_car.drive end end end # Program driver = Driver.new(16) car = ProxyCar.new(driver) car.drive driver = Driver.new(25) car = ProxyCar.new(driver) car.drive Output Sorry, the driver is too young to drive. Car has Proxy pattern 96

been driven! Delphi / Object Pascal // Proxy Design pattern unit DesignPattern.Proxy; interface type // Car Interface ICar = interface procedure DriveCar; end; // TCar class, implementing ICar TCar = Class(TInterfacedObject, ICar) class function New: ICar; procedure DriveCar; End; // Driver Interface IDriver = interface function Age: Integer; end; // TDriver Class, implementing IDriver TDriver = Class(TInterfacedObject, IDriver) private FAge: Integer; public constructor Create(Age: Integer); Overload; class function New(Age: Integer): IDriver; function Age: Integer; End; // Proxy Object TProxyCar = Class(TInterfacedObject, ICar) private FDriver: IDriver; FRealCar: ICar; public constructor Create(Driver: IDriver); Overload; class function New(Driver: IDriver): ICar; procedure DriveCar; End; implementation { TCar Implementation } class function TCar.New: ICar; begin Result := Create; end; procedure TCar.DriveCar; begin WriteLn('Car has been driven!'); end; { TDriver Implementation } constructor TDriver.Create(Age: Integer); begin inherited Create; FAge := Age; end; class function TDriver.New(Age: Integer): IDriver; begin Result := Create(Age); end; function TDriver.Age: Integer; begin Result := FAge; end; { TProxyCar Implementation } constructor TProxyCar.Create(Driver: IDriver); begin inherited Create; Self.FDriver := Driver; Self.FRealCar := TCar.Create AS ICar; end; class function TProxyCar.New(Driver: IDriver): ICar; begin Result := Create(Driver); end; procedure TProxyCar.DriveCar; begin if (FDriver.Age <= 16) then WriteLn('Sorry, the driver is too young to drive.') else FRealCar.DriveCar(); end; end. Usage program Project1; {$APPTYPE Console} uses DesignPattern.Proxy in 'DesignPattern.Proxy.pas'; begin TProxyCar.New(TDriver.New(16)).DriveCar; TProxyCar.New(TDriver.New(25)).DriveCar; end. Output Sorry, the driver is too young to drive. Car has been driven! Java The following Java (programming language)Java example illustrates the "virtual proxy" pattern. The ProxyImage class is used to access a remote method. The example creates first an interface against which the pattern creates the classes. This interface contains only one method to display the image, called displayImage(), that has to be coded by all classes implementing it. The proxy class ProxyImage is running on another system than the real image class itself and can represent the real image RealImage over there. The image information is accessed from the disk. Using the proxy pattern, the code of the ProxyImage avoids multiple loading of the image, accessing it from the other system in a memory-saving manner. The lazy loading demonstrated in this example is not part of the proxy pattern, but is merely an advantage made possible by the use of the proxy. interface Image { public void displayImage(); } // On System A class RealImage implements Image { private final String filename; /** * Constructor * @param filename */ public RealImage(String filename) { this.filename = filename; loadImageFromDisk(); } /** * Loads the image from the disk */ private void loadImageFromDisk() { System.out.println("Loading " + filename); } /** * Displays the image */ public void displayImage() { System.out.println("Displaying " + filename); } } // On System B class ProxyImage implements Image { private final String filename; private RealImage image; /** * Constructor * @param filename */ public ProxyImage(String filename) { this.filename = filename; } /** * Displays the image */ public void displayImage() { if (image == null) { image = new RealImage(filename); } image.displayImage(); } } class ProxyExample { /** * Test method */ public static void main(final String[] arguments) { Image image1 = new ProxyImage("HiRes_10MB_Photo1"); Image image2 = new ProxyImage("HiRes_10MB_Photo2"); image1.displayImage(); // loading necessary image1.displayImage(); // loading unnecessary image2.displayImage(); // loading necessary image2.displayImage(); // loading unnecessary image1.displayImage(); // loading unnecessary } } The program's output is: Loading HiRes_10MB_Photo1 Displaying HiRes_10MB_Photo1 Displaying HiRes_10MB_Photo1 Loading HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo1 Python """ Proxy pattern example. """ from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." class AbstractCar: __metaclass__ = ABCMeta @abstractmethod def drive(self): raise NotImplementedError(NOT_IMPLEMENTED) class Car(AbstractCar): def drive(self) -> None: print("Car has been driven!") class Driver(object): def __init__(self, age: int) -> None: self.age = age class ProxyCar(AbstractCar): def __init__(self, driver) -> None: self.car = Car() self.driver = driver def drive(self) -> None: if self.driver.age <= 16: print("Sorry, the driver is too young to drive.") else: self.car.drive() driver = Driver(16) car = ProxyCar(driver) car.drive() driver = Driver(25) car = ProxyCar(driver) car.drive() Rust trait ICar { fn drive(&self); } struct Car {} impl ICar for Car { fn drive(&self) { println!("brum brum"); } } impl Car Proxy pattern 97

{ fn new() -> Car { Car{} } } struct ProxyCar<'a> { real_car: &'a ICar, driver_age: i32, } impl<'a> ICar for ProxyCar<'a> { fn drive(&self) { if self.driver_age > 16 { self.real_car.drive(); } else { println!("no brum brum for you") } } } impl<'a> ProxyCar<'a> { fn new(driver_age: i32, other_car: &'a ICar) -> ProxyCar { ProxyCar { real_car: other_car, driver_age: driver_age, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_can_drive() { let car = Car::new(); let proxy_car = ProxyCar::new(17, &car); proxy_car.drive(); } #[test] fn test_underage() { let car = Car::new(); let proxy_car = ProxyCar::new(16, &car); proxy_car.drive(); } } ReferencesExternal linksclass=noviewerWikimedia Commons has media related to Proxy pattern., David (February 22, 2002). "Take control with the Proxy design pattern". JavaWorld. Retrieved 2020-07-20. PerfectJPattern Open Source Project, Provides componentized implementation of the Proxy Pattern in Java Adapter vs. Proxy vs. Facade Pattern Comparison at the Wayback Machine (archived 2012-03-11) Proxy Design Pattern Proxy pattern C++ implementation example at the Wayback Machine (archived 2014-10-19) Proxy pattern description from the Portland Pattern Repository

Twin pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the is a software design pattern that allows developers to model multiple inheritance in programming languages that do not support multiple inheritance. This pattern avoids many of the problems with multiple inheritance.Definition Instead of having a single class which is derived from two super-classes, have two separate sub-classes each derived from one of the two super-classes. These two sub-classes are closely coupled, so, both can be viewed as a Twin object having two ends.Applicability The twin pattern can be used: to model multiple inheritance in a language in which multiple inheritance is not supported to avoid some problems of multiple inheritance.Structure There will be two or more parent classes which are used to be inherited. There will be sub-classes each of which is derived from one of the super-classes. The sub-classes are mutually linked via fields, and each sub-class may override the methods inherited from the super-class. New methods and fields are usually declared in one sub-class. The following diagram shows the typical structure of multiple inheritance: Typical multiple inheritanceThe following diagram shows the Twin pattern structure after replacing the previous multiple inheritance structure: Twin patternCollaborations Each child class is responsible for the protocol inherited from its parent. It handles the messages from this protocol and forwards other messages to its partner class. Clients of the twin pattern reference one of the twin objects directly and the other via its twin field.Clients that rely on the protocols of parent classes communicate with objects of the respective child class.Sample code The following code is a sketched implementation of a computer game board with moving balls. class for the game board: public class Gameboard extends Canvas { public int width, height; public GameItem firstItem; … } code sketch for GameItem class: public abstract class GameItem { Gameboard board; int posX, posY; GameItem next; public abstract void draw(); public abstract void click (MouseEvent e); public abstract boolean intersects (GameItem other); public abstract void collideWith (GameItem other); public void check() { GameItem x; for (x = board.firstItem; x != null; x = x.next) if (intersects(x)) collideWith(x); } public static BallItem newBall(int posX, int posY, int radius) {//method Twin pattern 98

of GameBoard BallItem ballItem = new BallItem(posX, posY, radius); BallThread ballThread = new BallThread(); ballItem.twin = ballThread; ballThread.twin = ballItem; return ballItem; } } code sketch for the BallItem class: public class BallItem extends GameItem { BallThread twin; int radius; int dx, dy; boolean suspended; public void draw() { board.getGraphics().drawOval(posX-radius, posY-radius, 2*radius, 2*radius); } public void move() { posX += dx; posY += dy; } public void click() { if (suspended) twin.resume(); else twin.suspend(); suspended = ! suspended; } public boolean intersects (GameItem other) { if (other instanceof Wall) return posX - radius <= other.posX && other.posX <= posX + radius || posY - radius <= other.posY && other.posY <= posY + radius; else return false; } public void collideWith (GameItem other) { Wall wall = (Wall) other; if (wall.isVertical) dx = - dx; else dy = - dy; } } Code sketch for BallThread class: public class BallThread extends Thread { BallItem twin; public void run() { while (true) { twin.draw(); /*erase*/ twin.move(); twin.draw(); } } } Implementation of the Twin pattern The following issues should be considered: Data abstraction - partner classes of the twin class have to be tightly coupled, as probably they have to access each other private fields and methods. In Java, this can be achieved by placing the partner classes into a common package and providing package visibility for the required fields and methods. In Modula-3 and in Oberon, partner classes can be placed in a common module Efficiency - Since the Twin pattern uses composition which requires message forwarding, the Twin pattern may be less efficient than inheritance. However, since multiple inheritance is slightly less efficient than single inheritance anyway, the overhead will not be a major problem.References

Blackboard (design pattern)

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the blackboard pattern is a behavioral design pattern that provides a computational framework for the design and implementation of systems that integrate large and diverse specialized modules, and implement complex, non-deterministic control strategies.This pattern was identified by the members of the HEARSAY-II project and first applied to speech recognition.Structure The blackboard model defines three main components: blackboard - a structured global memory containing objects from the solution space knowledge sources - specialized modules with their own representation control component - selects, configures and executes modules.Implementation The first step is to design the solution space (i.e. potential solutions) that leads to the blackboard structure. Then, knowledge sources are identified. These two activities are closely related.The next step is to specify the control component; it generally takes the form of a complex scheduler that makes use of a set of domain-specific heuristics to rate the relevance of executable knowledge sources.System StructureApplications Usage-domains include: speech recognition vehicle identification and tracking protein structure identification sonar signals interpretation.Consequences The blackboard pattern provides effective solutions for designing and implementing complex systems where heterogeneous modules have to be dynamically combined to solve a problem. This provides non-functional properties such as: reusability changeability robustness.The blackboard pattern allows multiple processes to work closer together on separate threads, polling and reacting when necessary.ExampleAn example of the Blackboard pattern has been provided by Microsoft. Blackboard (design pattern) 99

https://social.technet.microsoft.com/wiki/contents/articles/13461.blackboard-design-pattern-a-practical-example-radar-defense-system.aspxReferences

Chain of responsibility pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In object-oriented design, the chain-of-responsibility pattern is a design pattern (computer science)design pattern consisting of a source of Command patterncommand objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. Thus, the chain of responsibility is an object oriented version of the if ... else if ... else if ...... else ... endif idiom, with the benefit that the condition–action blocks can be dynamically rearranged and reconfigured at runtime.In a variation of the standard chain-of-responsibility model, some handlers may act as dynamic dispatchdispatchers, capable of sending commands out in a variety of directions, forming a tree of responsibility. In some cases, this can occur recursively, with processing objects calling higher-up processing objects with commands that attempt to solve some smaller part of the problem; in this case recursion continues until the command is processed, or the entire tree has been explored. An XML Interpreter (computing)interpreter might work in this manner.This pattern promotes the idea of loose coupling. The chain-of-responsibility pattern is structurally nearly identical to the decorator pattern, the difference being that for the decorator, all classes handle the request, while for the chain of responsibility, exactly one of the classes in the chain handles the request. This is a strict definition of the Responsibility concept in the Design PatternsGoF book. However, many implementations (such as loggers below, or UI event handling, or servlet filters in Java, etc) allow several elements in the chain to take responsibility. Overview The Chain of Responsibility design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe common solutions to recurring design problems when designing flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Chain of Responsibility design pattern solve? Coupling the sender of a request to its receiver should be avoided. It should be possible that more than one receiver can handle a request. Implementing a request directly within the class that sends the request is inflexible because it couples the class to a particular receiver and makes it impossible to support multiple receivers. What solution does the Chain of Responsibility design pattern describe? Define a chain of receiver objects having the responsibility, depending on run-time conditions, to either handle a request or forward it to the next receiver on the chain (if any). This enables to send a request to a chain of receivers without having to know which one handles the request. The request gets passed along the chain until a receiver handles the request. The sender of a request is no longer coupled to a particular receiver. See also the UML class and sequence diagram below. Structure UML class and sequence diagram A sample UML class and sequence diagram for the Chain of Responsibility design pattern. In the above Unified Modeling LanguageUML class diagram, the Sender class doesn't refer to a particular receiver class directly. Instead, Sender refers to the Handler interface for handling a request (handler.handleRequest()), which makes the Sender independent of which receiver handles the request. The Receiver1, Receiver2, and Receiver3 classes implement the Handler interface by either handling or forwarding a request (depending on run-time Chain of responsibility pattern 100

conditions). The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: In this example, the Sender object calls handleRequest() on the receiver1 object (of type Handler). The receiver1 forwards the request to receiver2, which in turn forwards the request to receiver3, which handles (performs) the request. Example class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Chain-of-responsibility implementations in various languagesJava example Below is an example of this pattern in Java. A logger is created using a chain of loggers, each one configured with different log levels. import java.util.Arrays; import java.util.EnumSet; import java.util.function.Consumer; @FunctionalInterface public interface Logger { public enum LogLevel { INFO, DEBUG, WARNING, ERROR, FUNCTIONAL_MESSAGE, FUNCTIONAL_ERROR; public static LogLevel[] all() { return values(); } } abstract void message(String msg, LogLevel severity); default Logger appendNext(Logger nextLogger) { return (msg, severity) -> { message(msg, severity); nextLogger.message(msg, severity); }; } static Logger writeLogger(LogLevel[] levels, Consumer stringConsumer) { EnumSet set = EnumSet.copyOf(Arrays.asList(levels)); return (msg, severity) -> { if (set.contains(severity)) { stringConsumer.accept(msg); } }; } static Logger consoleLogger(LogLevel... levels) { return writeLogger(levels, msg -> System.err.println("Writing to console: " + msg)); } static Logger emailLogger(LogLevel... levels) { return writeLogger(levels, msg -> System.err.println("Sending via : " + msg)); } static Logger fileLogger(LogLevel... levels) { return writeLogger(levels, msg -> System.err.println("Writing to Log File: " + msg)); } public static void main(String[] args) { // Build an immutable chain of responsibility Logger logger = consoleLogger(LogLevel.all()) .appendNext(emailLogger(LogLevel.FUNCTIONAL_MESSAGE, LogLevel.FUNCTIONAL_ERROR)) .appendNext(fileLogger(LogLevel.WARNING, LogLevel.ERROR)); // Handled by consoleLogger since the console has a LogLevel of all logger.message("Entering function ProcessOrder().", LogLevel.DEBUG); logger.message("Order record retrieved.", LogLevel.INFO); // Handled by consoleLogger and emailLogger since emailLogger implements Functional_Error & Functional_Error logger.message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel.FUNCTIONAL_ERROR); logger.message("Order Dispatched.", LogLevel.FUNCTIONAL_MESSAGE); // Handled by consoleLogger and fileLogger since fileLogger implements Warning & Error logger.message("Customer Address details missing in Branch DataBase.", LogLevel.WARNING); logger.message("Customer Address details missing in Organization DataBase.", LogLevel.ERROR); } } C# example This C# examples uses the logger application to select different sources based on the log level; namespace ChainOfResponsibility { [Flags] public enum LogLevel { None = 0, // 0 Info = 1, // 1 Debug = 2, // 10 Warning = 4, // 100 Error = 8, // 1000 FunctionalMessage = 16, // 10000 FunctionalError = 32, // 100000 All = 63 // 111111 } ///

/// Abstract Handler in chain of responsibility pattern. /// public abstract class Logger { protected LogLevel logMask; // The next Handler in the chain protected Logger next; public Logger(LogLevel mask) { this.logMask = mask; } /// /// Sets the Next logger to make a list/chain of Handlers. /// public Logger SetNext(Logger nextlogger) { Logger lastLogger = this; while (lastLogger.next != null) { lastLogger = lastLogger.next; } lastLogger.next = nextlogger; return this; } public void Message(string msg, LogLevel severity) { if ((severity & logMask) != 0) // True only if any of the logMask bits are set in severity { WriteMessage(msg); } if (next != null) { next.Message(msg, severity); } } abstract protected void WriteMessage(string msg); } public class ConsoleLogger : Logger { public ConsoleLogger(LogLevel mask) : base(mask) { } protected override void WriteMessage(string msg) { Console.WriteLine("Writing to console: " + msg); } } public class EmailLogger : Logger { public EmailLogger(LogLevel mask) : base(mask) { } protected override void WriteMessage(string msg) { // Placeholder for send logic, usually the email configurations are saved in config file. Console.WriteLine("Sending via email: " + msg); } } class FileLogger : Logger { public FileLogger(LogLevel mask) : base(mask) { } protected override void WriteMessage(string msg) { // Placeholder for File writing logic Console.WriteLine("Writing to Log File: " + msg); } } public class Program { public static void Main(string[] args) { // Build the chain of responsibility Logger logger; logger = new ConsoleLogger(LogLevel.All) .SetNext(new EmailLogger(LogLevel.FunctionalMessage | LogLevel.FunctionalError)) .SetNext(new FileLogger(LogLevel.Warning | LogLevel.Error)); // Handled by ConsoleLogger since the console has a loglevel of Chain of responsibility pattern 101

all logger.Message("Entering function ProcessOrder().", LogLevel.Debug); logger.Message("Order record retrieved.", LogLevel.Info); // Handled by ConsoleLogger and FileLogger since filelogger implements Warning & Error logger.Message("Customer Address details missing in Branch DataBase.", LogLevel.Warning); logger.Message("Customer Address details missing in Organization DataBase.", LogLevel.Error); // Handled by ConsoleLogger and EmailLogger as it implements functional error logger.Message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel.FunctionalError); // Handled by ConsoleLogger and EmailLogger logger.Message("Order Dispatched.", LogLevel.FunctionalMessage); } } } /* Output Writing to console: Entering function ProcessOrder(). Writing to console: Order record retrieved. Writing to console: Customer Address details missing in Branch DataBase. Writing to Log File: Customer Address details missing in Branch DataBase. Writing to console: Customer Address details missing in Organization DataBase. Writing to Log File: Customer Address details missing in Organization DataBase. Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1. Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1. Writing to console: Order Dispatched. Sending via email: Order Dispatched. */ Crystal example enum LogLevel None Info Debug Warning Error FunctionalMessage FunctionalError All end abstract class Logger property log_levels property next : Logger | Nil def initialize(*levels) @log_levels = [] of LogLevel levels.each do |level| @log_levels << level end end def message(msg : String, severity : LogLevel) if @log_levels.includes?(LogLevel::All) || @log_levels.includes?(severity) write_message(msg) end @next.try(&.message(msg, severity)) end abstract def write_message(msg : String) end class ConsoleLogger < Logger def write_message(msg : String) puts "Writing to console: #{msg}" end end class EmailLogger < Logger def write_message(msg : String) puts "Sending via email: #{msg}" end end class FileLogger < Logger def write_message(msg : String) puts "Writing to Log File: #{msg}" end end # Program # Build the chain of responsibility logger = ConsoleLogger.new(LogLevel::All) logger1 = logger.next = EmailLogger.new(LogLevel::FunctionalMessage, LogLevel::FunctionalError) logger2 = logger1.next = FileLogger.new(LogLevel::Warning, LogLevel::Error) # Handled by ConsoleLogger since the console has a loglevel of all logger.message("Entering function ProcessOrder().", LogLevel::Debug) logger.message("Order record retrieved.", LogLevel::Info) # Handled by ConsoleLogger and FileLogger since filelogger implements Warning & Error logger.message("Customer Address details missing in Branch DataBase.", LogLevel::Warning) logger.message("Customer Address details missing in Organization DataBase.", LogLevel::Error) # Handled by ConsoleLogger and EmailLogger as it implements functional error logger.message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel::FunctionalError) # Handled by ConsoleLogger and EmailLogger logger.message("Order Dispatched.", LogLevel::FunctionalMessage) Output Writing to console: Entering function ProcessOrder(). Writing to console: Order record retrieved. Writing to console: Customer Address details missing in Branch DataBase. Writing to Log File: Customer Address details missing in Branch DataBase. Writing to console: Customer Address details missing in Organization DataBase. Writing to Log File: Customer Address details missing in Organization DataBase. Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1. Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1. Writing to console: Order Dispatched. Sending via email: Order Dispatched. Python example """ Chain of responsibility pattern example. """ from abc import ABCMeta, abstractmethod from enum import Enum, auto class LogLevel(Enum): """ Log Levels Enum.""" NONE = auto() INFO = auto() DEBUG = auto() WARNING = auto() ERROR = auto() FUNCTIONAL_MESSAGE = auto() FUNCTIONAL_ERROR = auto() ALL = auto() class Logger(object): """Abstract handler in chain of responsibility pattern.""" __metaclass__ = ABCMeta next = None def __init__(self, levels) -> None: """Initialize new logger. Arguments: levels (list[str]): List of log levels. """ self.log_levels = [] for level in levels: self.log_levels.append(level) def set_next(self, next_logger: Logger): """Set next responsible logger in the chain. Arguments: next_logger (Logger): Next responsible logger. Returns: Logger: Next responsible logger. """ self.next = next_logger return self.next def message(self, msg: str, severity: LogLevel) -> None: """Message writer handler. Arguments: msg (str): Message string. severity (LogLevel): Severity of message as log level enum. """ if LogLevel.ALL in self.log_levels or severity in self.log_levels: self.write_message(msg) if self.next is not None: self.next.message(msg, severity) @abstractmethod def write_message(self, msg: str) -> None: """Abstract method to Chain of responsibility pattern 102

write a message. Arguments: msg (str): Message string. Raises: NotImplementedError """ raise NotImplementedError("You should implement this method.") class ConsoleLogger(Logger): def write_message(self, msg: str) -> None: """Overrides parent's abstract method to write to console. Arguments: msg (str): Message string. """ print("Writing to console:", msg) class EmailLogger(Logger): """Overrides parent's abstract method to send an email. Arguments: msg (str): Message string. """ def write_message(self, msg: str) -> None: print(f"Sending via email: {msg}") class FileLogger(Logger): """Overrides parent's abstract method to write a file. Arguments: msg (str): Message string. """ def write_message(self, msg: str) -> None: print(f"Writing to log file: {msg}") def main(): """Building the chain of responsibility.""" logger = ConsoleLogger([LogLevel.ALL]) email_logger = logger.set_next( EmailLogger([LogLevel.FUNCTIONAL_MESSAGE, LogLevel.FUNCTIONAL_ERROR]) ) # As we don't need to use file logger instance anywhere later # We will not set any value for it. email_logger.set_next( FileLogger([LogLevel.WARNING, LogLevel.ERROR]) ) # ConsoleLogger will handle this part of code since the message # has a log level of all logger.message("Entering function ProcessOrder().", LogLevel.DEBUG) logger.message("Order record retrieved.", LogLevel.INFO) # ConsoleLogger and FileLogger will handle this part since file logger # implements WARNING and ERROR logger.message( "Customer Address details missing in Branch DataBase.", LogLevel.WARNING ) logger.message( "Customer Address details missing in Organization DataBase.", LogLevel.ERROR ) # ConsoleLogger and EmailLogger will handle this part as they implement # functional error logger.message( "Unable to Process Order ORD1 Dated D1 for customer C1.", LogLevel.FUNCTIONAL_ERROR ) logger.message("OrderDispatched.", LogLevel.FUNCTIONAL_MESSAGE) if __name__ == "__main__": main() Implementations Cocoa and Cocoa Touch The Cocoa (API)Cocoa and Cocoa Touch frameworks, used for OS X and iOS applications respectively, actively use the chain-of-responsibility pattern for handling events. Objects that participate in the chain are called responder objects, inheriting from the NSResponder (OS X)/UIResponder (iOS) class. All view objects (NSView/UIView), view controller objects (NSViewController/UIViewController), window objects (NSWindow/UIWindow), and the application object (NSApplication/UIApplication) are responder objects.Typically, when a view receives an event which it can't handle, it dispatches it to its superview until it reaches the view controller or window object. If the window can't handle the event, the event is dispatched to the application object, which is the last object in the chain. For example: On OS X, moving a textured window with the mouse can be done from any location (not just the title bar), unless on that location there's a view which handles dragging events, like slider controls. If no such view (or superview) is there, dragging events are sent up the chain to the window which does handle the dragging event. On iOS, it's typical to handle view events in the view controller which manages the view hierarchy, instead of subclassing the view itself. Since a view controller lies in the responder chain after all of its managed subviews, it can intercept any view events and handle them. References 103 Command pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In object-oriented programming, the command pattern is a Behavioral patternbehavioral Design pattern (computer science)design pattern in which an object is used to Information hidingencapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.Four terms always associated with the command pattern are command, receiver, invoker and client. A command object knows about receiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command. The receiver object to execute these methods is also stored in the command object by Object composition#Aggregationaggregation. The receiver then does the work when the execute() method in command is called. An invoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about the command interface. Invoker object(s), command objects and receiver objects are held by a client object, the client decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the class of the method or the method parameters. Using an invoker object allows bookkeeping about command executions to be conveniently performed, as well as implementing different modes for commands, which are managed by the invoker object, without the need for the client to be aware of the existence of bookkeeping or modes. The central ideas of this design pattern closely mirror the semantics of first-class functions and higher-order functions in functional programming languages. Specifically, the invoker object is a higher-order function of which the command object is a first-class argument. Overview The Command design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. Using the Command design pattern can solve these problems: Coupling the invoker of a request to a particular request should be avoided. That is, hard-wired requests should be avoided. It should be possible to configure an object (that invokes a request) with a request. Implementing (hard-wiring) a request directly into a class is inflexible because it couples the class to a particular request at compile-time, which makes it impossible to specify a request at run-time. Using the Command design pattern describes the following solution: Define separate (command) objects that encapsulate a request. A class delegates a request to a command object instead of implementing a particular request directly. This enables one to configure a class with a command object that is used to perform a request. The class is no longer coupled to a particular request and has no knowledge (is independent) of how the request is carried out. See also the UML class and sequence diagram below. Structure UML class and sequence diagram A sample UML class and sequence diagram for the Command design pattern. In the above Unified Modeling LanguageUML class diagram, the Invoker class doesn't implement a request directly. Instead, Invoker refers to the Command interface to perform a request (command.execute()), which makes the Invoker independent of how the request is performed. The Command1 class implements the Command interface by performing an action on a receiver (receiver1.action1()). The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: The Invoker object calls execute() on a Command1 object. Command1 calls action1() on a Receiver1 object, which Command pattern 104

performs the request. UML class diagram UML diagram of the command patternUses GUI buttons and menu items In (Java)Swing and Borland Delphi programming, an Action is a command object. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Action object. Macro (computer science)Macro recording If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then "play back" the same actions by executing the same command objects again in sequence. If the program embeds a scripting engine, each command object can implement a toScript() method, and user actions can then be easily recorded as scripts. Code MobilityMobile Code Using languages such as Java where code can be streamed/slurped from one location to another via URLClassloaders and Codebases the commands can enable new behavior to be delivered to remote locations (EJB Command, Master Worker). Multi-level undo If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method. Networking It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games. Parallel Processing Where the commands are written as tasks to a shared resource and executed by many threads in parallel (possibly on remote machines -this variant is often referred to as the Master/Worker pattern) Progress bars Suppose a program has a sequence of commands that it executes in order. If each command object has a getEstimatedDuration() method, the program can easily estimate the total duration. It can show a progress bar that meaningfully reflects how close the program is to completing all the tasks. Thread pools A typical, general-purpose class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. The items in the queue are command objects. Typically these objects implement a common interface such as java.lang.Runnable that allows the thread pool to execute the command even though the thread pool class itself was written without any knowledge of the specific tasks for which it would be used. database transactionTransactional behavior Similar to undo, a database engine or software installer may keep a list of operations that have been or will be performed. Should one of them fail, all others can be reversed or discarded (usually called rollback). For example, if two database tables that refer to each other must be updated, and the second update fails, the transaction can be rolled back, so that the first table does not now contain an invalid reference.wizard (software)Wizards Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the "Finish" button on the last page. In these cases, a natural way to separate code from application code is to implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. "Finish" simply triggers a call to execute(). This way, the command class will work. Terminology The terminology used to describe command pattern implementations is not consistent and can therefore be confusing. This is the result of ambiguity, the use of synonyms, and implementations that may obscure the original pattern by going well beyond it. Ambiguity. The term command is ambiguous. For example, move up, move up may refer to a single (move up) command that should be executed twice, or it may refer to two commands, each of which happens to do the same thing (move up). If the former command is added twice to an undo stack, both items on the stack refer to the same command instance. This may be appropriate when a command can always be undone the same way (e.g. move down). Both the Gang of Four (software)Gang of Four and the Command pattern#JavaJava example below use this interpretation of the term command. On the other hand, if the latter commands are added to an undo stack, the stack refers to two separate objects. This may be appropriate when each object on the stack must contain information that allows the command to be undone. For example, to undo a delete selection command, the object may contain a copy of the deleted text so that it can be re-inserted, if the delete selection command must be undone. Note that using Command pattern 105

a separate object for each invocation of a command is also an example of the chain of responsibility pattern. The term execute is also ambiguous. It may refer to running the code identified by the command object's execute method. However, in Microsoft's Windows Presentation Foundation a command is considered to have been executed when the command's execute method has been invoked, but that does not necessarily mean that the application code has run. That occurs only after some further event processing. Synonyms and homonyms. Client, Source, Invoker: the button, toolbar button, or menu item clicked, the shortcut key pressed by the user.Command Object, Routed Command Object, Action Object: a singleton object (e.g. there is only one CopyCommand object), which knows about shortcut keys, button images, command text, etc. related to the command. A source/invoker object calls the Command/Action object's execute/performAction method. The Command/Action object notifies the appropriate source/invoker objects when the availability of a command/action has changed. This allows buttons and menu items to become inactive (grayed out) when a command/action cannot be executed/performed.Receiver, Target Object: the object that is about to be copied, pasted, moved, etc. The receiver object owns the method that is called by the command's execute method. The receiver is typically also the target object. For example, if the receiver object is a cursor and the method is called moveUp, then one would expect that the cursor is the target of the moveUp action. On the other hand, if the code is defined by the command object itself, the target object will be a different object entirely.Command Object, routed event arguments, event object: the object that is passed from the source to the Command/Action object, to the Target object to the code that does the work. Each button click or shortcut key results in a new command/event object. Some implementations add more information to the command/event object as it is being passed from one object (e.g. CopyCommand) to another (e.g. document section). Other implementations put command/event objects in other event objects (like a box inside a bigger box) as they move along the line, to avoid naming conflicts. (See also chain of responsibility pattern.)Handler, ExecutedRoutedEventHandler, method, function: the actual code that does the copying, pasting, moving, etc. In some implementations the handler code is part of the command/action object. In other implementations the code is part of the Receiver/Target Object, and in yet other implementations the handler code is kept separate from the other objects.Command Manager, Undo Manager, Scheduler, Queue, Dispatcher, Invoker: an object that puts command/event objects on an undo stack or redo stack, or that holds on to command/event objects until other objects are ready to act on them, or that routes the command/event objects to the appropriate receiver/target object or handler code. Implementations that go well beyond the original command pattern. Microsoft's Windows Presentation Foundation (WPF), introduces routed commands, which combine the command pattern with event processing. As a result, the command object no longer contains a reference to the target object nor a reference to the application code. Instead, invoking the command object's execute command results in a so-called Executed Routed Event that during the event's tunneling or bubbling may encounter a so-called binding object that identifies the target and the application code, which is executed at that point.Example Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off. A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light. The Switch in the following C# implementation turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine. Go The following code is an implementation of Command pattern in Go. // package room package room import "fmt" //light - Receiver type Light struct{} func (l *Light) TurnOn() { fmt.Println("The light is on") } func (l *Light) TurnOff() { fmt.Println("The light is off") } //Command - Command Interface type Command interface { execute() } //SwitchOnCommand - ConcreteCommand(The Command for turning on the light) type SwitchOnCommand struct { Light *Light } func (cmd *SwitchOnCommand) execute() { cmd.Light.TurnOn() } //SwitchOffCommand - ConcreteCommand(The Command for turning off the light) type SwitchOffCommand struct { Light *Light } func (cmd *SwitchOffCommand) execute() { cmd.Light.TurnOff() } //Switch - The invoker struct type Switch struct { commands []Command } //StoreAndExecute func (sw *Switch) StoreAndExecute(cmd Command) { sw.commands = append(sw.commands, cmd) cmd.execute() } // package main package main import "github.com/tkstorm/go-design/behavioral/command/room" func main() { // Receiver lamp := new(room.Light) // Command pattern 106

ConcreteCommand switchOn := &room.SwitchOnCommand{Light: lamp} switchOff := &room.SwitchOffCommand{Light: lamp} // Invoker mySwitch := new(room.Switch) mySwitch.StoreAndExecute(switchOn) mySwitch.StoreAndExecute(switchOff) } C# The following code is an implementation of Command pattern in C#. using System; namespace CommandPattern { public interface ICommand { void Execute(); } /* The Invoker class */ public class Switch { ICommand _closedCommand; ICommand _openedCommand; public Switch(ICommand closedCommand, ICommand openedCommand) { this._closedCommand = closedCommand; this._openedCommand = openedCommand; } // Close the circuit / power on public void Close() { this._closedCommand.Execute(); } // Open the circuit / power off public void Open() { this._openedCommand.Execute(); } } /* An interface that defines actions that the receiver can perform */ public interface ISwitchable { void PowerOn(); void PowerOff(); } /* The Receiver class */ public class Light : ISwitchable { public void PowerOn() { Console.WriteLine("The light is on"); } public void PowerOff() { Console.WriteLine("The light is off"); } } /* The Command for turning off the device - ConcreteCommand #1 */ public class CloseSwitchCommand : ICommand { private ISwitchable _switchable; public CloseSwitchCommand(ISwitchable switchable) { _switchable = switchable; } public void Execute() { _switchable.PowerOff(); } } /* The Command for turning on the device - ConcreteCommand #2 */ public class OpenSwitchCommand : ICommand { private ISwitchable _switchable; public OpenSwitchCommand(ISwitchable switchable) { _switchable = switchable; } public void Execute() { _switchable.PowerOn(); } } /* The test class or client */ internal class Program { public static void Main(string[] arguments) { string argument = arguments.Length > 0 ? arguments[0].ToUpper() : null; ISwitchable lamp = new Light(); // Pass reference to the lamp instance to each command ICommand switchClose = new CloseSwitchCommand(lamp); ICommand switchOpen = new OpenSwitchCommand(lamp); // Pass reference to instances of the Command objects to the switch Switch @switch = new Switch(switchClose, switchOpen); if (argument == "ON") { // Switch (the Invoker) will invoke Execute() on the command object. @switch.Open(); } else if (argument == "OFF") { // Switch (the Invoker) will invoke the Execute() on the command object. @switch.Close(); } else { Console.WriteLine("Argument \"ON\" or \"OFF\" is required."); } } } }Java In order to associate a name to an action to execute, the actions (switch on, switch off) on a lamp are wrapped into instances of the classes SwitchOnCommand and SwitchOffCommand, both implementing the interface Command. import java.util.HashMap; /** The Command interface */ interface Command { void execute(); } /** The Invoker class */ class Switch { private final HashMap commandMap = new HashMap<>(); public void register(String commandName, Command command) { commandMap.put(commandName, command); } public void execute(String commandName) { Command command = commandMap.get(commandName); if (command == null) { throw new IllegalStateException("no command registered for " + commandName); } command.execute(); } } /** The Receiver class */ class Light { public void turnOn() { System.out.println("The light is on"); } public void turnOff() { System.out.println("The light is off"); } } /** The Command for turning on the light - ConcreteCommand #1 */ class SwitchOnCommand implements Command { private final Light light; public SwitchOnCommand(Light light) { this.light = light; } @Override // Command public void execute() { light.turnOn(); } } /** The Command for turning off the light - ConcreteCommand #2 */ class SwitchOffCommand implements Command { private final Light light; public SwitchOffCommand(Light light) { this.light = light; } @Override // Command public void execute() { light.turnOff(); } } public class CommandDemo { public static void main(final String[] arguments) { Light lamp = new Light(); Command switchOn = new SwitchOnCommand(lamp); Command switchOff = new SwitchOffCommand(lamp); Switch mySwitch = new Switch(); mySwitch.register("on", switchOn); mySwitch.register("off", switchOff); mySwitch.execute("on"); mySwitch.execute("off"); } } Using a functional interface Since Java 8, it's not necessary to create the classes SwitchOnCommand and SwitchOffCommand anymore, one can use instead the :: operator as shown in the example below public class CommandDemo { public static void main(final String[] arguments) { Light lamp = new Light(); Command switchOn = lamp::turnOn; Command switchOff = lamp::turnOff; Switch mySwitch = new Switch(); mySwitch.register("on", switchOn); mySwitch.register("off", switchOff); mySwitch.execute("on"); mySwitch.execute("off"); } } Python The following code is an implementation of Command pattern in Python Command pattern 107

(programming language)Python. from collections import deque class Switch(object): """The INVOKER class""" def __init__(self) -> None: self._history = deque() @property def history(self): return self._history def execute(self, command) -> None: self._history.appendleft(command) command.execute() class Command(object): """The COMMAND interface""" def __init__(self, obj) -> None: self._obj = obj def execute(self): raise NotImplementedError class TurnOnCommand(Command): """The COMMAND for turning on the light""" def execute(self) -> None: self._obj.turn_on() class TurnOffCommand(Command): """The COMMAND for turning off the light""" def execute(self) -> None: self._obj.turn_off() class Light(object): """The RECEIVER class""" def turn_on(self) -> None: print("The light is on") def turn_off(self) -> None: print("The light is off") class LightSwitchClient(object): """The CLIENT class""" def __init__(self) -> None: self._lamp = Light() self._switch = Switch() @property def switch(self): return self._switch def press(self, cmd: str) -> None: cmd = cmd.strip().upper() if cmd == "ON": self._switch.execute(TurnOnCommand(self._lamp)) elif cmd == "OFF": self._switch.execute(TurnOffCommand(self._lamp)) else: print("Argument 'ON' or 'OFF' is required.") # Execute if this file is run as a script and not imported as a module if __name__ == "__main__": light_switch = LightSwitchClient() print("Switch ON test.") light_switch.press("ON") print("Switch OFF test.") light_switch.press("OFF") print("Invalid Command test.") light_switch.press("****") print("Command history:") print(light_switch.switch.history) Ruby # Invoker class Switch attr_reader :history def execute(cmd) @history ||= [] @history << cmd.execute end end # Command Interface class Command attr_reader :obj def initialize(obj) @obj = obj end def execute raise NotImplementedError end end # Command for turning on class TurnOnCommand < Command def execute obj.turn_on end end # Command for turning off class TurnOffCommand < Command def execute obj.turn_off end end # Receiver class Light def turn_on 'the light is on' end def turn_off 'the light is off' end end # Client class LightSwitchClient attr_reader :switch def initialize @lamp = Light.new @switch = Switch.new end def switch_for(cmd) case cmd when 'on' then @switch.execute(TurnOnCommand.new(@lamp)) when 'off' then @switch.execute(TurnOffCommand.new(@lamp)) else puts 'Sorry, I so sorry' end end end client = LightSwitchClient.new client.switch_for('on') client.switch_for('off') client.switch.history #=> ['the light is on', 'the light is off'] Scala /* The Command interface */ trait Command { def execute() } /* The Invoker class */ class Switch { private var history: List[Command] = Nil def storeAndExecute(cmd: Command) { cmd.execute() this.history :+= cmd } } /* The Receiver class */ class Light { def turnOn() = println("The light is on") def turnOff() = println("The light is off") } /* The Command for turning on the light - ConcreteCommand #1 */ class FlipUpCommand(theLight: Light) extends Command { def execute() = theLight.turnOn() } /* The Command for turning off the light - ConcreteCommand #2 */ class FlipDownCommand(theLight: Light) extends Command { def execute() = theLight.turnOff() } /* The test class or client */ object PressSwitch { def main(arguments: Array[String]) { val lamp = new Light() val switchUp = new FlipUpCommand(lamp) val switchDown = new FlipDownCommand(lamp) val s = new Switch() try { arguments(0).toUpperCase match { case "ON" => s.storeAndExecute(switchUp) case "OFF" => s.storeAndExecute(switchDown) case _ => println("Argument \"ON\" or \"OFF\" is required.") } } catch { case e: Exception => println("Arguments required.") } } } JavaScript The following code is an implementation of Command pattern in JavaScript. /* The Invoker function */ "use strict"; class Switch { constructor() { this._commands = []; } storeAndExecute(command) { this._commands.push(command); command.execute(); } } class Light { turnOn() { console.log('turn on') } turnOff() { console.log('turn off') } } class FlipDownCommand { constructor(light) { this._light = light; } execute() { this._light.turnOff(); } } class FlipUpCommand { constructor(light) { this._light = light; } execute() { this._light.turnOn(); } } var light = new Light(); var switchUp = new FlipUpCommand(light); var switchDown = new FlipDownCommand(light); var switcher = new Switch(); switcher.storeAndExecute(switchUp); switcher.storeAndExecute(switchDown); CoffeeScript The following code is an implementation of Command pattern in CoffeeScript. # The Invoker function class Switch _commands = [] storeAndExecute: (command) -> _commands.push(command) command.execute() # The Receiver function class Light turnOn: -> console.log ('turn on') turnOff: -> console.log ('turn off') # The Command for turning on the light - ConcreteCommand #1 class FlipUpCommand constructor: (@light) -> execute: -> @light.turnOn() # The Command for turning off the light - ConcreteCommand #2 class FlipDownCommand Command pattern 108

constructor: (@light) -> execute: -> @light.turnOff() light = new Light() switchUp = new FlipUpCommand(light) switchDown = new FlipDownCommand(light) switcher = new Switch() switcher.storeAndExecute(switchUp) switcher.storeAndExecute(switchDown) C++ #include #include class ICommand { public: virtual ~ICommand() = default; virtual void execute() = 0; }; class Switch { private: std::queue commands_; public: void storeAndExecute(ICommand *command) { if (command) { commands_.push(command); command->execute(); commands_.pop(); } } }; class Light { public: void turnOn() { std::cout << "The light is on." << std::endl; } void turnOff() { std::cout << "The light is off." << std::endl; } }; // The Command for turning on the light - ConcreteCommand #1 class SwitchOnCommand: public ICommand { private: Light *light_; public: SwitchOnCommand(Light *light) : light_(light) { } void execute() { light_->turnOn(); } }; // The Command for turning off the light - ConcreteCommand #2 class SwitchOffCommand: public ICommand { private: Light *light_; public: SwitchOffCommand(Light *light) : light_(light) { } void execute() { light_->turnOff(); } }; int main() { Light light = Light(); SwitchOnCommand onCommand(&light); SwitchOffCommand offCommand(&light); ICommand *switchOn = &onCommand; ICommand *switchOff = &offCommand; Switch switcher = Switch(); switcher.storeAndExecute(switchOn); switcher.storeAndExecute(switchOff); } ReferencesExternal linksclass=noviewerWikimedia Commons has media related to Command pattern.class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Command implementations in various languages Command Pattern Java Tip 68: Learn how to implement the Command pattern in Java

Interpreter pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In computer programming, the is a design pattern (computer science)design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a Class (computer science)class for each (Terminal symbolterminal or Nonterminal symbolnonterminal) in a Domain specific languagesspecialized computer language. The abstract syntax treesyntax tree of a sentence in the language is an instance of the composite patterncomposite pattern and is used to evaluate (interpret) the sentence for a client.:243 See also Composite pattern. Overview The Interpreter design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Interpreter design pattern solve? A Backus-Naur formgrammar for a simple language should be defined so that sentences in the language can be interpreted. When a problem occurs very often, it could be considered to represent it as a sentence in a simple language (Domain-specific languageDomain Specific Languages) so that an interpreter can solve the problem by interpreting the sentence. For example, when many different or complex search expressions must be specified. Implementing (hard-wiring) them directly into a class is inflexible because it commits the class to particular expressions and makes it impossible to specify new expressions or change existing ones independently from (without having to change) the class. What solution does the Interpreter design pattern describe? Define a grammar for a simple language by defining an Expression class hierarchy and implementing an interpret() operation. Represent a Interpreter pattern 109

sentence in the language by an abstract syntax tree (AST) made up of Expression instances. Interpret a sentence by calling interpret() on the AST. The expression objects are composed recursively into a composite/tree structure that is called abstract syntax tree (see Composite pattern). The Interpreter pattern doesn't describe how to build an abstract syntax tree. This can be done either manually by a client or automatically by a parser. See also the UML class and object diagram below. Uses Specialized database query languages such as SQL. Specialized computer languages that are often used to describe communication protocols. Most general-purpose computer languages actually incorporate several specialized languages. Structure UML class and object diagram A sample UML class and object diagram for the Interpreter design pattern. In the above Unified Modeling LanguageUML Class diagramclass diagram, the Client class refers to the common AbstractExpression interface for interpreting an expression interpret(context). The TerminalExpression class has no children and interprets an expression directly. The NonTerminalExpression class maintains a container of child expressions (expressions) and forwards interpret requests to these expressions. The object collaboration diagram shows the run-time interactions: The Client object sends an interpret request to the abstract syntax tree. The request is forwarded to (performed on) all objects downwards the tree structure. The NonTerminalExpression objects (ntExpr1,ntExpr2) forward the request to their child expressions. The TerminalExpression objects (tExpr1,tExpr2,…) perform the interpretation directly. UML class diagram Example BNF The following Backus–Naur form example illustrates the interpreter pattern. The grammar expression ::= plus | minus | variable | number plus ::= expression expression '+' minus ::= expression expression '-' variable ::= 'a' | 'b' | 'c' | ... | 'z' digit = '0' | '1' | ... | '9' number ::= digit | digit number defines a language that contains Reverse Polish Notation expressions like: a b + a b c + - a b + c a - - C# This structural code demonstrates the Interpreter patterns, which using a defined grammar, provides the interpreter that processes parsed statements. namespace DesignPatterns.Interpreter { // "Context" class Context { } // "AbstractExpression" abstract class AbstractExpression { public abstract void Interpret(Context context); } // "TerminalExpression" class TerminalExpression : AbstractExpression { public override void Interpret(Context context) { Console.WriteLine("Called Terminal.Interpret()"); } } // "NonterminalExpression" class NonterminalExpression : AbstractExpression { public override void Interpret(Context context) { Console.WriteLine("Called Nonterminal.Interpret()"); } } class MainApp { static void Main() { var context = new Context(); // Usually a tree var list = new List(); // Populate 'abstract syntax tree' list.Add(new TerminalExpression()); list.Add(new NonterminalExpression()); list.Add(new TerminalExpression()); list.Add(new TerminalExpression()); // Interpret foreach (AbstractExpression exp in list) { exp.Interpret(context); } } } } Java Following the interpreter pattern, we need to implement the interface Expr with a lambda (it can be a class) for each grammar rule. public class Interpreter { @FunctionalInterface public interface Expr { int interpret(Map context); static Expr number(int number) { return context -> number; } static Expr plus(Expr left, Expr right) { return context -> left.interpret(context) + right.interpret(context); } static Expr minus(Expr left, Expr right) { return context -> left.interpret(context) - right.interpret(context); } static Expr variable(String name) { return context -> context.getOrDefault(name, 0); } } While the interpreter pattern does not address parsing:247 a parser is provided for completeness. private static Expr parseToken(String token, ArrayDeque stack) { Expr left, right; switch(token) { case "+": // It's necessary to remove first the right operand from the stack right = stack.pop(); // ...and then the left one left = stack.pop(); return Expr.plus(left, right); case "-": right = stack.pop(); left = stack.pop(); return Expr.minus(left, right); default: return Expr.variable(token); } } public static Expr parse(String expression) { ArrayDeque stack = new ArrayDeque(); for (String token : expression.split(" ")) { stack.push(parseToken(token, stack)); } return stack.pop(); } Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42. public static void main(final String[] args) { Expr expr = parse("w x z - +"); Map context = Map.of("w", 5, "x", 10, "z", 42); int result = expr.interpret(context); System.out.println(result); // -27 } } PHP (Example 1) /** * AbstractExpression */ interface Expression { public function interpret(array $context): int; } /** * TerminalExpression */ class TerminalExpression implements Expression { /** @var string */ private $name; public function __construct(string $name) { $this->name = $name; } public function interpret(array $context): int { return intval($context[$this->name]); } } /** * NonTerminalExpression */ abstract class Interpreter pattern 110

NonTerminalExpression implements Expression { /** @var Expression $left */ protected $left; /** @var ?Expression $right */ protected $right; public function __construct(Expression $left, ?Expression $right) { $this->left = $left; $this->right = $right; } abstract public function interpret(array $context): int; public function getRight() { return $this->right; } public function setRight($right): void { $this->right = $right; } } /** * NonTerminalExpression - PlusExpression */ class PlusExpression extends NonTerminalExpression { public function interpret(array $context): int { return intval($this->left->interpret($context) + $this->right->interpret($context)); } } /** * NonTerminalExpression - MinusExpression */ class MinusExpression extends NonTerminalExpression { public function interpret(array $context): int { return intval($this->left->interpret($context) - $this->right->interpret($context)); } } /** * Client */ class InterpreterClient { protected function parseList(array &$stack, array $list, int &$index) { /** @var string $token */ $token = $list[$index]; switch($token) { case '-': list($left, $right) = $this->fetchArguments($stack, $list, $index); return new MinusExpression($left, $right); case '+': list($left, $right) = $this->fetchArguments($stack, $list, $index); return new PlusExpression($left, $right); default: return new TerminalExpression($token); } } protected function fetchArguments(array &$stack, array $list, int &$index): array { /** @var Expression $left */ $left = array_pop($stack); /** @var Expression $right */ $right = array_pop($stack); if ($right === null) { ++$index; $this->parseListAndPush($stack, $list, $index); $right = array_pop($stack); } return array($left, $right); } protected function parseListAndPush(array &$stack, array $list, int &$index) { array_push($stack, $this->parseList($stack, $list, $index)); } protected function parse(string $data): Expression { $stack = []; $list = explode(' ', $data); for ($index=0; $indexparseListAndPush($stack, $list, $index); } return array_pop($stack); } public function main() { $data = "u + v - w + z"; $expr = $this->parse($data); $context = ['u' => 3, 'v' => 7, 'w' => 35, 'z' => 9]; $res = $expr->interpret($context); echo "result: $res" . PHP_EOL; } } // test.php function loadClass($className) { require_once __DIR__ . "/$className.php"; } spl_autoload_register('loadClass'); (new InterpreterClient())->main(); //result: -16 PHP (Example 2) based on the example above with another realization of the Client /** * Client */ class InterpreterClient { public function parseToken(string $token, array &$stack): Expression { switch($token) { case '-': /** @var Expression $left */ $left = array_pop($stack); /** @var Expression $right */ $right = array_pop($stack); return new MinusExpression($left, $right); case '+': /** @var Expression $left */ $left = array_pop($stack); /** @var Expression $right */ $right = array_pop($stack); return new PlusExpression($left, $right); default: return new TerminalExpression($token); } } public function parse(string $data): Expression { $unfinishedData = null; $stack = []; $list = explode(' ', $data); foreach ($list as $token) { $data = $this->parseToken($token, $stack); if ( ($unfinishedData instanceof NonTerminalExpression) && ($data instanceof TerminalExpression) ) { $unfinishedData->setRight($data); array_push($stack, $unfinishedData); $unfinishedData = null; continue; } if ($data instanceof NonTerminalExpression) { if ($data->getRight() === null) { $unfinishedData = $data; continue; } } array_push($stack, $data); } return array_pop($stack); } public function main() { $data = "u + v - w + z"; $expr = $this->parse($data); $context = ['u' => 3, 'v' => 7, 'w' => 35, 'z' => 9]; $res = $expr->interpret($context); echo "result: $res" . PHP_EOL; } } References External links class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Interpreterimplementations in various languages Interpreter implementation in Ruby (programming language)Ruby Interpreter implementation in C++ SourceMaking tutorial Interpreter pattern description from the Portland Pattern Repository 111 Iterator pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In object-oriented programming, the iterator pattern is a design pattern (computer science)design pattern in which an iterator is used to traverse a container (data structure)container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.For example, the hypothetical algorithm SearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows SearchForElement to be used on any container that supports the required type of iterator. Overview The Iterator design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Iterator design pattern solve? The elements of an aggregate object should be accessed and traversed without exposing its representation (data structures). New traversal operations should be defined for an aggregate object without changing its interface. Defining access and traversal operations in the aggregate interface is inflexible because it commits the aggregate to particular access and traversal operations and makes it impossible to add new operations later without having to change the aggregate interface. What solution does the Iterator design pattern describe? Define a separate (iterator) object that encapsulates accessing and traversing an aggregate object. Clients use an iterator to access and traverse an aggregate without knowing its representation (data structures). Different can be used to access and traverse an aggregate in different ways. New access and traversal operations can be defined independently by defining new iterators. See also the UML class and sequence diagram below. Definition The essence of the Iterator Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.".Design Patterns (book)Gang Of FourStructure UML class and sequence diagram A sample UML class and sequence diagram for the Iterator design pattern. In the above Unified Modeling LanguageUML class diagram, the Client class refers (1) to the Aggregate interface for creating an Iterator object (createIterator()) and (2) to the Iterator interface for traversing an Aggregate object (next(),hasNext()). The Iterator1 class implements the Iterator interface by accessing the Aggregate1 class. The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: The Client object calls createIterator() on an Aggregate1 object, which creates an Iterator1 object and returns it to the Client. The Client uses then Iterator1 to traverse the elements of the Aggregate1 object. UML class diagram The iterator patternLanguage-specific implementation Some languages standardize syntax. C++ and Python are notable examples. C# .NET Framework has special interfaces that support a simple iteration: System.Collections.IEnumerator over a non-generic collection and System.Collections.Generic.IEnumerator over a generic collection. C Sharp (programming language)C# statement foreach is designed to easily iterate through the collection that implements System.Collections.IEnumerator and/or System.Collections.Generic.IEnumerator interface. Since C# v2, foreach is also able to iterate through types that implement System.Collections.Generic.IEnumerable and System.Collections.Generic.IEnumerator Example of using foreach statement: var primes = new List{ 2, 3, 5, 7, 11, 13, 17, 19 }; long m = 1; foreach (var p in primes) m *= p; C++ C++ implements iterators with the semantics of pointer (computer programming)pointers in that language. In C++, a class can overload all of the pointer operations, so an iterator can be implemented that acts more or less like a pointer, complete with dereference, Iterator pattern 112

increment, and decrement. This has the advantage that C++ algorithms such as std::sort can immediately be applied to plain old memory buffers, and that there is no new syntax to learn. However, it requires an "end" iterator to test for equality, rather than allowing an iterator to know that it has reached the end. In C++ language, we say that an iterator models the iterator concept (generic programming)concept. Java Java has the Iterator interface. A simple example showing how to return integers between [start, end] using an Iterator import java.util.Iterator; import java.util.NoSuchElementException; public class RangeIteratorExample { public static Iterator range(int start, int end) { return new Iterator<>() { private int index = start; @Override public boolean hasNext() { return index < end; } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } return index++; } }; } public static void main(String[] args) { var iterator = range(0, 10); while (iterator.hasNext()) { System.out.println(iterator.next()); } // or using a lambda iterator.forEachRemaining(System.out::println); } } As of Java 5, objects implementing the Iterable interface, which returns an Iterator from its only method, can be traversed using Java's syntax. The Collection interface from the Java collections framework extends Iterable. Example of class Family implementing the Iterable interface: import java.util.Iterator; import java.util.Set; class Family implements Iterable { private final Set elements; public Family(Set elements) { this.elements = Set.copyOf(elements); } @Override public Iterator iterator() { return elements.iterator(); } } The class IterableExample demonstrates the use of class Family : public class IterableExample { public static void main(String[] args) { var weasleys = Set.of( "Arthur", "Molly", "Bill", "Charlie", "Percy", "Fred", "George", "Ron", "Ginny" ); var family = new Family<>(weasleys); for (var name : family) { System.out.println(name + " Weasley"); } } } Output: Ron Weasley Molly Weasley Percy Weasley Fred Weasley Charlie Weasley George Weasley Arthur Weasley Ginny Weasley Bill Weasley JavaScript JavaScript, as part of ECMAScript#6th EditionECMAScript 6, supports the iterator pattern with any object that provides a next() method, which returns an object with two specific properties: done and value. Here's an example that shows a reverse array iterator: function reverseArrayIterator(array) { var index = array.length - 1; return { next: () => index >= 0 ? {value: array[index--], done: false} : {done: true} } } const it = reverseArrayIterator(['three', 'two', 'one']); console.log(it.next().value); //-> 'one' console.log(it.next().value); //-> 'two' console.log(it.next().value); //-> 'three' console.log(`Are you done? ${it.next().done}`); //-> true Most of the time, though, it is desirable to provide Iterator semantics on objects so that they can be iterated automatically via for...of loops. Some of JavaScript's built-in types such as Array, Map, or Set already define their own iteration behavior. The same effect can be achieved by defining an object's meta @@iterator method, also referred to by Symbol.iterator. This creates an Iterable object. Here's an example of a range function that generates a list of values starting from start to end, exclusive, using a regular for loop to generate the numbers: function range(start, end) { return { [Symbol.iterator]() { // #A return this; }, next() { if (start < end) { return { value: start++, done: false }; // #B } return { done: true, value: end }; // #B } } } for (number of range(1, 5)) { console.log(number); // -> 1, 2, 3, 4 } The iteration mechanism of built-in types, like strings, can also be manipulated: let iter = ['I', 't', 'e', 'r', 'a', 't', 'o', 'r'][Symbol.iterator](); iter.next().value; //-> I iter.next().value; //-> t PHP PHP supports the iterator pattern via the Iterator interface, as part of the standard distribution. Objects that implement the interface can be iterated over with the foreach language construct. Example of patterns using PHP: booksCollection = $booksCollection; } public function current() { return $this->booksCollection->getTitle($this->i_position); } public function key(): int { return $this->i_position; } public function next(): void { $this->i_position++; } public function rewind(): void { $this->i_position = 0; } public function valid(): bool { return !is_null($this->booksCollection->getTitle($this->i_position)); } } a_titles[] = $string; } public function getTitle($key) { if (isset($this->a_titles[$key])) { return $this->a_titles[$key]; } return null; } public function is_empty(): bool { return empty($this->$a_titles); } }

BookCollection(); $booksCollection->addTitle('Design Patterns'); $booksCollection->addTitle('PHP7 is the best'); $booksCollection->addTitle('Laravel Rules'); $booksCollection->addTitle('DHH Rules'); foreach ($booksCollection as $book) { var_dump($book); } OUTPUT string(15) "Design Patterns" string(16) "PHP7 is the best" string(13) "Laravel Rules" string(9) "DHH Rules" Python Python (programming language)Python prescribes a syntax for iterators as part of the language itself, so that language keywords such as for work with what Python calls iterables. An iterable has an __iter__() method that returns an iterator object. The "iterator protocol" requires next() return the next element or raise a StopIteration exception upon reaching the end of the sequence. Iterators also provide an __iter__() method returning themselves so that they can also be iterated over e.g., using a for loop. Generator (computer programming)#PythonGenerators are available since 2.2. In Python 3, next() was renamed __next__().ReferencesExternal links class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Iterator implementations in various languages Object iteration in PHP Iterator Pattern in C# Iterator pattern in UML and in LePUS3 (a formal modelling language) SourceMaking tutorial Design Patterns implementation examples tutorial Iterator Pattern

Mediator pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the defines an object that Encapsulation (computer programming)encapsulates how a set of objects interact. This pattern is considered to be a due to the way it can alter the program's running behavior.In object-oriented programming, programs often consist of many class (computer science)classes. Business logic and computation are distributed among these classes. However, as more classes are added to a program, especially during Software maintenancemaintenance and/or refactoring, the problem of communication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes. With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing Coupling (computer programming)coupling.Overview The Mediator design pattern is one of the twenty-three well-known Design Patternsdesign patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Mediator design pattern solve? Tight coupling between a set of interacting objects should be avoided. It should be possible to change the interaction between a set of objects independently. Defining a set of interacting objects by accessing and updating each other directly is inflexible because it tightly couples the objects to each other and makes it impossible to change the interaction independently from (without having to change) the objects. And it stops the objects from being reusable and makes them hard to test. Tightly coupled objects are hard to implement, change, test, and reuse because they refer to and know about many different objects.What solution does the Mediator design pattern describe? Define a separate (mediator) object that encapsulates the interaction between a set of objects. Mediator pattern 114

Objects delegate their interaction to a mediator object instead of interacting with each other directly. The objects interact with each other indirectly through a mediator object that controls and coordinates the interaction. This makes the objects loosely coupled. They only refer to and know about their mediator object and have no explicit knowledge of each other.See also the UML class and sequence diagram below. Definition The essence of the Mediator Pattern is to "define an object that encapsulates how a set of objects interact". It promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to be varied independently. Client classes can use the mediator to send messages to other clients, and can receive messages from other clients via an event on the mediator class. StructureUML class and sequence diagramA sample UML class and sequence diagram for the Mediator design pattern.In the above Unified Modeling LanguageUML Class diagramclass diagram, the Colleague1 and Colleague2 classes do not refer to (and update) each other directly. Instead, they refer to the common Mediator interface for controlling and coordinating interaction (mediate()), which makes them independent from one another with respect to how the interaction is carried out. The Mediator1 class implements the interaction between Colleague1 and Colleague2. The Unified Modeling LanguageUML sequence diagram shows the run-time interactions. In this example, a Mediator1 object mediates (controls and coordinates) the interaction between Colleague1 and Colleague2 objects. Assuming that Colleague1 wants to interact with Colleague2 (to update/synchronize its state, for example), Colleague1 calls mediate(this) on the Mediator1 object, which gets the changed data from Colleague1 and performs an action2() on Colleague2. Thereafter, Colleague2 calls mediate(this) on the Mediator1 object, which gets the changed data from Colleague2 and performs an action1() on Colleague1. Class diagramThe mediator behavioural design patternParticipants Mediator - defines the interface for communication between Colleague objectsConcreteMediator - implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all of the Colleagues and their purposes with regards to inter-communication.Colleague - defines the interface for communication with other Colleagues through its MediatorConcreteColleague - implements the Colleague interface and communicates with other Colleagues through its MediatorExample C# The Mediator pattern ensures that components are loose couplingloosely coupled, such that they do not call each other explicitly, but instead do so through calls to a mediator. In the following example, the Mediator registers all Components and then calls their SetState methods. public interface IComponent { void SetState(object state); } public class Component1 : IComponent { public void SetState(object state) { throw new NotImplementedException(); } } public class Component2 : IComponent { public void SetState(object state) { throw new NotImplementedException(); } } // Mediates the common tasks public class Mediator { public IComponent Component1 { get; set; } public IComponent Component2 { get; set; } public void ChangeState(object state) { this.Component1.SetState(state); this.Component2.SetState(state); } } A chat room could use the Mediator pattern, or a system where many ‘clients’ each receive a message each time one of the other clients performs an action (for chat rooms, this would be when each person sends a message). In reality using the Mediator pattern for a chat room would only be practical when used with remote procedure callremoting. Using raw sockets would not allow for the delegation (computing)delegate callback (computer programming)callbacks (people subscribed to the Mediator class’ MessageReceived event). public delegate void MessageReceivedEventHandler(string message, string sender); public class Mediator { public event MessageReceivedEventHandler MessageReceived; public void Send(string message, string sender) { if (MessageReceived != null) { Console.WriteLine("Sending '{0}' from {1}", message, sender); MessageReceived(message, sender); } } } public class Person { private Mediator _mediator; public string Name { get; set; } public Person(Mediator mediator, string name) { Name = name; _mediator = mediator; _mediator.MessageReceived += new MessageReceivedEventHandler(Receive); } private void Receive(string message, string sender) { if (sender != Name) Console.WriteLine("{0} received '{1}' from {2}", Name, message, sender); } public void Send(string message) { _mediator.Send(message, Name); } } Java In the following example, a Mediator object controls the values of several Storage objects forcing the user code to access to the stored values through the mediator. When a storage object wants to emit an event indicating that its value has changed, it also goes back to the mediator object (via the method notifyObservers) that controls the list of the observers (implemented using the ). import java.util.HashMap; import java.util.Optional; import Mediator pattern 115

java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; class Storage { T value; T getValue() { return value; } void setValue(Mediator mediator, String storageName, T value) { this.value = value; mediator.notifyObservers(storageName); } } class Mediator { private final HashMap> storageMap = new HashMap<>(); private final CopyOnWriteArrayList> observers = new CopyOnWriteArrayList<>(); public void setValue(String storageName, T value) { Storage storage = storageMap.computeIfAbsent(storageName, name -> new Storage<>()); storage.setValue(this, storageName, value); } public Optional getValue(String storageName) { return Optional.ofNullable(storageMap.get(storageName)).map(Storage::getValue); } public void addObserver(String storageName, Runnable observer) { observers.add(eventName -> { if (eventName.equals(storageName)) { observer.run(); } }); } void notifyObservers(String eventName) { observers.forEach(observer -> observer.accept(eventName)); } } public class MediatorDemo { public static void main(String[] args) { Mediator mediator = new Mediator<>(); mediator.setValue("bob", 20); mediator.setValue("alice", 24); mediator.getValue("alice").ifPresent(age -> System.out.println("age for alice: " + age)); mediator.addObserver("bob", () -> { System.out.println("new age for bob: " + mediator.getValue("bob").orElseThrow(RuntimeException::new)); }); mediator.setValue("bob", 21); } } References External links class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Mediator implementations in various languagesKaiser, Bodo (2012-09-21). "Is the use of the mediator pattern recommend?". Stack Overflow.

Memento pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The is a design pattern (computer science)software design pattern that provides the ability to restore an object to its previous state (undo via rollback).The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an Opaque data typeopaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.Classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the Random_seedseed state) and the state in a finite state machine. Overview The Memento design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. The Memento Pattern was created by Noah Thompson, David Espiritu, and Dr. Drew Clinkenbeard for early HP products. What problems can the Memento design pattern solve? The internal state of an object should be saved externally so that the object Memento pattern 116

can be restored to this state later. The object's encapsulation must not be violated. The problem is that a well designed object is encapsulated so that its representation (data structure) is hidden inside the object and can't be accessed from outside the object. What solution does the Memento design pattern describe?Make an object (originator) itself responsible for saving its internal state to a (memento) object and restoring to a previous state from a (memento) object. Only the originator that created a memento is allowed to access it. A client (caretaker) can request a memento from the originator (to save the internal state of the originator) and pass a memento back to the originator (to restore to a previous state). This enables to save and restore the internal state of an originator without violating its encapsulation. See also the UML class and sequence diagram below. Structure UML class and sequence diagram A sample UML class and sequence diagram for the Memento design pattern. In the above Unified Modeling LanguageUML Class diagramclass diagram, the Caretaker class refers to the Originator class for saving (createMemento()) and restoring (restore(memento)) originator's internal state. The Originator class implements (1) createMemento() by creating and returning a Memento object that stores originator's current internal state and (2) restore(memento) by restoring state from the passed in Memento object. The Unified Modeling LanguageUML Sequence diagramsequence diagram shows the run-time interactions: (1) Saving originator's internal state: The Caretaker object calls createMemento() on the Originator object, which creates a Memento object, saves its current internal state (setState()), and returns the Memento to the Caretaker. (2) Restoring originator's internal state: The Caretaker calls restore(memento) on the Originator object and specifies the Memento object that stores the state that should be restored. The Originator gets the state (getState()) from the Memento to set its own state. Java example class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Memento implementations in various languagesThe following Java (programming language)Java program illustrates the "undo" usage of the memento pattern. import java.util.List; import java.util.ArrayList; class Originator { private String state; // The class could also contain additional data that is not part of the // state saved in the memento.. public void set(String state) { this.state = state; System.out.println("Originator: Setting state to " + state); } public Memento saveToMemento() { System.out.println("Originator: Saving to Memento."); return new Memento(this.state); } public void restoreFromMemento(Memento memento) { this.state = memento.getSavedState(); System.out.println("Originator: State after restoring from Memento: " + state); } public static class Memento { private final String state; public Memento(String stateToSave) { state = stateToSave; } // accessible by outer class only private String getSavedState() { return state; } } } class Caretaker { public static void main(String[] args) { List savedStates = new ArrayList(); Originator originator = new Originator(); originator.set("State1"); originator.set("State2"); savedStates.add(originator.saveToMemento()); originator.set("State3"); // We can request multiple mementos, and choose which one to roll back to. savedStates.add(originator.saveToMemento()); originator.set("State4"); originator.restoreFromMemento(savedStates.get(1)); } } The output is: Originator: Setting state to State1 Originator: Setting state to State2 Originator: Saving to Memento. Originator: Setting state to State3 Originator: Saving to Memento. Originator: Setting state to State4 Originator: State after restoring from Memento: State3 This example uses a String as the state, which is an in Java. In real-life scenarios the state will almost always be an object, in which case a copy of the state must be done. It must be said that the implementation shown has a drawback: it declares an internal class. It would be better if this memento strategy could apply to more than one originator. There are mainly three other ways to achieve Memento: Serialization. A class declared in the same package. The object can also be accessed via a proxy, which can achieve any save/restore operation on the object. C# example The memento pattern allows one to capture the internal state of an object without violating encapsulation such that later one can undo/revert the changes if required. Here one can see that the memento object is actually used to revert the changes made in the object. class Originator { private string state; // The class could also contain additional data that is not part of the // state saved in the memento. public void Set(string state) { Console.WriteLine("Originator: Setting state to " + state); this.state = state; } public Memento SaveToMemento() { Console.WriteLine("Originator: Saving to Memento."); return new Memento(state); } public void RestoreFromMemento(Memento memento) { state = memento.SavedState; Console.WriteLine("Originator: State Memento pattern 117

after restoring from Memento: " + state); } public class Memento { public readonly string SavedState; public Memento(string stateToSave) { SavedState = stateToSave; } } } class Caretaker { static void Main(string[] args) { List savedStates = new List(); Originator originator = new Originator(); originator.Set("State1"); originator.Set("State2"); savedStates.Add(originator.SaveToMemento()); originator.Set("State3"); // We can request multiple mementos, and choose which one to roll back to. savedStates.Add(originator.SaveToMemento()); originator.Set("State4"); originator.RestoreFromMemento(savedStates[1]); } } Python example """ Memento pattern example. """ class Memento(object): def __init__(self, state) -> None: self._state = state def get_saved_state(self): return self._state class Originator(object): _state = "" def set(self, state) -> None: print("Originator: Setting state to", state) self._state = state def save_to_memento(self) -> Memento: print("Originator: Saving to Memento.") return Memento(self._state) def restore_from_memento(self, memento) -> None: self._state = memento.get_saved_state() print("Originator: State after restoring from Memento:", self._state) saved_states = [] originator = Originator() originator.set("State1") originator.set("State2") saved_states.append(originator.save_to_memento()) originator.set("State3") saved_states.append(originator.save_to_memento()) originator.set("State4") originator.restore_from_memento(saved_states[1]) References External links Description of Memento Pattern in Ada (programming language)Ada Memento UML Class Diagram with C# and .NET code samples SourceMaking TutorialMemento Design Pattern using Java

Null Object pattern

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof). It was first published in the Pattern Languages of Program Design book series.

Motivation In most object-oriented languages, such as Java or C#, references may be null. These references need to be checked to ensure they are not null before invoking any methods, because methods typically cannot be invoked on null references. The Objective-C language takes another approach to this problem and does nothing when sending a message to nil; if a return value is expected, nil (for objects), 0 (for numeric values), NO (for BOOL values), or a struct (for struct types) with all its members initialised to null/0/NO/zero-initialised struct is returned.

Description Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a null object is very predictable and has no side effects: it does nothing. For example, a function may retrieve a list of files in a folder and perform some action on each. In the case of an empty folder, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design. By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to 118

check whether the return value is a null object (an empty list) and react differently if desired. The null object pattern can also be used to act as a stub for testing, if a certain feature such as a database is not available for testing.

Example Given a binary tree, with this node structure:

class node { node left node right }

One may implement a tree size procedure recursively:

function tree_size(node) { return 1 + tree_size(node.left) + tree_size(node.right) }

Since the child nodes may not exist, one must modify the procedure by adding non-existence or null checks:

function tree_size(node) { set sum = 1 if node.left exists { sum = sum + tree_size(node.left) } if node.right exists { sum = sum + tree_size(node.right) } return sum }

This however makes the procedure more complicated by mixing boundary checks with normal logic, and it becomes harder to read. Using the null object pattern, one can create a special version of the procedure but only for null nodes:

function tree_size(node) { return 1 + tree_size(node.left) + tree_size(node.right) }

function tree_size(null_node) { return 0 }

This separates normal logic from special case handling, and makes the code easier to understand. Null Object pattern 119

Relation to other patterns It can be regarded as a special case of the and the Strategy pattern. It is not a pattern from Design Patterns, but is mentioned in Martin Fowler's Refactoring and Joshua Kerievsky's Refactoring To Patterns as the Insert Null Object refactoring. Chapter 17 of Robert Cecil Martin's Agile Software Development: Principles, Patterns and Practices is dedicated to the pattern.

Alternatives From C# 6.0 it is possible to use the "?." operator (aka null-conditional operator), which will simply evaluate to null if its left operand is null.

// compile as Console Application, requires C# 6.0 or higher using System;

namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string str = "test"; Console.WriteLine(str?.Length); Console.ReadKey(); } } } // The output will be: // 4

Extension methods and Null coalescing In some Microsoft .NET languages, Extension methods can be used to perform what is called 'null coalescing'. This is because extension methods can be called on null values as if it concerns an 'instance method invocation' while in fact extension methods are static. Extension methods can be made to check for null values, thereby freeing code that uses them from ever having to do so. Note that the example below uses the C# to guarantee error free invocation, where it could also have used a more mundane if...then...else. The following example only works when you do not care the existence of null, or you treat null and the same. The assumption may not hold in other applications.

// compile as Console Application, requires C# 3.0 or higher using System; using System.Linq; namespace MyExtensionWithExample { public static class StringExtensions { public static int SafeGetLength(this string valueOrNull) { return (valueOrNull ?? string.Empty).Length; } } Null Object pattern 120

public static class Program { // define some strings static readonly string[] strings = new [] { "Mr X.", "Katrien Duck", null, "Q" }; // write the total length of all the strings in the array public static void Main(string[] args) { var query = from text in strings select text.SafeGetLength(); // no need to do any checks here Console.WriteLine(query.Sum()); } } } // The output will be: // 18

In various languages

C++ A language with statically typed references to objects illustrates how the null object becomes a more complicated pattern:

#include

class Animal { public: virtual ~Animal() = default;

virtual void MakeSound() const = 0; };

class Dog : public Animal { public: virtual void MakeSound() const override { std::cout << "woof!" << std::endl; } };

class NullAnimal : public Animal { public: virtual void MakeSound() const override {} };

Here, the idea is that there are situations where a pointer or reference to an Animal object is required, but there is no appropriate object available. A null reference is impossible in standard-conforming C++. A null Animal* pointer is possible, and could be useful as a place-holder, but may not be used for direct dispatch: a->MakeSound() is undefined behavior if a is a . The null object pattern solves this problem by providing a special NullAnimal class which can be instantiated bound to an Animal pointer or reference. Null Object pattern 121

The special null class must be created for each class hierarchy that is to have a null object, since a NullAnimal is of no use when what is needed is a null object with regard to some Widget base class that is not related to the Animal hierarchy. Note, that NOT having a null class at all is an important feature, in contrast to languages where "anything is a reference" (e.g. Java and C#). In C++, the design of a function or method may explicitly state whether null is allowed or not.

// Function which requires an |Animal| instance, and will not accept null. void DoSomething(const Animal& animal) { // |animal| may never be null here. }

// Function which may accept an |Animal| instance or null. void DoSomething(const Animal* animal) { // |animal| may be null. }

C# C# is a language in which the null object pattern can be properly implemented. This example shows animal objects that display sounds and a NullAnimal instance used in place of the C# null keyword. The null object provides consistent behaviour and prevents a runtime null reference exception that would occur if the C# null keyword were used instead.

/* Null object pattern implementation: */ using System;

// Animal interface is the key to compatibility for Animal implementations below. interface IAnimal { void MakeSound(); }

// Animal is the base case. abstract class Animal : IAnimal { // A shared instance that can be used for comparisons public static readonly IAnimal Null = new NullAnimal();

// The Null Case: this NullAnimal class should be used in place of C# null keyword. private class NullAnimal : Animal { public override void MakeSound() { // Purposefully provides no behaviour. Null Object pattern 122

} } public abstract void MakeSound(); }

// Dog is a real animal. class Dog : IAnimal { public void MakeSound() { Console.WriteLine("Woof!"); } }

/* ======* Simplistic usage example in a Main entry point. */ static class Program { static void Main() { IAnimal dog = new Dog(); dog.MakeSound(); // outputs "Woof!"

/* Instead of using C# null, use the Animal.Null instance. * This example is simplistic but conveys the idea that if the Animal.Null instance is used then the program * will never experience a .NET System.NullReferenceException at runtime, unlike if C# null were used. */ IAnimal unknown = Animal.Null; //<< replaces: IAnimal unknown = null; unknown.MakeSound(); // outputs nothing, but does not throw a runtime exception } }

Smalltalk Following the Smalltalk principle, everything is an object, the absence of an object is itself modeled by an object, called nil. In the GNU Smalltalk for example, the class of nil is UndefinedObject, a direct descendant of Object. Any operation that fails to return a sensible object for its purpose may return nil instead, thus avoiding the special case of returning "no object". This method has the advantage of simplicity (no need for a special case) over the classical "null" or "no object" or "null reference" approach. Especially useful messages to be used with nil are isNil or ifNil:, which make it practical and safe to deal with possible references to nil in Smalltalk programs. Null Object pattern 123

Common Lisp In Lisp, functions can gracefully accept the special object nil, which reduces the amount of special case testing in application code. For instance, although nil is an atom and does not have any fields, the functions car and cdr accept nil and just return it, which is very useful and results in shorter code. Since nil is the empty list in Lisp, the situation described in the introduction above doesn't exist. Code which returns nil is returning what is in fact the empty list (and not anything resembling a null reference to a list type), so the caller does not need to test the value to see whether or not it has a list. The null object pattern is also supported in multiple value processing. If the program attempts to extract a value from an expression which returns no values, the behavior is that the null object nil is substituted. Thus (list (values)) returns (nil) (a one-element list containing nil). The (values) expression returns no values at all, but since the function call to list needs to reduce its argument expression to a value, the null object is automatically substituted.

CLOS In , the object nil is the one and only instance of the special class null. What this means is that a method can be specialized to the null class, thereby implementing the null design pattern. Which is to say, it is essentially built into the object system:

;; empty dog class

(defclass dog () ())

;; a dog object makes a sound by barking: woof! is printed on standard output ;; when (make-sound x) is called, if x is an instance of the dog class.

(defmethod make-sound ((obj dog)) (format t "woof!~%"))

;; allow (make-sound nil) to work via specialization to null class. ;; innocuous empty body: nil makes no sound. (defmethod make-sound ((obj null)))

The class null is a subclass of the symbol class, because nil is a symbol. Since nil also represents the empty list, null is a subclass of the list class, too. Methods parameters specialized to symbol or list will thus take a nil argument. Of course, a null specialization can still be defined which is a more specific match for nil. Null Object pattern 124

Scheme Unlike Common Lisp, and many dialects of Lisp, the Scheme dialect does not have a nil value which works this way; the functions car and cdr may not be applied to an empty list; Scheme application code therefore has to use the empty? or pair? predicate functions to sidestep this situation, even in situations where very similar Lisp would not need to distinguish the empty and non-empty cases thanks to the behavior of nil.

Ruby In duck-typed languages like Ruby, language inheritance is not necessary to provide expected behavior.

class Dog def sound "bark" end end

class NilAnimal def sound(*); end end

def get_animal(animal=NilAnimal.new) animal end

get_animal(Dog.new).sound => "bark" get_animal.sound => nil

Attempts to directly monkey-patch NilClass instead of providing explicit implementations give more unexpected side effects than benefits.

JavaScript In duck-typed languages like JavaScript, language inheritance is not necessary to provide expected behavior.

class Dog { sound() { return 'bark'; } }

class NullAnimal { sound() { return null; } }

function getAnimal(type) { return type === 'dog' ? new Dog() : new NullAnimal(); Null Object pattern 125

}

['dog', null].map((animal) => getAnimal(animal).sound()); // Returns ["bark", null]

Java public interface Animal { void makeSound() ; }

public class Dog implements Animal { public void makeSound() { System.out.println("woof!"); } }

public class NullAnimal implements Animal { public void makeSound() { // silence... } }

This code illustrates a variation of the C++ example, above, using the Java language. As with C++, a null class can be instantiated in situations where a reference to an Animal object is required, but there is no appropriate object available. A null Animal object is possible (Animal myAnimal = null;) and could be useful as a place-holder, but may not be used for calling a method. In this example, myAnimal.makeSound(); will throw a NullPointerException. Therefore, additional code may be necessary to test for null objects. The null object pattern solves this problem by providing a special NullAnimal class which can be instantiated as an object of type Animal. As with C++ and related languages, that special null class must be created for each class hierarchy that needs a null object, since a NullAnimal is of no use when what is needed is a null object that does not implement the Animal interface.

PHP interface Animal { public function makeSound(); }

class Dog implements Animal { public function makeSound() { echo "Woof.."; } }

class Cat implements Animal Null Object pattern 126

{ public function makeSound() { echo "Meowww.."; } }

class NullAnimal implements Animal { public function makeSound() { // silence... } }

$animalType = 'elephant'; switch($animalType) { case 'dog': $animal = new Dog(); break; case 'cat': $animal = new Cat(); break; default: $animal = new NullAnimal(); break; } $animal->makeSound(); // ..the null animal makes no sound

Visual Basic .NET The following null object pattern implementation demonstrates the concrete class providing its corresponding null object in a static field Empty. This approach is frequently used in the .NET Framework (String.Empty, EventArgs.Empty, Guid.Empty, etc.).

Public Class Animal Public Shared ReadOnly Empty As Animal = New AnimalEmpty()

Public Overridable Sub MakeSound() Console.WriteLine("Woof!") End Sub End Class

Friend NotInheritable Class AnimalEmpty Inherits Animal

Public Overrides Sub MakeSound() ' End Sub Null Object pattern 127

End Class

Criticism This pattern should be used carefully as it can make errors/bugs appear as normal program execution.[1] Care should be taken not to implement this pattern just to avoid null checks and make code more readable, since the harder-to-read code may just move to another place and be less standard – such as when different logic must execute in case the object provided is indeed the null object. The common pattern in most languages with reference types is to compare a reference to a single value referred to as null or nil. Also, there is additional need for testing that no code anywhere ever assigns null instead of the null object, because in most cases and languages with static typing, this is not a compiler error if the null object is of a reference type, although it would certainly lead to errors at run time in parts of the code where the pattern was used to avoid null checks. On top of that, in most languages and assuming there can be many null objects (i.e. the null object is a reference type but doesn't implement the singleton pattern in one or another way), checking for the null object instead of for the null or nil value introduces overhead, as does the singleton pattern likely itself upon obtaining the singleton reference.

References [1] Fowler, Martin (1999). Refactoring pp. 216

External links

• Jeffrey Walker's account of the Null Object Pattern (http:/ / www. cs. oberlin. edu/ ~jwalker/ nullObjPattern/ )

• Martin Fowler's description of Special Case, a slightly more general pattern (http:/ / martinfowler. com/

eaaCatalog/ specialCase. html)

• Null Object Pattern Revisited (http:/ / www. owlnet. rice. edu/ ~comp212/ 00-spring/ handouts/ week06/

null_object_revisited. htm)

• Introduce Null Object refactoring (http:/ / refactoring. com/ catalog/ introduceNullObject. html)

• SourceMaking Tutorial (http:/ / sourcemaking. com/ design_patterns/ null_object)

• Null Object Pattern in Swift (https:/ / medium. com/ @eofster/ null-object-pattern-in-swift-1b96e03b2756) Observer pattern 128 Observer pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The observer pattern is a design pattern (computer science)software design pattern in which an Object (computer science)#Objects in object-oriented programmingobject, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their Method (computer science)methods.It is mainly used to implement distributed event handling systems, in "event driven" software. In those systems, the subject is usually called a "stream of events" or "stream source of events", while the observers are called "sink of events". The stream nomenclature simulates or adapts to a physical setup where the observers are physically separated and have no control over the emitted events of the subject/stream-source. This pattern then perfectly suits any process where data arrives through I/O, that is, where data is not available to the CPU at startup, but can arrive "randomly" (HTTP requests, GPIO data, user input from keyboard/mouse/..., distributed databases and blockchains, ...). Most modern languages have built-in "event" constructs which implement the observer pattern components. While not mandatory most 'observers' implementations will use background threads listening for subject events and other support mechanism from the kernel (Linux epoll, ...) Overview The Observer design pattern is one of the twenty-three well-known Design Patterns"Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.What problems can the Observer design pattern solve? The Observer pattern addresses the following problems: A one-to-many dependency between objects should be defined without making the objects tightly coupled. It should be ensured that when one object changes state an open-ended number of dependent objects are updated automatically. It should be possible that one object can notify an open-ended number of other objects. Defining a one-to-many dependency between objects by defining one object (subject) that updates the state of dependent objects directly is inflexible because it couples the subject to particular dependent objects. Still it can make sense from a performance point of view or if the object implementation is tightly coupled (think of low level kernel structures that execute thousands of times a second). Tightly coupled objects can be hard to implement in some scenarios, and hard to reuse because they refer to and know about (and how to update) many different objects with different interfaces. In other scenarios tightly coupled objects can be a better option since the compiler will be able to detect errors at compile time and optimize the code at CPU instruction level. What solution does the Observer design pattern describe? Define Subject and Observer objects. so that when a subject changes state, all registered observers are notified and updated automatically (and probably asynchronously). The sole responsibility of a subject is to maintain a list of observers and to notify them of state changes by calling their update() operation. The responsibility of observers is to register (and unregister) themselves on a subject (to get notified of state changes) and to update their state (synchronize their state with subject's state) when they are notified. This makes subject and observers loosely coupled. Subject and observers have no explicit knowledge of each other. Observers can be added and removed independently at run-time. This notification-registration interaction is also known as publish-subscribe.See also the UML class and sequence diagram below. Strong vs. The observer pattern can cause memory leaks, known as the lapsed listener problem, because in basic implementation it requires both explicit registration and explicit deregistration, as in the dispose pattern, because the subject holds strong references to the observers, keeping them alive. This can be prevented by the subject holding weak references to the observers. Coupling and typical pub-sub implementations Typically, the observer pattern is implemented so the Observer pattern 129

"subject" being "observed" is part of the object for which state changes are being observed (and communicated to the observers). This type of implementation is considered "tightly coupled systemtightly coupled", forcing both the observers and the subject to be aware of each other and have access to their internal parts, creating possible issues of , speed, message recovery and maintenance (also called event or notification loss), the lack of flexibility in conditional dispersion, and possible hindrance to desired security measures. In some (polling (computer science)non-polling) implementations of the publish-subscribe pattern (aka the pub-sub pattern), this is solved by creating a dedicated "" server (and sometimes an extra "message handler" object) as an extra stage between the observer and the object being observed, thus decoupling the components. In these cases, the message queue server is accessed by the observers with the observer pattern, "subscribing to certain messages" knowing only about the expected message (or not, in some cases), while knowing nothing about the message sender itself; the sender also may know nothing about the observers. Other implementations of the publish-subscribe pattern, which achieve a similar effect of notification and communication to interested parties, do not use the observer pattern at all. Comparison between different observer pattern implementations Moshe Bindler, 2015 (Github) Differences between pub/sub and observer pattern The Observer Pattern by Adi Osmani (Safari books online)In early implementations of multi-window operating systems like OS/2 and Windows, the terms "publish-subscribe pattern" and "event driven software development" were used as a synonym for the observer pattern. The Windows Programming Experience Charles Petzold, Nov 10, 1992, PC Magazine (Google Books)The observer pattern, as described in the Design Patterns GoF book, is a very basic concept and does not address removing interest in changes to the observed "subject" or special logic to be done by the observed "subject" before or after notifying the observers. The pattern also does not deal with recording when change notifications are sent or guaranteeing that they are being received. These concerns are typically handled in message queueing systems of which the observer pattern is only a small part. Related patterns: Publish–subscribe pattern, mediator patternmediator, singleton patternsingleton. Uncoupled The observer pattern may be used in the absence of publish-subscribe, as in the case where model status is frequently updated. Frequent updates may cause the view to become unresponsive (e.g by invoking many painter's algorithmrepaint calls); such observers should instead use a timer. Thus instead of being overloaded by change message, the observer will cause the view to represent the approximate state of the model at a regular interval. This mode of observer is particularly useful for progress barprogress bars, where the underlying operation's progress changes with several times per second. StructureUML class and sequence diagramA sample UML class and sequence diagram for the Observer design pattern. In the above Unified Modeling LanguageUML class diagram, the Subject class does not update the state of dependent objects directly. Instead, Subject refers to the Observer interface (update()) for updating state, which makes the Subject independent of how the state of dependent objects is updated. The Observer1 and Observer2 classes implement the Observer interface by synchronizing their state with subject's state. The Unified Modeling LanguageUML Sequence diagramsequence diagram shows the run-time interactions: The Observer1 and Observer2 objects call attach(this) on Subject1 to register themselves. Assuming that the state of Subject1 changes, Subject1 calls notify() on itself. notify() calls update() on the registered Observer1 and Observer2 objects, which request the changed data (getState()) from Subject1 to update (synchronize) their state. UML class diagramUnified Modeling LanguageUML class diagram of Observer patternExampleWhile the library classes java.util.Observer and java.util.Observable exist, they have been deprecated in Java 9 because the model implemented was quite limited. Below is an example written in Java (programming language)Java that takes keyboard input and treats each input line as an event. When a string is supplied from System.in, the method notifyObservers is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods. Java import java.util.List; import java.util.ArrayList; import java.util.Scanner; class EventSource { public interface Observer { void update(String event); } private final List observers = new ArrayList<>(); private void notifyObservers(String event) { observers.forEach(observer -> observer.update(event)); //alternative lambda expression: observers.forEach(Observer::update); } public void addObserver(Observer observer) { observers.add(observer); } public void scanSystemIn() { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String line = scanner.nextLine(); notifyObservers(line); } } } public class Observer pattern 130

ObserverDemo { public static void main(String[] args) { System.out.println("Enter Text: "); EventSource eventSource = new EventSource(); eventSource.addObserver(event -> { System.out.println("Received response: " + event); }); eventSource.scanSystemIn(); } } Kotlin import java.util.Scanner typealias Observer = (event: String) -> Unit; class EventSource { private val observers = mutableListOf() private fun notifyObservers(event: String) { observers.forEach { it(event) } } fun addObserver(observer: Observer) { observers += observer } fun scanSystemIn() { val scanner = Scanner(System.`in`) while (scanner.hasNext()) { val line = scanner.nextLine() notifyObservers(line) } } } fun main(arg: List) { println("Enter Text: ") val eventSource = EventSource() eventSource.addObserver { event -> println("Received response: $event") } eventSource.scanSystemIn() } Delphi uses System.Generics.Collections , System.SysUtils ; type IObserver = interface ['{0C8F4C5D-1898-4F24-91DA-63F1DD66A692}'] procedure Update(const AValue: string); end; type TEdijsObserverManager = class strict private FObservers: TList; public constructor Create; overload; destructor Destroy; override; procedure NotifyObservers(const AValue: string); procedure AddObserver(const AObserver: IObserver); procedure UnregisterObsrver(const AObserver: IObserver); end; type TListener = class(TInterfacedObject, IObserver) strict private FName: string; public constructor Create(const AName: string); reintroduce; procedure Update(const AValue: string); end; procedure TEdijsObserverManager.AddObserver(const AObserver: IObserver); begin if not FObservers.Contains(AObserver) then FObservers.Add(AObserver); end; constructor TEdijsObserverManager.Create; begin inherited Create; FObservers := TList.Create; end; destructor TEdijsObserverManager.Destroy; begin FreeAndNil(FObservers); inherited; end; procedure TEdijsObserverManager.NotifyObservers(const AValue: string); var i: Integer; begin for i := 0 to FObservers.Count - 1 do FObservers[i].Update(AValue); end; procedure TEdijsObserverManager.UnregisterObsrver(const AObserver: IObserver); begin if FObservers.Contains(AObserver) then FObservers.Remove(AObserver); end; constructor TListener.Create(const AName: string); begin inherited Create; FName := AName; end; procedure TListener.Update(const AValue: string); begin WriteLn(FName + ' listener received notification: ' + AValue); end; procedure TEdijsForm.ObserverExampleButtonClick(Sender: TObject); var _DoorNotify: TEdijsObserverManager; _ListenerHusband: IObserver; _ListenerWife: IObserver; begin _DoorNotify := TEdijsObserverManager.Create; try _ListenerHusband := TListener.Create('Husband'); _DoorNotify.AddObserver(_ListenerHusband); _ListenerWife := TListener.Create('Wife'); _DoorNotify.AddObserver(_ListenerWife); _DoorNotify.NotifyObservers('Someone is knocking on the door'); finally FreeAndNil(_DoorNotify); end; end; Output Husband listener received notification: Someone is knocking on the door Wife listener received notification: Someone is knocking on the door Python A similar example in Python_(programming_language)Python: class Observable: def __init__(self): self._observers = [] def register_observer(self, observer): self._observers.append(observer) def notify_observers(self, *args, **kwargs): for observer in self._observers: observer.notify(self, *args, **kwargs) class Observer: def __init__(self, observable): observable.register_observer(self) def notify(self, observable, *args, **kwargs): print('Got', args, kwargs, 'From', observable) subject = Observable() observer = Observer(subject) subject.notify_observers('test') C# public class Payload { public string Message { get; set; } } public class Subject : IObservable { public IList> Observers { get; set; } public Subject() { Observers = new List>(); } public IDisposable Subscribe(IObserver observer) { if (!Observers.Contains(observer)) { Observers.Add(observer); } return new Unsubscriber(Observers, observer); } public void SendMessage(string message) { foreach (var observer in Observers) { observer.OnNext(new Payload { Message = message }); } } } public class Unsubscriber : IDisposable { private IObserver observer; private IList> observers; public Unsubscriber(IList> observers, IObserver observer) { this.observers = observers; this.observer = observer; } public void Dispose() { if (observer != null && observers.Contains(observer)) { observers.Remove(observer); } } } public class Observer : IObserver { public string Message { get; set; } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(Payload value) { Message = value.Message; } public IDisposable Register(Subject subject) { return subject.Subscribe(this); } } JavaScript Libraries and frameworks exist for JavaScript to utilize the observer pattern. One such library is RxJS seen below. // import the fromEvent operator Observer pattern 131

import { fromEvent } from 'rxjs'; // grab button reference const button = document.getElementById('myButton'); // create an observable of button clicks const myObservable = fromEvent(button, 'click'); // for now, let's just log the event on each click const subscription = myObservable.subscribe(event => console.log(event)); ReferencesExternal linksclass=noviewer Observer implementations in various languages at Wikibooks

Publish/subscribe

In software architecture, publish–subscribe is a where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published messages into classes without knowledge of which subscribers, if any, there may be. Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are. Publish–subscribe is a sibling of the message queue paradigm, and is typically one part of a larger message-oriented middleware system. Most messaging systems support both the pub/sub and message queue models in their API, e.g. Java Message Service (JMS). This pattern provides greater network scalability and a more dynamic network topology, with a resulting decreased flexibility to modify the publisher and the structure of the published data.

Message filtering In the publish-subscribe model, subscribers typically receive only a subset of the total messages published. The process of selecting messages for reception and processing is called filtering. There are two common forms of filtering: topic-based and content-based. In a topic-based system, messages are published to "topics" or named logical channels. Subscribers in a topic-based system will receive all messages published to the topics to which they subscribe. The publisher is responsible for defining the topics to which subscribers can subscribe. In a content-based system, messages are only delivered to a subscriber if the attributes or content of those messages matches constraints defined by the subscriber. The subscriber is responsible for classifying the messages. Some systems support a hybrid of the two; publishers post messages to a topic while subscribers register content-based subscriptions to one or more topics.

Topologies In many pub/sub systems, publishers post messages to an intermediary or event bus, and subscribers register subscriptions with that broker, letting the broker perform the filtering. The broker normally performs a store and forward function to route messages from publishers to subscribers. In addition, the broker may prioritize messages in a queue before routing. Subscribers may register for specific messages at build time, initialization time or runtime. In GUI systems, subscribers can be coded to handle user commands (e.g., click of a button), which corresponds to build time registration. Some frameworks and software products use XML configuration files to register subscribers. These configuration files are read at initialization time. The most sophisticated alternative is when subscribers can be added or removed at runtime. This latter approach is used, for example, in database triggers, mailing lists, and RSS. Publish/subscribe 132

The Data Distribution Service (DDS) middleware does not use a broker in the middle. Instead, each publisher and subscriber in the pub/sub system shares meta-data about each other via IP multicast. The publisher and the subscribers cache this information locally and route messages based on the discovery of each other in the shared cognizance. In effect, brokerless architectures require publish/subscribe system to construct an overlay network which allows efficient decentralized routing from publishers to subscribers. It was shown by Jon Kleinberg that efficient decentralised routing requires Navigable Small-World topologies. Such Small-World topologies are usually implemented by decentralized or federated publish/subscribe systems. Locality-aware publish/subscribe systems construct Small-World topologies that route subscriptions through short-distance and low-cost links thereby reducing subscription delivery times.

History One of the earliest publicly described pub/sub systems was the "news" subsystem of the Isis Toolkit, described at the 1987 Association for Computing Machinery (ACM) Symposium on Operating Systems Principles conference (SOSP '87), in a paper "Exploiting Virtual Synchrony in Distributed Systems. 123–138".

Advantages

Loose coupling Publishers are loosely coupled to subscribers, and need not even know of their existence. With the topic being the focus, publishers and subscribers are allowed to remain ignorant of system topology. Each can continue to operate as per normal independently of the other. In the traditional tightly coupled client–server paradigm, the client cannot post messages to the server while the server process is not running, nor can the server receive messages unless the client is running. Many pub/sub systems decouple not only the locations of the publishers and subscribers but also decouple them temporally. A common strategy used by middleware analysts with such pub/sub systems is to take down a publisher to allow the subscriber to work through the backlog (a form of bandwidth throttling).

Scalability Pub/sub provides the opportunity for better scalability than traditional client-server, through parallel operation, message caching, tree-based or network-based routing, etc. However, in certain types of tightly coupled, high-volume enterprise environments, as systems scale up to become data centers with thousands of servers sharing the pub/sub infrastructure, current vendor systems often lose this benefit; scalability for pub/sub products under high load in these contexts is a research challenge. Outside of the enterprise environment, on the other hand, the pub/sub paradigm has proven its scalability to volumes far beyond those of a single data center, providing Internet-wide distributed messaging through web syndication protocols such as RSS and Atom. These syndication protocols accept higher latency and lack of delivery guarantees in exchange for the ability for even a low-end web server to syndicate messages to (potentially) millions of separate subscriber nodes. Publish/subscribe 133

Disadvantages The most serious problems with pub/sub systems are a side-effect of their main advantage: the decoupling of publisher from subscriber.

Message delivery issues A pub/sub system must be designed carefully to be able to provide stronger system properties that a particular application might require, such as assured delivery. • The broker in a pub/sub system may be designed to deliver messages for a specified time, but then stop attempting delivery, whether or not it has received confirmation of successful receipt of the message by all subscribers. A pub/sub system designed in this way cannot guarantee delivery of messages to any applications that might require such assured delivery. Tighter coupling of the designs of such a publisher and subscriber pair must be enforced outside of the pub/sub architecture to accomplish such assured delivery (e.g. by requiring the subscriber to publish receipt messages). • A publisher in a pub/sub system may assume that a subscriber is listening, when in fact it is not. A factory may utilize a pub/sub system where equipment can publish problems or failures to a subscriber that displays and logs those problems. If the logger fails (crashes), equipment problem publishers won't necessarily receive notice of the logger failure, and error messages will not be displayed or recorded by any equipment on the pub/sub system. This is also a design challenge for alternative messaging architectures, such as a client/server system. In a client/server system, when an error logger fails, the system will receive an indication of the error logger (server) failure. However, the client/server system will have to deal with that failure by having redundant logging servers online, or by dynamically spawning fallback logging servers. This adds complexity to the client and server designs, as well as to the client/server architecture as a whole. However, in a pub/sub system, redundant logging subscribers that are exact duplicates of the existing logger can be added to the system to increase logging reliability without any impact to any other equipment on the system. In a pub/sub system, the feature of assured error message logging can be added incrementally, subsequent to implementing the basic functionality of equipment problem message logging. The pub/sub pattern scales well for small networks with a small number of publisher and subscriber nodes and low message volume. However, as the number of nodes and messages grows, the likelihood of instabilities increases, limiting the maximum scalability of a pub/sub network. Example throughput instabilities at large scales include: • Load surges—periods when subscriber requests saturate network throughput followed by periods of low message volume (underutilized network bandwidth) • Slowdowns—as more and more applications use the system (even if they are communicating on separate pub/sub channels) the message volume flow to an individual subscriber will slow For pub/sub systems that use brokers (servers), the argument for a broker to send messages to a subscriber is in-band, and can be subject to security problems. Brokers might be fooled into sending notifications to the wrong client, amplifying denial of service requests against the client. Brokers themselves could be overloaded as they allocate resources to track created subscriptions. Even with systems that do not rely on brokers, a subscriber might be able to receive data that it is not authorized to receive. An unauthorized publisher may be able to introduce incorrect or damaging messages into the pub/sub system. This is especially true with systems that broadcast or multicast their messages. Encryption (e.g. Transport Layer Security (SSL/TLS)) can prevent unauthorized access, but cannot prevent damaging messages from being introduced by authorized publishers. Architectures other than pub/sub, such as client/server systems, are also vulnerable to authorized message senders that behave maliciously. Publish/subscribe 134

References

External links

• hmbdc: a low latency high throughput C++14 messaging framework based on disruptor (https:/ / bitbucket. org/

hmbd/ hmbdc-rel/ overview)

• Amazon SNS - Pub/Sub Service by AWS (http:/ / aws. amazon. com/ sns/ )

• Azure Service Bus - Pub/Sub Service by Microsoft Azure (https:/ / docs. microsoft. com/ en-us/ azure/

service-bus/ )

• Chabok Push - Iranian Pub/Sub (http:/ / chabokpush. com/ )

• Google Cloud Pub/Sub - Pub/Sub service by Google Cloud Platform (https:/ / cloud. google. com/ pubsub/ ) • IBM MQ

• XMPP XEP-0060: Publish-Subscribe (http:/ / xmpp. org/ extensions/ xep-0060. html)

• Message Broker MQTT With Publish-Subscribe Paradigm (https:/ / web. archive. org/ web/ 20180222200528/

http:/ / mqtt. org/ ) • For an open source example which is in production on MSN.com and Microsoft.com, see Distributed

Publish/Subscribe Event System (http:/ / www. codeplex. com/ pubsub)

• Python PubSub (http:/ / pubsub. sf. net) a Python Publish-Subscribe broker for messages *within* an application (NOT network)

• The OMG DDS portal (http:/ / portals. omg. org/ dds)

• libpubsub-cpp (https:/ / github. com/ cinemast/ libpubsub-cpp) a topic based Publish/Subscribe framework implemented in C++

• Publish Subscribe example in C++ (https:/ / web. archive. org/ web/ 20121120005844/ http:/ / rtmatheson. com/

2010/ 03/ working-on-the-subject-observer-pattern/ )

• Synapse is a C++ framework that implements a Publish-subscribe pattern (http:/ / open. syn3. nl/ syn3/ trac/

default/ wiki/ projects/ synapse)

• Programmer Question-Answer topics tagged with "publish-subscribe" (https:/ / stackoverflow. com/ questions/

tagged/ publish-subscribe)

• Hermes, a message broker built on top of (http:/ / hermes. allegro. tech/ ) Design pattern Servant 135 Design pattern Servant

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In software engineering, the servant pattern defines an object used to offer some functionality to a group of Class (computer science)classes without defining that functionality in each of them. A Servant is a class whose Object (computer science)instance (or even just class) provides Method (computer science)methods that take care of a desired service, while objects for which (or with whom) the servant does something, are taken as Parameter (computer science)parameters.Description and simple example Servant is used for providing some behavior to a group of classes. Instead of defining that behavior in each class - or when we cannot factor out this behavior in the common parent class - it is defined once in the Servant. For example: we have a few classes representing geometric objects (rectangle, ellipse, and triangle). We can draw these objects on some canvas. When we need to provide a “move” method for these objects we could implement this method in each class, or we can define an interface they implement and then offer the “move” functionality in a servant. An interface is defined to ensure that serviced classes have methods, that servant needs to provide desired behavior. If we continue in our example, we define an Interface “Movable” specifying that every class implementing this interface needs to implement method “getPosition” and “setPosition”. The first method gets the position of an object on a canvas and second one sets the position of an object and draws it on a canvas. Then we define a servant class “MoveServant”, which has two methods “moveTo(Movable movedObject, Position where)” and moveBy(Movable movedObject, int dx, int dy). The Servant class can now be used to move every object which implements the Movable. Thus the “moving” code appears in only one class which respects the “Separation of Concerns” rule. Two ways of implementation There are two ways to implement this design pattern. Figure 1: User uses servant to achieve some functionality and passes the serviced objects as parameters. User knows the servant (in which case he doesn’t need to know the serviced classes) and sends messages with his requests to the servant instances, passing the serviced objects as parameters. The serviced classes (geometric objects from our example) don’t know about servant, but they implement the “IServiced” interface. The user class just calls the method of servant and passes serviced objects as parameters. This situation is shown on figure 1. Figure 2: User requests operations from serviced instances, which then asks servant to do it for them. Serviced instances know the servant and the user sends them messages with his requests (in which case she doesn’t have to know the servant). The serviced instances then send messages to the instances of servant, asking for service. On figure 2 is shown opposite situation, where user don’t know about servant class and calls directly serviced classes. Serviced classes then asks servant themselves to achieve desired functionality. How to implement Servant Analyze what behavior servant should take care of. State what methods servant will define and what these methods will need from serviced parameter. By other words, what serviced instance must provide, so that servants methods can achieve their goals. Analyze what abilities serviced classes must have, so they can be properly serviced. We define an interface, which will enforce implementation of declared methods. Define an interface specifying requested behavior of serviced objects. If some instance wants to be served by servant, it must implement this interface. Define (or acquire somehow) specified servant (his class). Implement defined interface with serviced classes. ExampleThis simple example shows the situation described above. This example is only illustrative and will not offer any actual drawing of geometric objects, nor specification of what they look like. // Servant class, offering its functionality to classes implementing // Movable Interface public class MoveServant { // Method, which will move Movable implementing class to position where public void moveTo(Movable serviced, Position where) { // Do Design pattern Servant 136

some other stuff to ensure it moves smoothly and nicely, this is // the place to offer the functionality serviced.setPosition(where); } // Method, which will move Movable implementing class by dx and dy public void moveBy(Movable serviced, int dx, int dy) { // this is the place to offer the functionality dx += serviced.getPosition().xPosition; dy += serviced.getPosition().yPosition; serviced.setPosition(new Position(dx, dy)); } } // Interface specifying what serviced classes needs to implement, to be // serviced by servant. public interface Movable { public void setPosition(Position p); public Position getPosition(); } // One of geometric classes public class Triangle implements Movable { // Position of the geometric object on some canvas private Position p; // Method, which sets position of geometric object public void setPosition(Position p) { this.p = p; } // Method, which returns position of geometric object public Position getPosition() { return this.p; } } // One of geometric classes public class Ellipse implements Movable { // Position of the geometric object on some canvas private Position p; // Method, which sets position of geometric object public void setPosition(Position p) { this.p = p; } // Method, which returns position of geometric object public Position getPosition() { return this.p; } } // One of geometric classes public class Rectangle implements Movable { // Position of the geometric object on some canvas private Position p; // Method, which sets position of geometric object public void setPosition(Position p) { this.p = p; } // Method, which returns position of geometric object public Position getPosition() { return this.p; } } // Just a very simple container class for position. public class Position { public int xPosition; public int yPosition; public Position(int dx, int dy) { xPosition = dx; yPosition = dy; } } Similar design pattern: Command Design patterns Command patternCommand and Servant are very similar and implementations of them are often virtually the same. The difference between them is the approach to the problem. For the Servant pattern we have some objects to which we want to offer some functionality. We create a class whose instances offer that functionality and which defines an interface that serviced objects must implement. Serviced instances are then passed as parameters to the servant. For the Command pattern we have some objects that we want to modify with some functionality. So, we define an interface which commands which desired functionality must be implemented. Instances of those commands are then passed to original objects as parameters of their methods. Even though design patterns Command and Servant are similar it doesn’t mean it’s always like that. There are a number of situations where use of design pattern Command doesn’t relate to the design pattern Servant. In these situations we usually need to pass to called methods just a reference to another method, which it will need in accomplishing its goal. Since we can’t pass references to methods in many languages, we have to pass an object implementing an interface which declares the signature of passed method. Resources Pecinovský, Rudolf; Jarmila Pavlíčková; Luboš Pavlíček (June 2006). Let's Modify the Objects First Approach into Design Patterns First (PDF). Eleventh Annual Conference on Innovation and Technology in Computer Science Education, University of Bologna. 137 Specification pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

Specification Pattern in Unified Modeling LanguageUML In computer programming, the specification pattern is a particular software design pattern, whereby business rules can be recombined by chaining the business rules together using boolean logic. The pattern is frequently used in the context of domain-driven design.A specification pattern outlines a business rule that is combinable with other business rules. In this pattern, a unit of business logic inherits its functionality from the abstract aggregate Composite Specification class. The Composite Specification class has one function called IsSatisfiedBy that returns a boolean value. After instantiation, the specification is "chained" with other specifications, making new specifications easily maintainable, yet highly customizable business logic. Furthermore, upon instantiation the business logic may, through method invocation or inversion of control, have its state altered in order to become a delegate of other classes such as a persistence repository. Code examples C Sharp (programming language)C# public interface ISpecification { bool IsSatisfiedBy(object candidate); ISpecification And(ISpecification other); ISpecification AndNot(ISpecification other); ISpecification Or(ISpecification other); ISpecification OrNot(ISpecification other); ISpecification Not(); } public abstract class CompositeSpecification : ISpecification { public abstract bool IsSatisfiedBy(object candidate); public ISpecification And(ISpecification other) { return new AndSpecification(this, other); } public ISpecification AndNot(ISpecification other) { return new AndNotSpecification(this, other); } public ISpecification Or(ISpecification other) { return new OrSpecification(this, other); } public ISpecification OrNot(ISpecification other) { return new OrNotSpecification(this, other); } public ISpecification Not() { return new NotSpecification(this); } } public class AndSpecification : CompositeSpecification { private ISpecification leftCondition; private ISpecification rightCondition; public AndSpecification(ISpecification left, ISpecification right) { leftCondition = left; rightCondition = right; } public override bool IsSatisfiedBy(object candidate) { return leftCondition.IsSatisfiedBy(candidate) && rightCondition.IsSatisfiedBy(candidate); } } public class AndNotSpecification : CompositeSpecification { private ISpecification leftCondition; private ISpecification rightCondition; public AndNotSpecification(ISpecification left, ISpecification right) { leftCondition = left; rightCondition = right; } public override bool IsSatisfiedBy(object candidate) { return leftCondition.IsSatisfiedBy(candidate) && rightCondition.IsSatisfiedBy(candidate) != true; } } public class OrSpecification : CompositeSpecification { private ISpecification leftCondition; private ISpecification rightCondition; public OrSpecification(ISpecification left, ISpecification right) { leftCondition = left; rightCondition = right; } public override bool IsSatisfiedBy(object candidate) { return leftCondition.IsSatisfiedBy(candidate) || rightCondition.IsSatisfiedBy(candidate); } } public class OrNotSpecification : CompositeSpecification { private ISpecification leftCondition; private ISpecification rightCondition; public OrNotSpecification(ISpecification left, ISpecification right) { leftCondition = left; rightCondition = right; } public override bool IsSatisfiedBy(object candidate) { return leftCondition.IsSatisfiedBy(candidate) || rightCondition.IsSatisfiedBy(candidate) != true; } } public class NotSpecification : CompositeSpecification { private ISpecification Wrapped; public NotSpecification(ISpecification x) { Wrapped = x; } public override bool IsSatisfiedBy(object candidate) { return !Wrapped.IsSatisfiedBy(candidate); } } C Sharp (programming language)C# 6.0 with generics public interface ISpecification { bool IsSatisfiedBy(T candidate); ISpecification And(ISpecification other); ISpecification AndNot(ISpecification other); ISpecification Or(ISpecification other); ISpecification OrNot(ISpecification other); ISpecification Not(); } public abstract class Specification pattern 138

LinqSpecification : CompositeSpecification { public abstract Expression> AsExpression(); public override bool IsSatisfiedBy(T candidate) => AsExpression().Compile()(candidate); } public abstract class CompositeSpecification : ISpecification { public abstract bool IsSatisfiedBy(T candidate); public ISpecification And(ISpecification other) => new AndSpecification(this, other); public ISpecification AndNot(ISpecification other) => new AndNotSpecification(this, other); public ISpecification Or(ISpecification other) => new OrSpecification(this, other); public ISpecification OrNot(ISpecification other) => new OrNotSpecification(this, other); public ISpecification Not() => new NotSpecification(this); } public class AndSpecification : CompositeSpecification { ISpecification left; ISpecification right; public AndSpecification(ISpecification left, ISpecification right) { this.left = left; this.right = right; } public override bool IsSatisfiedBy(T candidate) => left.IsSatisfiedBy(candidate) && right.IsSatisfiedBy(candidate); } public class AndNotSpecification : CompositeSpecification { ISpecification left; ISpecification right; public AndNotSpecification(ISpecification left, ISpecification right) { this.left = left; this.right = right; } public override bool IsSatisfiedBy(T candidate) => left.IsSatisfiedBy(candidate) && !right.IsSatisfiedBy(candidate); } public class OrSpecification : CompositeSpecification { ISpecification left; ISpecification right; public OrSpecification(ISpecification left, ISpecification right) { this.left = left; this.right = right; } public override bool IsSatisfiedBy(T candidate) => left.IsSatisfiedBy(candidate) || right.IsSatisfiedBy(candidate); } public class OrNotSpecification : CompositeSpecification { ISpecification left; ISpecification right; public OrNotSpecification(ISpecification left, ISpecification right) { this.left = left; this.right = right; } public override bool IsSatisfiedBy(T candidate) => left.IsSatisfiedBy(candidate) || !right.IsSatisfiedBy(candidate); } public class NotSpecification : CompositeSpecification { ISpecification other; public NotSpecification(ISpecification other) => this.other = other; public override bool IsSatisfiedBy(T candidate) => !other.IsSatisfiedBy(candidate); } Python (programming language)Python from abc import abstractmethod from dataclasses import dataclass from typing import Any class BaseSpecification: @abstractmethod def is_satisfied_by(self, candidate: Any) -> bool: raise NotImplementedError() def and_(self, other: "BaseSpecification") -> "AndSpecification": return AndSpecification(self, other) def or_(self, other: "BaseSpecification") -> "OrSpecification": return OrSpecification(self, other) def not_(self) -> "NotSpecification": return NotSpecification(self) @dataclass(frozen=True) class AndSpecification(BaseSpecification): first: BaseSpecification second: BaseSpecification def is_satisfied_by(self, candidate: Any) -> bool: return self.first.is_satisfied_by(candidate) and self.second.is_satisfied_by(candidate) @dataclass(frozen=True) class OrSpecification(BaseSpecification): first: BaseSpecification second: BaseSpecification def is_satisfied_by(self, candidate: Any) -> bool: return self.first.is_satisfied_by(candidate) or self.second.is_satisfied_by(candidate) @dataclass(frozen=True) class NotSpecification(BaseSpecification): subject: BaseSpecification def is_satisfied_by(self, candidate: Any) -> bool: return not self.subject.is_satisfied_by(candidate) Example of useIn the following example, we are retrieving invoices and sending them to a collection agency if they are overdue, notices have been sent, and they are not already with the collection agency. This example is meant to show the end result of how the logic is 'chained' together. This usage example assumes a previously defined OverdueSpecification class that is satisfied when an invoice's due date is 30 days or older, a NoticeSentSpecification class that is satisfied when three notices have been sent to the customer, and an InCollectionSpecification class that is satisfied when an invoice has already been sent to the collection agency. The implementation of these classes isn't important here. Using these three specifications, we created a new specification called SendToCollection which will be satisfied when an invoice is overdue, when notices have been sent to the customer, and are not already with the collection agency. var OverDue = new OverDueSpecification(); var NoticeSent = new NoticeSentSpecification(); var InCollection = new InCollectionSpecification(); // example of specification pattern logic chaining var SendToCollection = OverDue.And(NoticeSent).And(InCollection.Not()); var InvoiceCollection = Service.GetInvoices(); foreach (var currentInvoice in InvoiceCollection) { if (SendToCollection.IsSatisfiedBy(currentInvoice)) { currentInvoice.SendToCollection(); } } Criticisms The Specification Pattern could be considered a software Specification pattern 139

anti-pattern: Cargo cult programming - There lacks a well-defined purpose for this pattern, and there's no guide when to implement it or not. Also, see Law of the instrument. Inner-platform effect - And() function which directly replicate Short-circuiting operator&& in C Sharp (programming language)C#. Also, Not() and potentially more. Also, see Reinventing the wheelReinventing the square wheel. Spaghetti code#Lasagna codeSpaghetti/Lasagna Code - Separate classes for each part of the specification fragments what could be a cohesive object. In the example above, OverDue is an extra layer between the logic for SendToCollection and the OverDueSpecification implementation. Most natural programming languages can accommodate domain-driven design with the core object-oriented concepts. Alternative example, without the Specification Pattern: var InvoiceCollection = Service.GetInvoices(); foreach (var invoice in InvoiceCollection) invoice.SendToCollectionIfNecessary(); // Invoice methods: public void SendToCollectionIfNecessary() { if (ShouldSendToCollection()) SendToCollection(); } private bool ShouldSendToCollection() => currentInvoice.OverDue && currentInvoice.NoticeSent && !currentInvoice.InCollection; This alternative uses foundation concepts of get-only properties, condition logic, and functions. The key alternative here is Get-Only Properties, which are well-named to maintain the domain-driven language, and enable the continued use of the natural && operator, instead of the Specification Pattern's And() function. Furthermore, the creation of a well-named function SendToCollectionIfNecessary is potentially more useful and descriptive, than the previous example (which could also be contained in such a function, except not directly on the object apparently). ReferencesEvans, Eric (2004). Domain Driven Design. Addison-Wesley. p. 224.External links Specifications by Eric Evans and Martin Fowler The Specification Pattern: A Primer by Matt Berther The Specification Pattern: A Four Part Introduction using VB.Net by Richard Dalton The Specification Pattern in PHP by Moshe Brevda Happyr Doctrine Specification in PHP by Happyr The Specification Pattern in Swift by Simon Strandgaard The Specification Pattern in TypeScript and JavaScript by Thiago Delgado Pinto specification pattern in flash 3 by Rolf Vreijdenberger State pattern 140 State pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

The state pattern is a Behavioral patternbehavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.The state pattern is used in computer programming to encapsulate varying behavior for the same object (computer science)object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.:395Overview The state design pattern is one of twenty-three Design Patternsdesign patterns documented by the Gang of Four that describe how to solve recurring design problems. Such problems cover the design of flexible and reusable object-oriented software, such as objects that are easy to implement, change, test, and reuse.The state pattern is set to solve two main problems: An object should change its behavior when its internal state changes. State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states. Implementing state-specific behavior directly within a class is inflexible because it commits the class to a particular behavior and makes it impossible to add a new state or change the behavior of an existing state later independently from (without changing) the class. In this, the pattern describes two solutions: Define separate (state) objects that encapsulate state-specific behavior for each state. That is, define an interface (state) for performing state-specific behavior, and define classes that implement the interface for each state. A class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly. This makes a class independent of how state-specific behavior is implemented. New states can be added by defining new state classes. A class can change its behavior at run-time by changing its current state object. Structure A sample UML class and sequence diagram for the State design pattern.State in UML In the above Unified Modeling Language (UML) class diagram, the Context class doesn't implement state-specific behavior directly. Instead, Context refers to the State interface for performing state-specific behavior (state.operation()), which makes Context independent of how state-specific behavior is implemented. The State1 and State2 classes implement the State interface, that is, implement (encapsulate) the state-specific behavior for each state. The UML sequence diagram shows the run-time interactions: The Context object delegates state-specific behavior to different State objects. First, Context calls operation(this) on its current (initial) state object (State1), which performs the operation and calls setState(State2) on Context to change context's current state to State2. The next time, Context again calls operation(this) on its current state object (State2), which performs the operation and changes context's current state to State1. Example Java The state interface and two implementations. The state's method has a reference to the context object and is able to change its state. interface State { void writeName(StateContext context, String name); } class LowerCaseState implements State { @Override public void writeName(StateContext context, String name) { System.out.println(name.toLowerCase()); context.setState(new MultipleUpperCaseState()); } } class MultipleUpperCaseState implements State { /* Counter local to this state */ private int count = 0; @Override public void writeName(StateContext context, String name) { System.out.println(name.toUpperCase()); /* Change state after StateMultipleUpperCase's writeName() gets invoked twice */ if (++count > 1) { context.setState(new LowerCaseState()); } } } The context class has a state variable that it instantiates in an initial state, in this case LowerCaseState. In its method, it uses the corresponding methods of the state object. class StateContext { private State pattern 141

State state; public StateContext() { state = new LowerCaseState(); } /** * Set the current state. * Normally only called by classes implementing the State interface. * @param newState the new state of this context */ void setState(State newState) { state = newState; } public void writeName(String name) { state.writeName(this, name); } } The demonstration below shows the usage: public class StateDemo { public static void main(String[] args) { StateContext context = new StateContext(); context.writeName("Monday"); context.writeName("Tuesday"); context.writeName("Wednesday"); context.writeName("Thursday"); context.writeName("Friday"); context.writeName("Saturday"); context.writeName("Sunday"); } } With the above code, the output of main() from StateDemo is: monday TUESDAY WEDNESDAY thursday FRIDAY SATURDAY sunday References class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: State implementations in various languages

Strategy pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral design patternbehavioral design pattern (computer science)software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.Strategy lets the algorithm vary independently from clients that use it.Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, Head First Design Patterns, First Edition, Chapter 1, Page 24, O'Reilly Media, Inc, 2004. Strategy is one of the patterns included in the influential book Design Patterns by Gamma et al. that popularized the concept of using design patterns to describe how to design flexible and reusable object-oriented software. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known until run-time and may require radically different validation to be performed. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without Duplicate codecode duplication. Typically the strategy pattern stores a reference to some code in a data structure and retrieves it. This can be achieved by mechanisms such as the native function pointer, the first-class function, classes or class instances in object-oriented programming languages, or accessing the language implementation's internal storage of code via Reflection (computer science)reflection. Structure UML class and sequence diagram A sample UML class and sequence diagram for the Strategy design pattern. In the above Unified Modeling LanguageUML Class diagramclass diagram, the Context class doesn't implement an algorithm directly. Instead, Context refers to the Strategy interface for performing an algorithm (strategy.algorithm()), which makes Context independent of how an algorithm is implemented. The Strategy1 and Strategy2 classes implement the Strategy interface, that is, implement (encapsulate) an algorithm. The Unified Modeling LanguageUML Sequence diagramsequence diagram shows the run-time interactions: The Context object delegates an algorithm to different Strategy objects. First, Context calls algorithm() Strategy pattern 142

on a Strategy1 object, which performs the algorithm and returns the result to Context. Thereafter, Context changes its strategy and calls algorithm() on a Strategy2 object, which performs the algorithm and returns the result to Context. Class diagram Strategy Pattern in Unified Modeling LanguageUMLhttp://www.mcdonaldland.info/2007/11/28/40/Strategy pattern in LePUS3 ( legend)Example C# The following example is in C Sharp (programming language)C#. public class StrategyPatternWiki { public static void Main(String[] args) { // Prepare strategies var normalStrategy = new NormalStrategy(); var happyHourStrategy = new HappyHourStrategy(); var firstCustomer = new Customer(normalStrategy); // Normal billing firstCustomer.Add(1.0, 1); // Start Happy Hour firstCustomer.Strategy = happyHourStrategy; firstCustomer.Add(1.0, 2); // New Customer Customer secondCustomer = new Customer(happyHourStrategy); secondCustomer.Add(0.8, 1); // The Customer pays firstCustomer.PrintBill(); // End Happy Hour secondCustomer.Strategy = normalStrategy; secondCustomer.Add(1.3, 2); secondCustomer.Add(2.5, 1); secondCustomer.PrintBill(); } } class Customer { private IList drinks; // Get/Set Strategy public IBillingStrategy Strategy { get; set; } public Customer(IBillingStrategy strategy) { this.drinks = new List(); this.Strategy = strategy; } public void Add(double price, int quantity) { this.drinks.Add(this.Strategy.GetActPrice(price * quantity)); } // Payment of bill public void PrintBill() { double sum = 0; foreach (var drinkCost in this.drinks) { sum += drinkCost; } Console.WriteLine($"Total due: {sum}."); this.drinks.Clear(); } } interface IBillingStrategy { double GetActPrice(double rawPrice); } // Normal billing strategy (unchanged price) class NormalStrategy : IBillingStrategy { public double GetActPrice(double rawPrice) => rawPrice; } // Strategy for Happy hour (50% discount) class HappyHourStrategy : IBillingStrategy { public double GetActPrice(double rawPrice) => rawPrice * 0.5; } Java The following example is in Java (programming language)Java. import java.util.ArrayList; interface BillingStrategy { // Use a price in cents to avoid floating point round-off error int getActPrice(int rawPrice); // Normal billing strategy (unchanged price) static BillingStrategy normalStrategy() { return rawPrice -> rawPrice; } // Strategy for Happy hour (50% discount) static BillingStrategy happyHourStrategy() { return rawPrice -> rawPrice / 2; } } class Customer { private final List drinks = new ArrayList<>(); private BillingStrategy strategy; public Customer(BillingStrategy strategy) { this.strategy = strategy; } public void add(int price, int quantity) { this.drinks.add(this.strategy.getActPrice(price*quantity)); } // Payment of bill public void printBill() { int sum = this.drinks.stream().mapToInt(v -> v).sum(); System.out.println("Total due: " + sum); this.drinks.clear(); } // Set Strategy public void setStrategy(BillingStrategy strategy) { this.strategy = strategy; } } public class StrategyPattern { public static void main(String[] arguments) { // Prepare strategies BillingStrategy normalStrategy = BillingStrategy.normalStrategy(); BillingStrategy happyHourStrategy = BillingStrategy.happyHourStrategy(); Customer firstCustomer = new Customer(normalStrategy); // Normal billing firstCustomer.add(100, 1); // Start Happy Hour firstCustomer.setStrategy(happyHourStrategy); firstCustomer.add(100, 2); // New Customer Customer secondCustomer = new Customer(happyHourStrategy); secondCustomer.add(80, 1); // The Customer pays firstCustomer.printBill(); // End Happy Hour secondCustomer.setStrategy(normalStrategy); secondCustomer.add(130, 2); secondCustomer.add(250, 1); secondCustomer.printBill(); } } Strategy and open/closed principle Accelerate and brake behaviors must be declared in each new car model. According to the strategy pattern, the behaviors of a class should not be inherited. Instead they should be encapsulated using interfaces. This is compatible with the open/closed principle (OCP), which proposes that classes should be open for extension but closed for modification. As an example, consider a car class. Two possible functionalities for car are brake and accelerate. Since accelerate and brake behaviors change frequently between models, a common approach is to implement these behaviors in subclasses. This approach has significant drawbacks: accelerate and brake behaviors must be declared in each new Car model. The work of managing these behaviors increases greatly as the number of models increases, and requires code to be duplicated across models. Additionally, it is not easy to determine the exact nature of the behavior for each model without investigating the code in each.The strategy pattern uses composition over inheritancecomposition instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, Strategy pattern 143

and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at run-time as well as at design-time. For instance, a car object's brake behavior can be changed from BrakeWithABS() to Brake() by changing the brakeBehavior member to: brakeBehavior = new Brake(); /* Encapsulated family of Algorithms * Interface and its implementations */ public interface IBrakeBehavior { public void brake(); } public class BrakeWithABS implements IBrakeBehavior { public void brake() { System.out.println("Brake with ABS applied"); } } public class Brake implements IBrakeBehavior { public void brake() { System.out.println("Simple Brake applied"); } } /* Client that can use the algorithms above interchangeably */ public abstract class Car { private IBrakeBehavior brakeBehavior; public Car(IBrakeBehavior brakeBehavior) { this.brakeBehavior = brakeBehavior; } public void applyBrake() { brakeBehavior.brake(); } public void setBrakeBehavior(IBrakeBehavior brakeType) { this.brakeBehavior = brakeType; } } /* Client 1 uses one algorithm (Brake) in the constructor */ public class Sedan extends Car { public Sedan() { super(new Brake()); } } /* Client 2 uses another algorithm (BrakeWithABS) in the constructor */ public class SUV extends Car { public SUV() { super(new BrakeWithABS()); } } /* Using the Car example */ public class CarExample { public static void main(final String[] arguments) { Car sedanCar = new Sedan(); sedanCar.applyBrake(); // This will invoke class "Brake" Car suvCar = new SUV(); suvCar.applyBrake(); // This will invoke class "BrakeWithABS" // set brake behavior dynamically suvCar.setBrakeBehavior( new Brake() ); suvCar.applyBrake(); // This will invoke class "Brake" } } Referencesclass=noviewerWikimedia Commons has media related to Strategy (design pattern).External linksclass=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Strategy implementations in various languages Strategy Pattern in UML (in Spanish)Geary, David (April 26, 2002). "Strategy for success". Java Design Patterns. JavaWorld. Retrieved 2020-07-20. Strategy Pattern for C article Refactoring: Replace Type Code with State/Strategy The Strategy Design Pattern at the Wayback Machine (archived 2017-04-15) Implementation of the Strategy pattern in JavaScript Template method pattern 144 Template method pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In object-oriented programming, the template method is one of the behavioral patternbehavioral Software design patterndesign patterns identified by Gamma et al. in the book Design Patterns. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.The helper methods may be either Abstract methodabstract methods, for which case subclasses are required to provide concrete implementations, or hook methods, which have empty bodies in the superclass. Subclass (computer science)Subclasses can (but are not required to) customize the operation by Method overridingoverriding the hook methods. The intent of the template method is to define the overall structure of the operation, while allowing subclasses to refine, or redefine, certain steps.OverviewThis pattern has two main parts: The "template method" is implemented as a method in a base class (usually an abstract class). This method contains code for the parts of the overall algorithm that are invariant. The template ensures that the overarching algorithm is always followed. In the template method, portions of the algorithm that may vary are implemented by sending self messages that request the execution of additional helper methods. In the base class, these helper methods are given a default implementation, or none at all (that is, they may be abstract methods). Subclasses of the base class "fill in" the empty or "variant" parts of the "template" with specific algorithms that vary from one subclass to another. It is important that subclasses do not override the template method itself.At run-time, the algorithm represented by the template method is executed by sending the template message to an instance of one of the concrete subclasses. Through inheritance, the template method in the base class starts to execute. When the template method sends a message to self requesting one of the helper methods, the message will be received by the concrete sub-instance. If the helper method has been overridden, the overriding implementation in the sub-instance will execute; if it has not been overridden, the inherited implementation in the base class will execute. This mechanism ensures that the overall algorithm follows the same steps every time, while allowing the details of some steps to depend on which instance received the original request to execute the algorithm. This pattern is an example of inversion of control because the high-level code no longer determines what algorithms to run; a lower-level algorithm is instead selected at run-time. Some of the self messages sent by the template method may be to hook methods. These methods are implemented in the same base class as the template method, but with empty bodies (i.e., they do nothing). Hook methods exist so that subclasses can override them, and can thus fine-tune the action of the algorithm without the need to override the template method itself. In other words, they provide a "hook" on which to "hang" variant implementations.Structure UML class diagram A sample UML class diagram for the Template Method design pattern.In the above Unified Modeling LanguageUML class diagram, the AbstractClass defines a templateMethod() operation that defines the skeleton (template) of a behavior by implementing the invariant parts of the behavior and sending to self the messages primitive1() and primitive2() , which, because they are implemented in SubClass1 , allow that subclass to provide a variant implementation of those parts of the algorithm. Template Method in Lepus3LePUS3.LePUS3 legend. Retrieved from http://lepus.org.uk/ref/legend/legend.xml.UsageThe template method is used in frameworks, where each implements the invariant parts of a domain's architecture, while providing hook methods for customization. This is an example of inversion of control. The template method is used for the following reasons. It lets subclasses implement varying behavior (through (programming)overriding of the hook Template method pattern 145

methods). It avoids duplication in the code: the general workflow of the algorithm is implemented once in the abstract class's template method, and necessary variations are implemented in the subclasses. It controls the point(s) at which specialization is permitted. If the subclasses were to simply override the template method, they could make radical and arbitrary changes to the workflow. In contrast, by overriding only the hook methods, only certain specific details of the workflow can be changed, and the overall workflow is left intact. Use with code generators The template pattern is useful when working with auto-generated code. The challenge of working with generated code is that changes to the source code will lead to changes in the generated code; if hand-written modifications have been made to the generated code, these will be lost. How, then, should the generated code be customized? The Template pattern provides a solution. If the generated code follows the template method pattern, the generated code will all be an abstract superclass. Provided that hand-written customizations are confined to a subclass, the code generator can be run again without risk of over-writing these modifications. When used with code generation, this pattern is sometimes referred to as the Generation gap (pattern)generation gap pattern.PHP Example abstract class Game { abstract protected function initialize(); abstract protected function startPlay(); abstract protected function endPlay(); /** Template method */ public final function play() { /** Primitive */ $this->initialize(); /** Primitive */ $this->startPlay(); /** Primitive */ $this->endPlay(); } } class Mario extends Game { protected function initialize() { echo "Mario Game Initialized! Start playing.". PHP_EOL; } protected function startPlay() { echo "Mario Game Started. Enjoy the game!". PHP_EOL; } protected function endPlay() { echo "Mario Game Finished!". PHP_EOL; } } class Tankfight extends Game { protected function initialize() { echo "Tankfight Game Initialized! Start playing.". PHP_EOL; } protected function startPlay() { echo "Tankfight Game Started. Enjoy the game!". PHP_EOL; } protected function endPlay() { echo "Tankfight Game Finished!". PHP_EOL; } } $game = new Tankfight(); $game->play(); $game = new Mario(); $game->play(); References External links class=noviewerThe Wikibook has a page on the topic of: Template method Six common uses of the template pattern Working with Template Classes in PHP 5 Template Method Design Pattern 146 Visitor pattern

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

In object-oriented programming and software engineering, the visitor Software design patterndesign pattern is a way of separating an algorithm from an Object (computer science)object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures. It is one way to follow the open/closed principle.In essence, the visitor allows adding new virtual functions to a family of Class (computer programming)classes, without modifying the classes. Instead, a visitor class is created that implements all of the appropriate specializations of the . The visitor takes the instance reference as input, and implements the goal through . Overview The Visitor design pattern is one of the twenty-three well-known Design PatternsGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. What problems can the Visitor design pattern solve? It should be possible to define a new operation for (some) classes of an object structure without changing the classes. When new operations are needed frequently and the object structure consists of many unrelated classes, it's inflexible to add new subclasses each time a new operation is required because "[..] distributing all these operations across the various node classes leads to a system that's hard to understand, maintain, and change." What solution does the Visitor design pattern describe? Define a separate (visitor) object that implements an operation to be performed on elements of an object structure. Clients traverse the object structure and call a dispatching operation accept(visitor) on an element — that "dispatches" (delegates) the request to the "accepted visitor object". The visitor object then performs the operation on the element ("visits the element").This makes it possible to create new operations independently from the classes of an object structure by adding new visitor objects. See also the UML class and sequence diagram below. Definition The Design PatternsGang of Four defines the Visitor as: Represent[ing] an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.The nature of the Visitor makes it an ideal pattern to plug into public thus allowing its clients to perform operations on a class using a "visiting" class without having to modify the source. Visitor pattern real-world exampleUses Moving operations into visitor classes is beneficial when many unrelated operations on an object structure are required, the classes that make up the object structure are known and not expected to change, new operations need to be added frequently, an algorithm involves several classes of the object structure, but it is desired to manage it in one single location, an algorithm needs to work across several independent class hierarchies. A drawback to this pattern, however, is that it makes extensions to the class hierarchy more difficult, as new classes typically require a new visit method to be added to each visitor. Use case example Consider the design of a 2D computer-aided design (CAD) system. At its core there are several types to represent basic geometric shapes like circles, lines, and arcs. The entities are ordered into layers, and at the top of the type hierarchy is the drawing, which is simply a list of layers, plus some added properties. A fundamental operation on this type hierarchy is saving a drawing to the system's native file format. At first glance it may seem acceptable to add local save methods to all types in the hierarchy. But it is also useful to be able to save drawings to other file formats. Adding ever more methods for saving into many different file formats soon clutters the relatively pure original geometric data structure. A naive way to solve this would be to maintain separate functions for each file format. Such a save function would take a drawing as input, traverse it, and encode into that specific file format. As Visitor pattern 147

this is done for each added different format, duplication between the functions accumulates. For example, saving a circle shape in a raster format requires very similar code no matter what specific raster form is used, and is different from other primitive shapes. The case for other primitive shapes like lines and polygons is similar. Thus, the code becomes a large outer loop traversing through the objects, with a large decision tree inside the loop querying the type of the object. Another problem with this approach is that it is very easy to miss a shape in one or more savers, or a new primitive shape is introduced, but the save routine is implemented only for one file type and not others, leading to code extension and maintenance problems. Instead, the visitor pattern can be applied. It encodes a logical operation on the whole hierarchy into one class containing one method per type. In the CAD example, each save function would be implemented as a separate Visitor subclass. This would remove all duplication of type checks and traversal steps. It would also make the compiler complain if a shape is omitted. Another motive is to reuse iteration code. For example, iterating over a directory structure could be implemented with a visitor pattern. This would allow creating file searches, file backups, directory removal, etc., by implementing a visitor for each function while reusing the iteration code. Structure UML class and sequence diagram A sample UML class diagram and sequence diagram for the Visitor design pattern.In the above Unified Modeling LanguageUML class diagram, the ElementA class doesn't implement a new operation directly. Instead, ElementA implements a dispatching operation accept(visitor) that "dispatches" (delegates) a request to the "accepted visitor object" (visitor.visitElementA(this)). The Visitor1 class implements the operation (visitElementA(e:ElementA)).ElementB then implements accept(visitor) by dispatching to visitor.visitElementB(this). The Visitor1 class implements the operation (visitElementB(e:ElementB)). The Unified Modeling LanguageUML sequence diagram shows the run-time interactions: The Client object traverses the elements of an object structure (ElementA,ElementB) and calls accept(visitor) on each element. First, the Client calls accept(visitor) on ElementA, which calls visitElementA(this) on the accepted visitor object. The element itself (this) is passed to the visitor so that it can "visit" ElementA (call operationA()). Thereafter, the Client calls accept(visitor) on ElementB, which calls visitElementB(this) on the visitor that "visits" ElementB (calls operationB()). Class diagram Visitor in Unified Modeling Language (UML)Visitor in Lepus3LePUS3 ( legend)Details The visitor pattern requires a programming language that supports single dispatch, as common object-oriented languages (such as C++, Java (programming language)Java, Smalltalk, Objective-C, Swift (programming language)Swift, JavaScript, Python (programming language)Python and C Sharp (programming language)C#) do. Under this condition, consider two objects, each of some class type; one is termed the element, and the other is visitor.The visitor declares a visit method, which takes the element as an argument, for each class of element. Concrete visitors are derived from the visitor class and implement these visit methods, each of which implements part of the algorithm operating on the object structure. The state of the algorithm is maintained locally by the concrete visitor class.The element declares an accept method to accept a visitor, taking the visitor as an argument. Concrete elements, derived from the element class, implement the accept method. In its simplest form, this is no more than a call to the visitor's visit method. Composite patternComposite elements, which maintain a list of child objects, typically iterate over these, calling each child's accept method.The client creates the object structure, directly or indirectly, and instantiates the concrete visitors. When an operation is to be performed which is implemented using the Visitor pattern, it calls the accept method of the top-level element(s).When the accept method is called in the program, its implementation is chosen based on both the dynamic type of the element and the static type of the visitor. When the associated visit method is called, its implementation is chosen based on both the dynamic type of the visitor and the static type of the element, as known from within the implementation of the accept method, which is the same as the dynamic type of the element. (As a bonus, if the visitor can't handle an argument of the given element's type, then the compiler will catch the error.) Thus, the implementation of the visit method is chosen based on both the dynamic type of the element and the dynamic type of the visitor. This effectively implements double dispatch. For languages whose object systems support , not only single dispatch, such as Common Lisp or C Sharp (programming language)C# via the Dynamic Language Runtime (DLR), implementation of the visitor pattern is greatly simplified (a.k.a. Dynamic Visitor) by allowing use of simple to cover all the cases being visited. A dynamic visitor, provided it operates on public data only, Visitor pattern 148

conforms to the open/closed principle (since it does not modify extant structures) and to the single responsibility principle (since it implements the Visitor pattern in a separate component). In this way, one algorithm can be written to traverse a graph of elements, and many different kinds of operations can be performed during that traversal by supplying different kinds of visitors to interact with the elements based on the dynamic types of both the elements and the visitors. C# example This example shows how to print a tree representing a numeric expression involving literals and their addition. The same example is presented using both classic and Dynamic Language Runtime implementations. Dynamic visitor This example declares a separate ExpressionPrinter class that takes care of the printing. The expression classes must expose their members to make this possible. using System; using System.Text; namespace Wikipedia { abstract class Expression { } class Literal : Expression { public double Value { get; set; } public Literal(double value) { this.Value = value; } } class Addition : Expression { public Expression Left { get; set; } public Expression Right { get; set; } public Addition(Expression left, Expression right) { Left = left; Right = right; } } class ExpressionPrinter { public static void Print(Literal literal, StringBuilder sb) { sb.Append(literal.Value); } public static void Print(Addition addition, StringBuilder sb) { sb.Append("("); Print((dynamic) addition.Left, sb); sb.Append("+"); Print((dynamic) addition.Right, sb); sb.Append(")"); } } class Program { static void Main(string[] args) { // Emulate 1 + 2 + 3 var e = new Addition( new Addition( new Literal(1), new Literal(2) ), new Literal(3) ); var sb = new StringBuilder(); ExpressionPrinter.Print((dynamic) e, sb); Console.WriteLine(sb); } } } Smalltalk example In this case, it is the object's responsibility to know how to print itself on a stream. The visitor here is then the object, not the stream. "There's no syntax for creating a class. Classes are created by sending messages to other classes." WriteStream subclass: #ExpressionPrinter instanceVariableNames: '' classVariableNames: '' package: 'Wikipedia'. ExpressionPrinter>>write: anObject "Delegates the action to the object. The object doesn't need to be of any special class; it only needs to be able to understand the message #putOn:" anObject putOn: self. ^ anObject. Object subclass: #Expression instanceVariableNames: '' classVariableNames: '' package: 'Wikipedia'. Expression subclass: #Literal instanceVariableNames: 'value' classVariableNames: '' package: 'Wikipedia'. Literal class>>with: aValue "Class method for building an instance of the Literal class" ^ self new value: aValue; yourself. Literal>>value: aValue "Setter for value" value := aValue. Literal>>putOn: aStream "A Literal object knows how to print itself" aStream nextPutAll: value asString. Expression subclass: #Addition instanceVariableNames: 'left right' classVariableNames: '' package: 'Wikipedia'. Addition class>>left: a right: b "Class method for building an instance of the Addition class" ^ self new left: a; right: b; yourself. Addition>>left: anExpression "Setter for left" left := anExpression. Addition>>right: anExpression "Setter for right" right := anExpression. Addition>>putOn: aStream "An Addition object knows how to print itself" aStream nextPut: $(. left putOn: aStream. aStream nextPut: $+. right putOn: aStream. aStream nextPut: $). Object subclass: #Program instanceVariableNames: '' classVariableNames: '' package: 'Wikipedia'. Program>>main | expression stream | expression := Addition left: (Addition left: (Literal with: 1) right: (Literal with: 2)) right: (Literal with: 3). stream := ExpressionPrinter on: (String new: 100). stream write: expression. Transcript show: stream contents. Transcript flush. C++ example Sources #include #include class AbstractDispatcher; // Forward declare AbstractDispatcher class File { // Parent class for the elements (ArchivedFile, SplitFile and // ExtractedFile) public: // This function accepts an object of any class derived from // AbstractDispatcher and must be implemented in all derived classes virtual void Accept(AbstractDispatcher& dispatcher) = 0; }; // Forward declare specific elements (files) to be dispatched class ArchivedFile; class SplitFile; class ExtractedFile; class AbstractDispatcher { // Declares the interface for the dispatcher public: // Declare overloads for each kind of a file to dispatch virtual void Dispatch(ArchivedFile& file) = 0; virtual void Dispatch(SplitFile& file) = 0; virtual void Dispatch(ExtractedFile& file) = 0; }; class ArchivedFile : public File { // Specific element class #1 public: // Resolved at runtime, it calls the dispatcher's overloaded function, // corresponding to ArchivedFile. void Accept(AbstractDispatcher& dispatcher) override { dispatcher.Dispatch(*this); } }; class SplitFile : public File { // Specific element class #2 public: // Resolved at runtime, it calls the dispatcher's overloaded function, // corresponding to SplitFile. void Accept(AbstractDispatcher& dispatcher) override { dispatcher.Dispatch(*this); } }; class ExtractedFile : public File { // Specific element class #3 public: // Resolved at runtime, it calls the dispatcher's overloaded function, // corresponding to ExtractedFile. void Visitor pattern 149

Accept(AbstractDispatcher& dispatcher) override { dispatcher.Dispatch(*this); } }; class Dispatcher : public AbstractDispatcher { // Implements dispatching of all // kind of elements (files) public: void Dispatch(ArchivedFile&) override { std::cout << "dispatching ArchivedFile" << std::endl; } void Dispatch(SplitFile&) override { std::cout << "dispatching SplitFile" << std::endl; } void Dispatch(ExtractedFile&) override { std::cout << "dispatching ExtractedFile" << std::endl; } }; int main() { ArchivedFile archived_file; SplitFile split_file; ExtractedFile extracted_file; std::vector files = { &archived_file, &split_file, &extracted_file, }; Dispatcher dispatcher; for (File* file : files) { file->Accept(dispatcher); } } Output dispatching ArchivedFile dispatching SplitFile dispatching ExtractedFile Go example Go does not support overloading, so the visit methods need different names. Sources package main import "fmt" type Visitor interface { visitWheel(wheel Wheel) string visitEngine(engine Engine) string visitBody(body Body) string visitCar(car Car) string } type element interface { Accept(visitor Visitor) string } type Wheel struct { name string } func (w *Wheel) Accept(visitor Visitor) string { return visitor.visitWheel(*w) } func (w *Wheel) getName() string { return w.name } type Engine struct{} func (e *Engine) Accept(visitor Visitor) string { return visitor.visitEngine(*e) } type Body struct{} func (b *Body) Accept(visitor Visitor) string { return visitor.visitBody(*b) } type Car struct { engine Engine body Body wheels [4]Wheel } func (c *Car) Accept(visitor Visitor) string { elements := []element{ &c.engine, &c.body, &c.wheels[0], &c.wheels[1], &c.wheels[2], &c.wheels[3], } res := visitor.visitCar(*c) for _, elem := range elements { res += elem.Accept(visitor) } return res } type PrintVisitor struct{} func (pv *PrintVisitor) visitWheel(wheel Wheel) string { return fmt.Sprintln("visiting", wheel.getName(), "wheel") } func (pv *PrintVisitor) visitEngine(engine Engine) string { return fmt.Sprintln("visiting engine") } func (pv *PrintVisitor) visitBody(body Body) string { return fmt.Sprintln("visiting body") } func (pv *PrintVisitor) visitCar(car Car) string { return fmt.Sprintln("visiting car") } /* output: visiting car visiting engine visiting body visiting front left wheel visiting front right wheel visiting back left wheel visiting back right wheel */ func main() { car := Car{ engine: Engine{}, body: Body{}, wheels: [4]Wheel{ {"front left"}, {"front right"}, {"back left"}, {"back right"}, }, } visitor := PrintVisitor{} res := car.Accept(&visitor) fmt.Println(res) } Output visiting car visiting engine visiting body visiting front left wheel visiting front right wheel visiting back left wheel visiting back right wheel Java example The following example is in the language Java (programming language)Java, and shows how the contents of a tree of nodes (in this case describing the components of a car) can be printed. Instead of creating print methods for each node subclass (Wheel, Engine, Body, and Car), one visitor class (CarElementPrintVisitor) performs the required printing action. Because different node subclasses require slightly different actions to print properly, CarElementPrintVisitor dispatches actions based on the class of the argument passed to its visit method. CarElementDoVisitor, which is analogous to a save operation for a different file format, does likewise. Diagram UML diagram of the Visitor pattern example with Car ElementsSources import java.util.List; interface CarElement { void accept(CarElementVisitor visitor); } interface CarElementVisitor { void visit(Body body); void visit(Car car); void visit(Engine engine); void visit(Wheel wheel); } class Wheel implements CarElement { private final String name; public Wheel(final String name) { this.name = name; } public String getName() { return name; } @Override public void accept(CarElementVisitor visitor) { /* * accept(CarElementVisitor) in Wheel implements * accept(CarElementVisitor) in CarElement, so the call * to accept is bound at run time. This can be considered * the *first* dispatch. However, the decision to call * visit(Wheel) (as opposed to visit(Engine) etc.) can be * made during compile time since 'this' is known at compile * time to be a Wheel. Moreover, each implementation of * CarElementVisitor implements the visit(Wheel), which is * another decision that is made at run time. This can be * considered the *second* dispatch. */ visitor.visit(this); } } class Body implements CarElement { @Override public void accept(CarElementVisitor visitor) { visitor.visit(this); } } class Engine implements CarElement { @Override public void accept(CarElementVisitor visitor) { visitor.visit(this); } } class Car implements CarElement { private final List elements; public Car() { this.elements = List.of( new Wheel("front left"), new Wheel("front right"), new Wheel("back left"), new Wheel("back right"), new Body(), new Engine() ); } @Override public void accept(CarElementVisitor visitor) { for (CarElement element : elements) { element.accept(visitor); } visitor.visit(this); } } class CarElementDoVisitor implements CarElementVisitor { @Override public void visit(Body body) { System.out.println("Moving my body"); Visitor pattern 150

} @Override public void visit(Car car) { System.out.println("Starting my car"); } @Override public void visit(Wheel wheel) { System.out.println("Kicking my " + wheel.getName() + " wheel"); } @Override public void visit(Engine engine) { System.out.println("Starting my engine"); } } class CarElementPrintVisitor implements CarElementVisitor { @Override public void visit(Body body) { System.out.println("Visiting body"); } @Override public void visit(Car car) { System.out.println("Visiting car"); } @Override public void visit(Engine engine) { System.out.println("Visiting engine"); } @Override public void visit(Wheel wheel) { System.out.println("Visiting " + wheel.getName() + " wheel"); } } public class VisitorDemo { public static void main(final String[] args) { Car car = new Car(); car.accept(new CarElementPrintVisitor()); car.accept(new CarElementDoVisitor()); } } Output Visiting front left wheel Visiting front right wheel Visiting back left wheel Visiting back right wheel Visiting body Visiting engine Visiting car Kicking my front left wheel Kicking my front right wheel Kicking my back left wheel Kicking my back right wheel Moving my body Starting my engine Starting my car Common Lisp example Sources (defclass auto () ((elements :initarg :elements))) (defclass auto-part () ((name :initarg :name :initform ""))) (defmethod print-object ((p auto-part) stream) (print-object (slot-value p 'name) stream)) (defclass wheel (auto-part) ()) (defclass body (auto-part) ()) (defclass engine (auto-part) ()) (defgeneric traverse ( other-object)) (defmethod traverse (function (a auto) other-object) (with-slots (elements) a (dolist (e elements) (funcall function e other-object)))) ;; do-something visitations ;; catch all (defmethod do-something (object other-object) (format t "don't know how ~s and ~s should interact~%" object other-object)) ;; visitation involving wheel and integer (defmethod do-something ((object wheel) (other-object integer)) (format t "kicking wheel ~s ~s times~%" object other-object)) ;; visitation involving wheel and symbol (defmethod do-something ((object wheel) (other-object symbol)) (format t "kicking wheel ~s symbolically using symbol ~s~%" object other-object)) (defmethod do-something ((object engine) (other-object integer)) (format t "starting engine ~s ~s times~%" object other-object)) (defmethod do-something ((object engine) (other-object symbol)) (format t "starting engine ~s symbolically using symbol ~s~%" object other-object)) (let ((a (make-instance 'auto :elements `(,(make-instance 'wheel :name "front-left-wheel") ,(make-instance 'wheel :name "front-right-wheel") ,(make-instance 'wheel :name "rear-left-wheel") ,(make-instance 'wheel :name "rear-right-wheel") ,(make-instance 'body :name "body") ,(make-instance 'engine :name "engine"))))) ;; traverse to print elements ;; stream *standard-output* plays the role of other-object here (traverse #'print a *standard-output*) (terpri) ;; print newline ;; traverse with arbitrary context from other object (traverse #'do-something a 42) ;; traverse with arbitrary context from other object (traverse #'do-something a 'abc))Output "front-left-wheel" "front-right-wheel" "rear-right-wheel" "rear-right-wheel" "body" "engine" kicking wheel "front-left-wheel" 42 times kicking wheel "front-right-wheel" 42 times kicking wheel "rear-right-wheel" 42 times kicking wheel "rear-right-wheel" 42 times don't know how "body" and 42 should interact starting engine "engine" 42 times kicking wheel "front-left-wheel" symbolically using symbol ABC kicking wheel "front-right-wheel" symbolically using symbol ABC kicking wheel "rear-right-wheel" symbolically using symbol ABC kicking wheel "rear-right-wheel" symbolically using symbol ABC don't know how "body" and ABC should interact starting engine "engine" symbolically using symbol ABCNotes The other-object parameter is superfluous in traverse. The reason is that it is possible to use an anonymous function that calls the desired target method with a lexically captured object: (defmethod traverse (function (a auto)) ;; other-object removed (with-slots (elements) a (dolist (e elements) (funcall function e)))) ;; from here too ;; ... ;; alternative way to print-traverse (traverse (lambda (o) (print o *standard-output*)) a) ;; alternative way to do-something with ;; elements of a and integer 42 (traverse (lambda (o) (do-something o 42)) a)Now, the multiple dispatch occurs in the call issued from the body of the anonymous function, and so traverse is just a mapping function that distributes a function application over the elements of an object. Thus all traces of the Visitor Pattern disappear, except for the mapping function, in which there is no evidence of two objects being involved. All knowledge of there being two objects and a dispatch on their types is in the lambda function. Python example Python does not support method overloading in classical sense (polymorphic behavior according to type of passed parameters), so the "visit" methods for the different model types need to have different names. Sources """ Visitor pattern example. """ from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." class CarElement: __metaclass__ = ABCMeta Visitor pattern 151

@abstractmethod def accept(self, visitor): raise NotImplementedError(NOT_IMPLEMENTED) class Body(CarElement): def accept(self, visitor): visitor.visitBody(self) class Engine(CarElement): def accept(self, visitor): visitor.visitEngine(self) class Wheel(CarElement): def __init__(self, name): self.name = name def accept(self, visitor): visitor.visitWheel(self) class Car(CarElement): def __init__(self): self.elements = [ Wheel("front left"), Wheel("front right"), Wheel("back left"), Wheel("back right"), Body(), Engine() ] def accept(self, visitor): for element in self.elements: element.accept(visitor) visitor.visitCar(self) class CarElementVisitor: __metaclass__ = ABCMeta @abstractmethod def visitBody(self, element): raise NotImplementedError(NOT_IMPLEMENTED) @abstractmethod def visitEngine(self, element): raise NotImplementedError(NOT_IMPLEMENTED) @abstractmethod def visitWheel(self, element): raise NotImplementedError(NOT_IMPLEMENTED) @abstractmethod def visitCar(self, element): raise NotImplementedError(NOT_IMPLEMENTED) class CarElementDoVisitor(CarElementVisitor): def visitBody(self, body): print("Moving my body.") def visitCar(self, car): print("Starting my car.") def visitWheel(self, wheel): print("Kicking my {} wheel.".format(wheel.name)) def visitEngine(self, engine): print("Starting my engine.") class CarElementPrintVisitor(CarElementVisitor): def visitBody(self, body): print("Visiting body.") def visitCar(self, car): print("Visiting car.") def visitWheel(self, wheel): print("Visiting {} wheel.".format(wheel.name)) def visitEngine(self, engine): print("Visiting engine.") car = Car() car.accept(CarElementPrintVisitor()) car.accept(CarElementDoVisitor()) Output Visiting front left wheel. Visiting front right wheel. Visiting back left wheel. Visiting back right wheel. Visiting body. Visiting engine. Visiting car. Kicking my front left wheel. Kicking my front right wheel. Kicking my back left wheel. Kicking my back right wheel. Moving my body. Starting my engine. Starting my car. Abstraction If one is using Python 3 or above, they can make a general implementation of the accept method: class Visitable: def accept(self, visitor): lookup = "visit_" + type(self).__qualname__.replace(".", "_") return getattr(visitor, lookup)(self) One could extend this to iterate over the class's method resolution order if they would like to fall back on already-implemented classes. They could also use the subclass hook feature to define the lookup in advance. Related design patterns Iterator pattern – defines a traversal principle like the visitor pattern, without making a type differentiation within the traversed objects Church encoding – a related concept from functional programming, in which tagged uniontagged union/sum types may be modeled using the behaviors of "visitors" on such types, and which enables the visitor pattern to emulate variants and pattern matchingpatterns. References External links class=noviewerWikimedia Commons has media related to Visitor pattern.class=noviewerThe Wikibook Computer Science Design Patterns has a page on the topic of: Visitor implementations in various languages The Visitor Family of Design Patterns at the Wayback Machine (archived October 22, 2015). Additional archives: April 12, 2004, March 5, 2002. A rough chapter from The Principles, Patterns, and Practices of Agile Software Development, Robert Cecil MartinRobert C. Martin, Prentice Hall Visitor pattern in UML and in LePUS3 (a Design Description Language) Article " Componentization: the Visitor Example by Bertrand Meyer and Karine Arnout, Computer (IEEE), vol. 39, no. 7, July 2006, pages 23-30. Article A Type-theoretic Reconstruction of the Visitor Pattern Article " The Essence of the Visitor Pattern" by Jens Palsberg and C. Barry Jay. 1997 IEEE Computer SocietyIEEE-CS Software engineeringCOMPSAC paper showing that accept() methods are unnecessary when reflection is available; introduces term 'Walkabout' for the technique. Article " A Time for Reflection" by Bruce Wallace – subtitled "Java 1.2's reflection capabilities eliminate burdensome accept() methods from your Visitor pattern" Visitor Patterns as a universal model of terminating computation. Visitor Pattern using reflection(java). PerfectJPattern Open Source Project, Provides a context-free and type-safe implementation of the Visitor Pattern in Java based on Delegates. Visitor Design Pattern SOLID 152 SOLID

SOLID Principles

• Single responsibility • Open–closed • Liskov substitution • Interface segregation • Dependency inversion

• v • t [1] • e

In object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. It is not related to the GRASP software design principles. The principles are a subset of many principles promoted by American software engineer and instructor Robert C. Martin.[1][2] Though they apply to any object-oriented design, the SOLID principles can also form a core philosophy for methodologies such as agile development or adaptive software development. The theory of SOLID principles was introduced by Martin in his 2000 paper Design Principles and Design Patterns, although the SOLID acronym was introduced later by Michael Feathers.

Concepts Single-responsibility principle A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. Open–closed principle "Software entities ... should be open for extension, but closed for modification." Liskov substitution principle "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program." See also . Interface segregation principle "Many client-specific interfaces are better than one general-purpose interface." Dependency inversion principle One should "depend upon abstractions, [not] concretions."

References [1] . (Note the reference to “the first five principles”, though the acronym is not used in this article.) Dates back to at least 2003. [2] Talk given at the 2009 Gotham Ruby Conference. Single responsibility principle 153 Single responsibility principle

SOLID Principles

• Single responsibility • Open–closed • Liskov substitution • Interface segregation • Dependency inversion

• v • t [1] • e

The single-responsibility principle (SRP) is a computer-programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class, module or function. All its services should be narrowly aligned with that responsibility. Robert C. Martin expresses the principle as, "A class should have only one reason to change," although, because of confusion around the word "reason" he more recently stated "This principle is about people."

History The term was introduced by Robert C. Martin in an article by the same name as part of his Principles of Object Oriented Design, made popular by his book Agile Software Development, Principles, Patterns, and Practices. Martin described it as being based on the principle of cohesion, as described by Tom DeMarco in his book Structured Analysis and System Specification, and Meilir Page-Jones in The Practical Guide to Structured Systems Design. In 2014 Martin wrote a blog post entitled The Single Responsibility Principle [1] with a goal to clarify what was meant by the phrase "reason for change."

Example Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to be changed (e.g. rewritten). As an example, consider a module that compiles and prints a report. Imagine such a module can be changed for two reasons. First, the content of the report could change. Second, the format of the report could change. These two things change for very different causes; one substantive, and one cosmetic. The single-responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should, therefore, be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times. The reason it is important to keep a class focused on a single concern is that it makes the class more robust. Continuing with the foregoing example, if there is a change to the report compilation process, there is a greater danger that the printing code will break if it is part of the same class. Single responsibility principle 154

References

External links

• The Secret behind the Single Responsibility Principle (https:/ / medium. com/ @wrong. about/ the-secret-behind-the-single-responsibility-principle-e2f3692bae25)

• The Single Responsibility Principle (https:/ / code. tutsplus. com/ tutorials/ solid-part-1-the-single-responsibility-principle--net-36074)

Open-closed principle

SOLID Principles

• Single responsibility • Open–closed • Liskov substitution • Interface segregation • Dependency inversion

• v • t [1] • e

In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code. The name open–closed principle has been used in two ways. Both ways use generalizations (for instance, inheritance or delegate functions) to resolve the apparent dilemma, but the goals, techniques, and results are different. Open–closed principle is one of the five SOLID principles of object-oriented design.

Meyer's open–closed principle Bertrand Meyer is generally credited for having originated the term open–closed principle,[1] which appeared in his 1988 book Object Oriented Software Construction. • A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs. • A module will be said to be closed if [it] is available for use by other modules. This assumes that the module has been given a well-defined, stable description (the interface in the sense of information hiding). At the time Meyer was writing, adding fields or functions to a library inevitably required changes to any programs depending on that library.Wikipedia:Citation needed Meyer's proposed solution to this dilemma relied on the notion of object-oriented inheritance (specifically implementation inheritance): A class is closed, since it may be compiled, stored in a library, baselined, and used by client classes. But it is also open, since any new class may use it as parent, adding new features. When a descendant class is defined, there is no need to change the original or to disturb its clients. Open-closed principle 155

Polymorphic open–closed principle During the 1990s, the open–closed principle became popularly redefined to refer to the use of abstracted interfaces, where the implementations can be changed and multiple implementations could be created and polymorphically substituted for each other. In contrast to Meyer's usage, this definition advocates inheritance from abstract base classes. Interface specifications can be reused through inheritance but implementation need not be. The existing interface is closed to modifications and new implementations must, at a minimum, implement that interface. Robert C. Martin's 1996 article "The Open-Closed Principle" was one of the seminal writings to take this approach. In 2001 related the open–closed principle to the pattern by Alistair Cockburn called Protected Variations, and to the David Parnas discussion of information hiding.[2]

References

[1] Robert C. Martin "The Open-Closed Principle", C++ Report, January 1996 (http:/ / docs. google. com/ a/ cleancoder. com/ viewer?a=v&

pid=explorer& chrome=true& srcid=0BwhCYaYDn8EgN2M5MTkwM2EtNWFkZC00ZTI3LWFjZTUtNTFhZGZiYmUzODc1& hl=en)

[2] Craig Larman, "Protected Variation: The Importance of Being Closed", IEEE Software May/June 2001, pp. 89-91 (http:/ / codecourse.

sourceforge. net/ materials/ The-Importance-of-Being-Closed. pdf)

External links

• The Principles of OOD (http:/ / butunclebob. com/ ArticleS. UncleBob. PrinciplesOfOod)

• The Open/Closed Principle: Concerns about Change in Software Design (https:/ / web. archive. org/ web/

20181204101941/ http:/ / blog. symprise. net/ 2009/ 06/ 23/

open-closed-principle-concerns-about-change-in-software-design/ )

• The Open Closed Principle (https:/ / 8thlight. com/ blog/ uncle-bob/ 2014/ 05/ 12/ TheOpenClosedPrinciple. html)

• The Open-Closed Principle -- and What Hides Behind It (https:/ / medium. com/ @wrong. about/ the-open-closed-principle-c3dc45419784) Liskov substitution principle 156 Liskov substitution principle

SOLID Principles

• Single responsibility • Open–closed • Liskov substitution • Interface segregation • Dependency inversion

• v • t [1] • e

Substitutability is a principle in object-oriented programming stating that, in a , if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.). More formally, the Liskov substitution principle (LSP) is a particular definition of a relation, called (strong) behavioral subtyping, that was initially introduced by in a 1987 conference keynote address titled Data abstraction and hierarchy. It is a semantic rather than merely syntactic relation, because it intends to guarantee semantic interoperability of types in a hierarchy, object types in particular. Barbara Liskov and Jeannette Wing described the principle succinctly in a 1994 paper as follows: Subtype Requirement: Let be a property provable about objects of type T. Then should be true for objects of type S where S is a subtype of T. In the same paper, Liskov and Wing detailed their notion of behavioral subtyping in an extension of Hoare logic, which bears a certain resemblance to Bertrand Meyer's design by contract in that it considers the interaction of subtyping with preconditions, postconditions and invariants.

Principle Liskov's notion of a behavioural subtype defines a notion of substitutability for objects; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program (e.g. correctness). Behavioural subtyping is a stronger notion than typical subtyping of functions defined in type theory, which relies only on the contravariance of argument types and covariance of the return type. Behavioural subtyping is undecidable in general: if q is the property "method for x always terminates", then it is impossible for a program (e.g. a compiler) to verify that it holds true for some subtype S of T, even if q does hold for T. Nonetheless, the principle is useful in reasoning about the design of class hierarchies. Liskov's principle imposes some standard requirements on signatures that have been adopted in newer object-oriented programming languages (usually at the level of classes rather than types; see nominal vs. structural subtyping for the distinction): • Contravariance of method arguments in the subtype. • Covariance of return types in the subtype. • No new exceptions should be thrown by methods of the subtype, except where those exceptions are themselves subtypes of exceptions thrown by the methods of the supertype. In addition to the signature requirements, the subtype must meet a number of behavioural conditions. These are detailed in a terminology resembling that of design by contract methodology, leading to some restrictions on how Liskov substitution principle 157

contracts can interact with inheritance: • Preconditions cannot be strengthened in a subtype. • Postconditions cannot be weakened in a subtype. • Invariants of the supertype must be preserved in a subtype. • History constraint (the "history rule"). Objects are regarded as being modifiable only through their methods (encapsulation). Because subtypes may introduce methods that are not present in the supertype, the introduction of these methods may allow state changes in the subtype that are not permissible in the supertype. The history constraint prohibits this. It was the novel element introduced by Liskov and Wing. A violation of this constraint can be exemplified by defining a mutable point as a subtype of an immutable point. This is a violation of the history constraint, because in the history of the immutable point, the state is always the same after creation, so it cannot include the history of a mutable point in general. Fields added to the subtype may however be safely modified because they are not observable through the supertype methods. Thus, one can derive a circle with fixed center but mutable radius from immutable point without violating LSP.

Origins The rules on pre- and postconditions are identical to those introduced by Bertrand Meyer in his 1988 book Object-Oriented Software Construction. Both Meyer, and later Pierre America, who was the first to use the term behavioral subtyping, gave proof-theoretic definitions of some behavioral subtyping notions, but their definitions did not take into account aliasing that may occur in programming languages that support references or pointers. Taking aliasing into account was the major improvement made by Liskov and Wing (1994), and a key ingredient is the history constraint. Under the definitions of Meyer and America, a MutablePoint would be a behavioral subtype of ImmutablePoint, whereas LSP forbids this.

Criticism While widely used, the characterization of behavioral subtyping as the ability to substitute subtype objects for supertype objects is flawed. It makes no mention of specifications, so it invites an incorrect reading where the implementation of the supertype is compared to the implementation of the subtype. This is problematic for several reasons, one being that it does not support the common case where the supertype is abstract and has no implementation. Also, more subtly, in the context of object-oriented imperative programming it is difficult to define precisely what it means to universally or existentially quantify over objects of a given type, or to substitute one object for another. When applying subtyping, generally we are not substituting subtype objects for supertype objects, we are simply using subtype objects as supertype objects. That is, it is the same objects, the subtype objects, that are also supertype objects. In an interview in 2016, Liskov herself explains that what she presented in her keynote address was an "informal rule", that Jeannette Wing later proposed that they "try to figure out precisely what this means", which led to their joint publication on behavioral subtyping, and indeed that "technically, it's called behavioral subtyping". During the interview, she does not use substitution terminology to discuss the concepts. Liskov substitution principle 158

References

Bibliography General references • Gary T. Leavens and Krishna K. Dhara, Concepts of Behavioral Subtyping and a Sketch of Their Extension to Component-Bases Systems in Gary T. Leavens, Murali Sitaraman, (ed.) Foundations of component-based systems, Cambridge University Press, 2000 ISBN 0-521-77164-1. This paper surveys various notions of behavioral subtyping, including Liskov and Wing's. • Liskov, B. H.; Wing, J. M. (November 1994). A behavioral notion of subtyping. ACM Trans. Program. Lang.

Syst. 16 (6). pp. 1811–1841. doi: 10.1145/197320.197383 (http:/ / doi. org/ 10. 1145/ 197320. 197383). An updated version appeared as CMU technical report: Liskov, Barbara; Wing, Jeannette (July 1999). "Behavioral Subtyping Using Invariants

and Constraints" (http:/ / reports-archive. adm. cs. cmu. edu/ anon/ 1999/ CMU-CS-99-156. ps) (PS). Retrieved 2006-10-05. The formalization of the principle by its authors. • Reinhold Plösch, Contracts, scenarios and prototypes: an integrated approach to high quality software, Springer, 2004, ISBN 3-540-43486-0. Contains a gentler introduction to behavioral subtyping in its various forms in chapter 2.

• Robert C. Martin, The Liskov Substitution Principle (https:/ / web. archive. org/ web/ 20151128004108/ http:/ /

www. objectmentor. com/ resources/ articles/ lsp. pdf), C++ Report, March 1996. An article popular in the object-oriented programming community that gives several examples of LSP violations. • Kazimir Majorinc, Ellipse-Circle Dilemma and Inverse Inheritance, ITI 98, Proceedings of the 20th International Conference of Information Technology Interfaces, Pula, 1998, ISSN 1330-1012. This paper discusses LSP in the mentioned context. Specific references • Liskov, B. (May 1988). "Keynote address - data abstraction and hierarchy". ACM SIGPLAN Notices. 23 (5):

17–34. doi: 10.1145/62139.62141 (http:/ / doi. org/ 10. 1145/ 62139. 62141). A keynote address in which Liskov first formulated the principle. • Meyer B., Object-oriented Software Construction, Prentice Hall, New York, 1988, ISBN 0-13-629031-0

External links

• The Liskov Substitution Principle (http:/ / www. engr. mun. ca/ ~theo/ Courses/ sd/ 5895-downloads/

sd-principles-3. ppt. pdf), T. S. Norvell, 2003.

• Liskov Substitution Principle Explained (https:/ / medium. com/ @wrong. about/ liskov-substitution-principle-a982551d584a)

• SOLID Class Design: The Liskov Substitution Principle (https:/ / www. tomdalling. com/ blog/ software-design/

solid-class-design-the-liskov-substitution-principle/ ) Interface segregation principle 159 Interface segregation principle

SOLID Principles

• Single responsibility • Open–closed • Liskov substitution • Interface segregation • Dependency inversion

• v • t [1] • e

In the field of software engineering, the interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.[1] ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called role interfaces.[2] ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy. ISP is one of the five SOLID principles of object-oriented design, similar to the High Cohesion Principle of GRASP.

Importance in object-oriented design Within object-oriented design, interfaces provide layers of abstraction that simplify code and create a barrier preventing coupling to dependencies. According to many software experts who have signed the Manifesto for Software Craftsmanship, writing well-crafted and self-explanatory software is almost as important as writing working software.[3] Using interfaces to further describe the intent of the software is often a good idea. A system may become so coupled at multiple levels that it is no longer possible to make a change in one place without necessitating many additional changes. Using an interface or an abstract class can prevent this side effect.

Origin The ISP was first used and formulated by Robert C. Martin while consulting for Xerox. Xerox had created a new printer system that could perform a variety of tasks such as stapling and faxing. The software for this system was created from the ground up. As the software grew, making modifications became more and more difficult so that even the smallest change would take a redeployment cycle of an hour, which made development nearly impossible. The design problem was that a single Job class was used by almost all of the tasks. Whenever a print job or a stapling job needed to be performed, a call was made to the Job class. This resulted in a 'fat' class with multitudes of methods specific to a variety of different clients. Because of this design, a staple job would know about all the methods of the print job, even though there was no use for them. The solution suggested by Martin utilized what is today called the Interface Segregation Principle. Applied to the Xerox software, an interface layer between the Job class and its clients was added using the Dependency Inversion Principle. Instead of having one large Job class, a Staple Job interface or a Print Job interface was created that would be used by the Staple or Print classes, respectively, calling methods of the Job class. Therefore, one interface was created for each job type, which was all implemented by the Job class. Interface segregation principle 160

Typical violation A typical violation of the Interface Segregation Principle is given in Agile Software Development: Principles, Patterns, and Practices in 'ATM Transaction example' and in an article also written by Robert C. Martin specifically about the ISP.[4] This example discusses the User Interface for an ATM, which handles all requests such as a deposit request, or a withdrawal request, and how this interface needs to be segregated into individual and more specific interfaces.

References [1] Martin, Robert (2002). Agile Software Development: Principles, Patterns, and Practices. Pearson Education.

[2] Role Interface (http:/ / martinfowler. com/ bliki/ RoleInterface. html)

[3] Manifesto of Software Craftsmanship (http:/ / manifesto. softwarecraftsmanship. org)

[4] Robert C. Martin,The Interface Segregation Principle, C++ Report, June 1996 (https:/ / docs. google. com/ a/ cleancoder. com/ viewer?a=v&

pid=explorer& chrome=true& srcid=0BwhCYaYDn8EgOTViYjJhYzMtMzYxMC00MzFjLWJjMzYtOGJiMDc5N2JkYmJi& hl=en)

External links

• Principles Of OOD (http:/ / butunclebob. com/ ArticleS. UncleBob. PrinciplesOfOod) – Description and links to detailed articles on SOLID.

Dependency inversion principle

WARNING: Article could not be rendered - ouputting plain text. Potential causes of the problem are: (a) a bug in the pdf-writer software (b) problematic Mediawiki markup (c) table is too wide

SOLID PrinciplesSingle-responsibility principleSingle responsibilityOpen–closed principleOpen–closedLiskov substitution principleLiskov substitutionInterface segregation principleInterface segregationDependency inversion principleDependency inversionvte In object-oriented design, the dependency inversion principle is a specific form of Coupling (computer programming)decoupling software Modular programmingmodules. When following this principle, the conventional dependency (computer science)dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces).Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.By dictating that both high-level and low-level objects must depend on the same abstraction, this design principle inverts the way some people may think about object-oriented programming.The idea behind points A and B of this principle is that when designing the interaction between a high-level module and a low-level one, the interaction should be thought of as an abstract interaction between them. This not only has implications on the design of the high-level module, but also on the low-level one: the low-level one should be designed with the interaction in mind and it may be necessary to change its usage interface. In many cases, thinking about the interaction in itself as an abstract concept allows the coupling of the components to be reduced without introducing additional coding patterns, allowing only a lighter and less implementation-dependent interaction schema. When the discovered abstract interaction schema(s) between two modules is/are generic and generalization makes sense, this design principle also leads to the following dependency Dependency inversion principle 161

inversion coding pattern. Traditional layers pattern In conventional application architecture, lower-level components (e.g. Utility Layer) are designed to be consumed by higher-level components (e.g. Policy Layer) which enable increasingly complex systems to be built. In this composition, higher-level components depend directly upon lower-level components to achieve some task. This dependency upon lower-level components limits the reuse opportunities of the higher-level components.The goal of the dependency inversion pattern is to avoid this highly coupled distribution with the mediation of an abstract layer, and to increase the re-usability of higher/policy layers. Dependency inversion pattern With the addition of an abstract layer, both high- and lower-level layers reduce the traditional dependencies from top to bottom. Nevertheless, the "inversion" concept does not mean that lower-level layers depend on higher-level layers. Both layers should depend on abstractions that draw the behavior needed by higher-level layers. In a direct application of dependency inversion, the abstracts are owned by the upper/policy layers. This architecture groups the higher/policy components and the abstractions that define lower services together in the same package. The lower-level layers are created by inheritance/implementation of these abstract classes or interfaces.The inversion of the dependencies and ownership encourages the re-usability of the higher/policy layers. Upper layers could use other implementations of the lower services. When the lower-level layer components are closed or when the application requires the reuse of existing services, it is common that an adapter patternAdapter mediates between the services and the abstractions. Dependency inversion pattern generalization In many projects the dependency inversion principle and pattern are considered as a single concept that should be generalized, i.e., applied to all interfaces between software modules. There are at least two reasons for that: It is simpler to see a good thinking principle as a coding pattern. Once an abstract class or an interface has been coded, the programmer may say: "I have done the job of abstraction". Because many unit testing tools rely on inheritance to accomplish mock objectmocking, the usage of generic interfaces between classes (not only between modules when it makes sense to use generality) became the rule. If the mocking tool used relies only on inheritance, it may become necessary to widely apply the dependency inversion pattern. This has major drawbacks: Merely implementing an interface over a class isn't sufficient to reduce coupling; only thinking about the potential abstraction of interactions can lead to a less coupled design. Implementing generic interfaces everywhere in a project makes it harder to understand and maintain. At each step the reader will ask themself what are the other implementations of this interface and the response is generally: only mocks. The interface generalization requires more plumbing code, in particular factories that generally rely on a dependency-injection framework. Interface generalization also restricts the usage of the programming language. Generalization restrictions The presence of interfaces to accomplish the Dependency Inversion Pattern (DIP) has other design implications in an object-oriented programmingobject-oriented program: All member variables in a class must be interfaces or abstracts. All concrete class packages must connect only through interface or abstract class packages. No class should derive from a concrete class. No method should override an implemented method. All variable instantiation requires the implementation of a creational pattern such as the Factory method patternfactory method or the Factory (object-oriented programming)factory pattern, or the use of a dependency injectiondependency-injection framework. Interface mocking restrictions Using inheritance-based mocking tools also introduces restrictions: Static externally visible members should systematically rely on dependency injection making them far harder to implement. All testable methods should become an interface implementation or an override of an abstract definition. Future directions Principles are ways of thinking. Patterns are common ways to solve problems. Coding patterns may be missing programming language features. Programming languages will continue to evolve to allow them to enforce stronger and more precise usage contracts in at least two directions: enforcing usage conditions (pre-, post- and invariant conditions) and state-based interfaces. This will probably encourage and potentially simplify a stronger application of the dependency inversion pattern in many situations. More and more mocking tools now use dependency injectiondependency-injection to solve the problem of replacing static and non virtual members. Programming languages will probably evolve to generate mocking-compatible bytecode. One direction will be to restrict the usage of non-virtual members. The other one will be to generate, at least in test situations, bytecode allowing non-inheritance based mocking. Implementations Two common implementations of DIP use similar logical architecture but with different implications. A direct Dependency inversion principle 162

implementation packages the policy classes with service abstracts classes in one library. In this implementation high-level components and low-level components are distributed into separate packages/libraries, where the Interface (computer science)interfaces defining the behavior/services required by the high-level component are owned by, and exist within the high-level component's library. The implementation of the high-level component's interface by the low-level component requires that the low-level component package depend upon the high-level component for compilation, thus inverting the conventional dependency relationship. Figures 1 and 2 illustrate code with the same functionality, however in Figure 2, an interface has been used to invert the dependency. The direction of dependency can be chosen to maximize policy code reuse, and eliminate cyclic dependencies. In this version of DIP, the lower layer component's dependency on the interfaces/abstracts in the higher-level layers makes re-utilization of the lower layer components difficult. This implementation instead ″inverts″ the traditional dependency from top-to-bottom to the opposite, from bottom-to-top. A more flexible solution extracts the abstract components into an independent set of packages/libraries: The separation of each layer into its own package encourages re-utilization of any layer, providing robustness and mobility.ExamplesGenealogical module A genealogical system may represent relationships between people as a graph of direct relationships between them (father-son, father-daughter, mother-son, mother-daughter, husband-wife, wife-husband, etc.). This is very efficient and extensible, as it is easy to add an ex-husband or a legal guardian. But some higher-level modules may require a simpler way to browse the system: any person may have children, parents, siblings (including half-brothers and -sisters or not), grandparents, cousins, and so on. Depending on the usage of the genealogical module, presenting common relationships as distinct direct properties (hiding the graph) will make the coupling between a higher-level module and the genealogical module much lighter and allow one to change the internal representation of the direct relationships completely without any effect on the modules using them. It also permits embedding exact definitions of siblings or uncles in the genealogical module, thus enforcing the single responsibility principle. Finally, if the first extensible generalized graph approach seems the most extensible, the usage of the genealogical module may show that a more specialized and simpler relationship implementation is sufficient for the application(s) and helps create a more efficient system. In this example, abstracting the interaction between the modules leads to a simplified interface of the lower-level module and may lead to a simpler implementation of it. Remote file server client Imagine you have to implement a client to a remote file server (FTP, cloud storage ...). You may think of it as a set of abstract interfaces: Connection/Disconnection (a connection persistence layer may be needed) Folder/tags creation/rename/delete/list interface File creation/replacement/rename/delete/read interface File searching Concurrent replacement or delete resolution File history management ... If both local files and remote files offers the same abstract interfaces, any high-level module using local files and fully implementing the dependency inversion pattern will be able to access local and remote files indiscriminately. Local disk will generally use folder, remote storage may use folder and/or tags. You have to decide how to unify them if possible. On remote file we may have to use only create or replace: remote files update do not necessarily make sense because random update is too slow comparing local file random update and may be very complicated to implement). On remote file we may need partial read and write (at least inside the remote file module to allow download or upload to resume after a communication interruption), but random read isn't adapted (except if a local cache is used). File searching may be pluggable : file searching can rely on the OS or in particular for tag or full text search, be implemented with distinct systems (OS embedded, or available separately). Concurrent replacement or delete resolution detection may impact the other abstract interfaces. When designing the remote file server client for each conceptual interface you have to ask yourself the level of service your high level modules require (not necessary all of them) and not only how to implement the remote file server functionalities but maybe how to make the file services in your application compatible between already implemented file services (local files, existing cloud clients) and your new remote file server client. Once you have designed the abstract interfaces required, your remote file server client should implement these interfaces. And because you probably restricted some local functionalities existing on local file (for example file update), you may have to write Adapter patternadapters for local or other existing used remote file access modules each offering the same abstract interfaces. You also have to write your own file access enumerator allowing to retrieve all file Dependency inversion principle 163

compatible systems available and configured on your computer. Once you do that, your application will be able to save its documents locally or remotely transparently. Or simpler, the high level module using the new file access interfaces can be used indistinctly in local or remote file access scenarios making it reusable. Remark: many OSes have started to implement these kind of functionalities and your work may be limited to adapt your new client to this already abstracted models. In this example, thinking of the module as a set of abstract interfaces, and adapting other modules to this set of interfaces, allows you to provide a common interface for many file storage systems. Model View ControllerExample of DIPUI and ApplicationLayer packages contains mainly concrete classes. Controllers contains abstracts/interface types. UI has an instance of ICustomerHandler. All packages are physically separated. In the ApplicationLayer there is a concrete implementation that Page class will use. Instances of this interface are created dynamically by a Factory (possibly in the same Controllers package). The concrete types, Page and CustomerHandler, don't depend on each other; both depend on ICustomerHandler. The direct effect is that the UI doesn't need to reference the ApplicationLayer or any concrete package that implements the ICustomerHandler. The concrete class will be loaded using reflection. At any moment the concrete implementation could be replaced by another concrete implementation without changing the UI class. Another interesting possibility is that the Page class implements an interface IPageViewer that could be passed as an argument to ICustomerHandler methods. Then the concrete implementation could communicate with UI without a concrete dependency. Again, both are linked by interfaces. Related patterns Applying the dependency inversion principle can also be seen as an example of the adapter pattern, i.e. the high-level class defines its own adapter interface which is the abstraction that the other high-level classes depend on. The adaptee implementation also depends on the adapter interface abstraction (of course, since it implements its interface) while it can be implemented by using code from within its own low-level module. The high-level has no dependency on the low-level module since it only uses the low-level indirectly through the adapter interface by invoking polymorphic methods to the interface which are implemented by the adaptee and its low-level module. Various patterns such as Plugin, Service locator patternService Locator, or Dependency injection are employed to facilitate the run-time provisioning of the chosen low-level component implementation to the high-level component. History The dependency inversion principle was postulated by Robert C. Martin and described in several publications including the paper Object Oriented Design Quality Metrics: an analysis of dependencies, an article appearing in the C++ Report in May 1996 entitled The Dependency Inversion Principle, and the books Agile Software Development, Principles, Patterns, and Practices, and Agile Principles, Patterns, and Practices in C#.ReferencesExternal links Object Oriented Design Quality Metrics: an analysis of dependencies Robert C. Martin, C++ Report, Sept/Oct 1995 The Dependency Inversion Principle, Robert C. Martin, C++ Report, May 1996 Examining the Dependency Inversion Principle, Derek Greer DIP in the Wild, Brett L. Schuchert, May 2013 IoC Container for Unity3D – part 2 Article Sources and Contributors 164 Article Sources and Contributors

Software design pattern Source: http://en.wikipedia.org/w/index.php?title=Software_design_pattern Contributors: 1Wiki8Q5G7FviTHBac3dx8HhdNYwDVstR, A3nm, Ahiijny, Airplaneman, Aksgkulkarni, Alexf, Alexmadon, Amitdipsite, Andy Dingley, BBL5660, BD2412, Basamajoe, Beland, Billinghurst, Biogeographist, Bogdanmionescu, Bollyjeff, BozzieBear, Bradarv90, BurritoBazooka, Cannolis, CaptainPinko, Chealer, ClueBot NG, Cmartin.scruthut, Cybercobra, Dawid Ireno, Dcirovic, Declanmcd, Demonkoryu, Der Hakawati, Devintseo, Docsman, Dorintosh, Egg, Emiya~ruwiki, Excirial, Fabianophp, Favonian, Ferdinand Pienaar, Flyer22 Frozen, Fragglet, Frietjes, Fubar Obfusco, GhostInTheMachine, Gilo1969, Greenrd, Halfdan, Hammersoft, Hayman30, Hipal, Hu12, I dream of horses, Ibjacked, Int80, Irene31, Izno, J00tel, JHP, Jarble, Jim1138, JohnCD, Jonesey95, Jsg68x, Karandotg, Kinglag, Kku, Koavf, Kpgjhpjm, Kvng, LibreNico, Lost on Belmont, Lucca Mito, Lylez, M4gnum0n, Maggyero, Magioladitis, Marek69, Mark Renier, Martnym, Mblumber, McSly, Mean as custard, Michael Hardy, Mindmatrix, Mirokado, Mohsin gujjar, MrOllie, Nbarth, Ninly, Northamerica1000, NunoAgostinho, Omkarsoft, Opticyclic, Phamnhatkhanh, Phil Boswell, Philip Trueman, Pintoch, Plokmijnuhby, Pnm, Pomoxis, Pratyya Ghosh, Primefac, Prs.mrc, Ptrb, QuiteUnusual, Ramram 43210, Rcsprinter123, Redneckua, Renesis, Rponamgi, Rudyment, RyanNerd, SS1901, Sae1962, Satellizer, Serv49, Sharad1.yadav, Shevonsilva, Slivicon, Snarpel, Sonicsuns, Star767, SteveLoughran, Stevemidgley, Stokito, Stryn, SudhakarNimmala, Sudhanshuss, Svoboman, Sxilderik, Tassedethe, Tea2min, Thornbirda, TonyFlury, Triskell, Umbr, Umlcat, Vanderjoe, Vignezds, Widr, Wikipedia acc0, William Di Luigi, Wonderfl, Xtian~enwiki, Ynhockey, ZeroOne, 209 anonymous edits

Abstract factory pattern Source: http://en.wikipedia.org/w/index.php?title=Abstract_factory_pattern Contributors: AJCham, Anthony Appleyard, AutisticCatnip, Balkrishnatalele, Beland, BenFrantzDale, Bigscoop, Blair.butterworth, BluesLf, Bthachdev, Cedar101, Chekhovych1995, ClueBot NG, Cybercobra, Dan Gluck, Daniel.Cardenas, David.nussio, Demonkoryu, Druckles, Dudu90, Eastlaw, Edbecnel, Edenphd, Ekamaloff~enwiki, Enric Naval, Epbr123, Firetinder, Fluffernutter, Frór, Ftiercel, Fylbecatulous, GKFX, Gilliam, GoingBatty, GregKalapos, GregorB, Gurjinder.rathore, Hipal, Hu12, Ibrahim Rasel, Imdonatello, InverseHypercube, Jaecheol.shin, Java architect, Jay.233, Jdcollins13, Jonathan Hall, Joriki, Kallikanzarid, Klemen Kocjancic, Lepsyleon, Linuraj, Lukasz.gosik, Lunavorax, MER-C, Magioladitis, Mahanga, Manop, Materialscientist, Matinict, Matt.forestpath, Mecanismo, Mfilatov, Michael Slone, Miladrahimi93, Minimac, MrOllie, Msjegan, Msthil, Mtasic, Mumeriqbal786, MusikAnimal, Napstr4u, Niceguyedc, Nicktmro, Nitinpai2000, Nkocharh, Oddity-, Pelister, Phil Boswell, Phresnel, Piano non troppo, Pikiwyn, Pilode, Pointillist, QuackGuru, R'n'B, RainbowOfLight, Reyjose, Rican7, Rnapier, Ronabop, Rory O'Kane, Rtushar, Rupendradhillon, Sadegh 1990 hosseini, Sae1962, Saltine, Scray, Sdillman, SergejDergatsjev, Shadowjams, Shakethehill, Skittleys, Slaykovsky, Smithrondive, Stephenb, Strike Eagle, Strohtaler, Sun Creator, TAnthony, Tabletop, Tea2min, The Anome, Tobiasly, Trappist the monk, Twsx, Vanderjoe, Venturor, Vikasgoyal77, Vinhphunguyen, Vinod.pahuja, Wikieditor06, Wikiluwatar, Winstonne, Woohookitty, Xqt, Yonghuster, YurfDog, Zymut, 248 anonymous edits

Builder pattern Source: http://en.wikipedia.org/w/index.php?title=Builder_pattern Contributors: A Gutierrez-Pulido, Abba-best, Actinium15, Aesopos, Ahmed Jolani, Alex Georgousis, Alex.Cham, AlphaFoobar, Alshamiri1, Amniarix, Aneeshpu, Anthony Appleyard, Bangbang.S, Beetny, Beland, BenFrantzDale, Bináris, Bobthebuilder710, Booler80, Bthachdev, Bubbablaster, Capt. James T. Kirk, Cedar101, CiaPan, ClueBot NG, Coldboyqn, Controllersphere, Craig Pemberton, Cybercobra, Daniel.Cardenas, Dave.liepmann, Demonkoryu, Desprocon, Diannaa, Dkolegov, Dohzya, Donner60, Drmies, Dyker, Ecabiac, Emcmanus, Endlessoblivion, EvgeniiKhomutsky, Fragglet, François Robere, Frap, Ftiercel, Fuksito, Funroll loops, Gallas.aladdin, Ghuckabone, Hannibal.hero, HelgeHan, Herpesklaus, Hipal, Hu12, IAmAI, ImaginaryDevelopment, Inmyhand77, JForget, JMatthews, JavierMC, Jaxel21, Jeroen De Dauw, Jesus Escaped, Justacoder, Ketorin, KroOoOze, KroOoze, Lacypaperclip, Laoris, Leem02, Lukasz.gosik, Lylez, MER-C, MSRylander, Magioladitis, Marcocast, Marcusmax, Maxeto0910, Metalktulu, MrOllie, Msjegan, Mtasic, MuruAingaran, Naaram, Nafeezabrar, Nishanthan144, Nitinpai2000, Oddbodz, Phoe6, Pmussler, Pointillist, Ptbotgourou, Rh.vieira, Rimian, Rotgruenbart, Rponamgi, Sadads, Sae1962, Salazard1, Sanspeur, Sbhukar, Sedziwoj~enwiki, Shakethehill, Shell Kinney, Shellwood, Shyal-b, Slaykovsky, Sligocki, Ssimsekler, Strike Eagle, Sun Creator, Supersid01, T638403, TaukiTahmid, The Thing That Should Not Be, Tom.Reding, Toteb5, Uziel302, Vanderjoe, Vdevigere, Vinod.pahuja, Volwen, Wadetregaskis, Wikidicted, WinerFresh, Yintan, Оберон, 242 anonymous edits

Dependency injection Source: http://en.wikipedia.org/w/index.php?title=Dependency_injection Contributors: Akkystud, Amazomagisto, Ant 222, AristosM, Basil.bourque, Bender235, Buchskj, ByM4k5, Callyalater1989, Cedar101, Certes, Chharvey, Chris Mounce, ClueBot NG, Connor2307, DatGuy, Diego Moya, Donner60, Earcanal, Ethanpet113, Flyer22 Frozen, Galhalee, Gcaprio wp, GermanJoe, Gilliam, Giraffedata, GünniX, HaeB, HelgeHan, Hulmem, HumanDoctorZoidberg, Humbug26, Huttarl, Introw, Ira Leviton, JJMC89, Jarble, JasonR., Jim1138, Jitendrashewale, Jjcolosi, Jo-surikat, John Lunney, Juanmamb, Jwolfeld, KH-1, Khelvaster, Kreinba, KurryKid, Kvng, Laughmetal, Lphaf, Maghnus, Materialscientist, MaxEnt, Mmeijeri, Mortense, MrOllie, Pranav1431, Praxidicae, Probablytom, Qwertyus, Rahib110, Raut1920, Runawayangel, Sae1962, Sawankarn123, SebNag, Ser Amantio di Nicolao, ShakespeareFan00, Simetrical, Sjö, Software designer, Storebj0rn, Tea2min, ThomasO1989, Tom.Reding, TomCerul, UlrikRasmussen, Vakharia.rohan, Vanderjoe, Ver, Xonqnopp, 123 anonymous edits

Factory method pattern Source: http://en.wikipedia.org/w/index.php?title=Factory_method_pattern Contributors: 1typesetter, Acyclic, AlanUS, Alaskanloops, Alklazema, Allens, Alquantor, Anareth, Andy Dingley, Anurag870, Aprock, Arturs Licis, BenFrantzDale, Bender2k14, Binksternet, BlueTaRaKa, Brvman, Bubbleben, C5st4wr6ch, CWenger, ClueBot NG, Courcelles, Cplakidas, CubeSat4U, DanDanner, DavidLeighEllis, Demonkoryu, Dineshkumar Ponnusamy, Donner60, Dudu90, Dynamiclc, Ebrahim, Ed Poor, EdijsKolesnikovics, Edward.in.Edmonton, Emilhdiaz, Evilandi, Excirial, FBarber, Favonian, FellGleaming, Flyer22 Frozen, Fmadd, Fraggle81, Frap, FreeRangeFrog, Frietjes, Galestar, Gary, Gerold Broser, Guentherwagner, Hellacioussatyr, Hipal, InverseHypercube, JIP, JMatthews, Jakew, Jarble, Jcodetips, Jddahl, Jicksonp, Jorisvi, Joswig, Jowa fan, Juansempere, Julianjensen, Kstone999, Kurousagi, Leem02, Little3lue, Lucascullen, Magioladitis, MartinRinehart, Matinict, Mattbierner, Matthewhaworth, MauiBoyInMaltby, MichielDMN, MikeEagling, MrOllie, Myz2018, Nbarth, Ncmvocalist, Nielses, Nomad311, Nunopicado, Ocallesp, Ophunt, Oshwah, Pashute, Pergriffiths, Philip Trueman, Pointillist, Pup500, R'n'B, RA0808, Rajah9, RedWordSmith, RenamedUser01302013, Revolteh, Reyjose, Rforuupt, Rich Farmbrough, RobinHood70, Rolf the wolf, Sae1962, Samwilson, Sasuke Sarutobi, SebNag, Slaykovsky, Slhck, Soufiane2011, Ssimsekler, Sumone10154, Svick, Thadguidry, Thesquaregroot, Thumperward, Tide rolls, Tommy2010, Tormit, Trappist the monk, Vanderjoe, Whatchildisthis, Widr, Zch051383471952, Zero4573, Zvpunry, Оберон, 276 anonymous edits

Lazy initialization Source: http://en.wikipedia.org/w/index.php?title=Lazy_initialization Contributors: A3nm, Abednigo, Alexey Luchkovsky, Angilly, Anoop Manakkalath, Anthony Appleyard, Atropos235, Avisnacks, BD2412, Bcraun, Bilbo1507, Blankfrack, BluePlateSpecial, Brittannica, Bthachdev, Bubbleben, C++Bro123, Cedar101, ClueBot NG, Demonkoryu, Derek Ross, Dexp, Dotyoyo, Doug Bell, Ed Poor, EinBestimmterNutzer, Enochlau, Frap, Gustavo.mori, Gwern, JLaTondre, Jarble, Jerryobject, JonHarder, Loriendrew, Lumingz, MASQUERAID, Magioladitis, Manohar reddy123123, Mark.knol, Maximaximax, Michael Hardy, Michael9422, Msjegan, Mtasic, Muqsitrayyan, Phresnel, Psychogears, Quagmire, RedWolf, RepeatUntil, Rheun, Rhomboid, Robevans123, RobinHood70, Sae1962, Shah.harsh02, Spock lone wolf, Sun Creator, Sundar2000, Tackline, Tea2min, The9muse, TheIncredibleEdibleOompaLoompa, Tormit, TotalDepravity, Trappist the monk, Uzume, VKokielov, Vieque, YordanGeorgiev, Ztyx~enwiki, 97 anonymous edits

Multiton pattern Source: http://en.wikipedia.org/w/index.php?title=Multiton_pattern Contributors: .digamma, A876, Abednigo, Beland, Biosmarcel, BluePlateSpecial, Bmord, Cedar101, Chris the speller, CliffHall, CraigDWells, DanielcWiki, DavidHarkness, Demonkoryu, Destynova, Drealecs, Dubwai, Ettrig, Frap, Galestar, Gang65, Garageatrois, Gwern, Heavenlyhash, Inumedia, Janaagaard, Khalid hassani, Magioladitis, MrOllie, Mtasic, Nbarth, Pavel Vozenilek, Peak, Qwertyus, Ranjit.sail, Rentzepopoulos, Rich Farmbrough, Ros Original, Sae1962, Spoon!, Steve R Barnes, Viy75, Wavelength, Wookietreiber, 64 anonymous edits

Object pool pattern Source: http://en.wikipedia.org/w/index.php?title=Object_pool_pattern Contributors: Aaron Schulz, Abdull, Andreas Kaufmann, Anthony Appleyard, Arch4ngel, Arunkd13, Audriusa, CesarB, Christoofar, Dgpop, DoctorKubla, Frap, Hairy Dude, Hectorpal, Izkala, Jarble, Jestar jokin, Jkl, Juansempere, M4gnum0n, Magioladitis, Mahanga, Marudubshinki, Moala, Msjegan, Munificent, Nbarth, Noodlez84, Omnipaedista, PJTraill, Pearle, Prari, Purplefeltangel, Qxz, RobinHood70, Ruijoel, Sadegh 1990 hosseini, Sae1962, Saigyo, Softwayer, Svick, Swpb, Tenbaset, Terry Rod, Trappist the monk, Vinod.pahuja, Vip saran, Vorburger, WikHead, 64 anonymous edits

Prototype pattern Source: http://en.wikipedia.org/w/index.php?title=Prototype_pattern Contributors: Abednigo, Alessandro57, Andro164, Andy Dingley, Anthony Appleyard, Arglbr, Arturs Licis, Ary29, Ashley thomas80, AurelienLourot, BenFrantzDale, Bh5k, Blaise170, BluePlateSpecial, Brighterorange, Btx40, Can't sleep, clown will eat me, Carlif, Catch ru, Ceciop, Cheungpat, ClueBot NG, Cmdrjameson, Colonies Chris, Cygon, Demonkoryu, Der Hakawati, Doug Bell, Eaefremov, Enric Naval, Errandir, Frap, Frecklefoot, Ftiercel, Fyrael, Gfxiang, Ghettoblaster, Gotovikas, Gsp, Hao2lian, Hipal, Hofoen, Hu12, Igitur, Io41, Ira Leviton, J.delanoy, Jarble, Jcollo, Jengelh, Jianghan, Klbrain, Lathspell, Leirith, Leszek Jańczuk, Liao, Lookforajit, Loren.wilton, Lukasz.gosik, Luís Felipe Braga, M2Ys4U, MER-C, Magioladitis, Materialscientist, Maxeto0910, Megazoid9000, Michael Devore, Mital.vora, Modster, Mokru, Mormat, Msjegan, Mtasic, PJonDevelopment, Patrickdepinguin, Pmussler, Pointillist, Ptbotgourou, Ragesoss, RedWolf, RobinHood70, Rsrikanth05, Rubenkazumov, Sae1962, Salazard1, Samykausar, ScottyBerg, SergejDergatsjev, Stalker314314, TakuyaMurata, TheMandarin, TheParanoidOne, This lousy T-shirt, Trappist the monk, Vanderjoe, Vghuston, Victorwss~enwiki, Vikasgoyal77, VladM, Wadetregaskis, XcepticZP, Zarkonnen, Zerokitsune, Zonito, 199 anonymous edits

Resource Acquisition Is Initialization Source: http://en.wikipedia.org/w/index.php?title=Resource_Acquisition_Is_Initialization Contributors: ActiveMan, AgniKalpa, Alca Isilon~enwiki, Alexander Davronov, Alexey.kudinkin, Anphanax, Antonielly, Arto B, Artoria2e5, BenFrantzDale, Bender235, Bporopat, C++Bro123, CRGreathouse, Captain Conundrum, Clements, Clitte bbt, ClueBot NG, Curly Turkey, Cybercobra, Damian Yerrick, DavePeixotto, David C Oliver, DavidDecotigny, Decltype, Demonkoryu, Dhhtsy, DonBarredora, Dougher, Download, Echuck215, Encyclopedant, Enerjazzer, Eriol Ancalagon, EvanED, Evilninja, Ex0du5 5utu7e, Falcon8765, FatalError, Finerrecliner, Forderud, Frosty976, Furrykef, GB fan, GermanJoe, Giraffedata, Grghosal, Guenther Brunthaler, Hexware, Intgr, Izkala, Izno, Jarble, JeffyTheDragonSlayer, Jgrahn, Jjcolotti, Jwfearn, Karmastan, Kinu, Kku, Kreinba, Kri, Kvangend, Lim Wei Quan, Lkarayan, Maghnus, Magioladitis, Mark viking, Matonen, Mecanismo, Medinoc, Michael9422, Mirokado, Mortense, Mr Stephen, Nbarth, Nutate, Omnipaedista, Oysta, Phonetagger, Pibara, Pingveno, Ptrb, Quietbritishjim, Quilz, Qwertyus, RJFJR, Rbonvall, Regenspaziergang, RoySmith, Runtime, Sae1962, Sebastian.Dietrich, Shurakai, Siodhe, Smurfix, SoledadKabocha, SoylentPurple, Sperxios, Spoon!, Tea2min, The Anome, The Nameless, The deprecator, Thumperward, Tidigare upphovsman, Torc2, Trevor MacInnis, Tronic2, Ushkin N, Wikante, Wikidrone, Xerxesnine, 182 anonymous edits Article Sources and Contributors 165

Singleton pattern Source: http://en.wikipedia.org/w/index.php?title=Singleton_pattern Contributors: Abhi beckert, Alddar, Alex Hartforod, Alex.Cham, Alexius08, Andy Dingley, Ankit amadeus, Arvindraivns, Ashkansirous, Assafwo, Atethnekos, Atreys, B3t, BenFrantzDale, Bibhatripathi, Billinghurst, Bogdanmionescu, C5st4wr6ch, Caballero1967, Captchad, Cedar101, ClueBot NG, Craxic, Daniele Gallesio, David.moreno72, DavidLeighEllis, Debashish, Demonkoryu, Dgpop, Diannaa, EdijsKolesnikovics, Ekamara, Enterprisey, Ethaniel, ExilorX, Faolin42, François Robere, Frap, FreeRangeFrog, GCarty, Gbouzon, GermanJoe, Gfc, Heidirose12345, Henklaak, HenrikKronborgPedersen, HenriqueRocha, Hpesoj00, I dream of horses, Idiotechie, Ifnord, InverseHypercube, Ipwxy, IronGargoyle, Isi96, Jaalto, Jago84, Jahudgins, Janaagaard, Jarble, Jcodetips, Jim1138, Jobin Bennett, JorisvS, Juansempere, KH-1, Kmogan17, Kreinba, Leem02, Maggyero, Magioladitis, Marti4d, Materialscientist, Matinict, Mcsee, Mild Bill Hiccup, MrOllie, Mtbradle, Nigos, Nmondal, Norm mit, Notivago, Nurieta, OrenBochman, Oshwah, PapaBaugh, Paralyz3, PatheticCopyEditor, Peppy Paneer, Peterl, Pinethicket, Pluma, Pmussler, Pnm, Pointillist, Polymerbringer, Quoth-22, Ravensfire, Ravivc, Richiebful, Riick, Robert Illes, Rogério Brito, Rotring, Sae1962, Savvo, Serketan, Shi Hou, Simpatico qa, Slinkp, SouthLake, Sun Creator, Tea2min, Tedickey, Thinking Stone, Thong10, Timp21337, Tony Mach, Traxer~enwiki, Turgan, Uzume, Vanderjoe, Vrenator, Widefox, WikiLaurent, Wingbullet, Xanzzibar, Xuranium, Yohanliyanage, Zymut, Ігор Дзюба, 248 anonymous edits

Adapter pattern Source: http://en.wikipedia.org/w/index.php?title=Adapter_pattern Contributors: Abdull, Abednigo, Alansohn, Alex Muscar, Alexius08, Andre Engels, Anonymous2420, Anthony Appleyard, Architectureblog, Ashrwe4a, BenFrantzDale, Blytkerchan, BotMultichill, Bravegag, BryanG, Bthachdev, CannonBallGuy, CatherineMunro, Chris.Soeffing, Conditioner1, Conditioner123, Cth027, Cyril Wack, DHN-bot~enwiki, Demonkoryu, Doug Bell, EVula, Edenphd, EdijsKolesnikovics, Eitan Behar, Eudoxie, Frap, Fred Bradstadt, Giantbicycle, GilHamilton, Grendelkhan, Guy Macon, Gwern, Hao2lian, Happyser, Hardywang, Hipal, Hu12, HughD, I dream of horses, IanLewis~enwiki, Intgr, Ivant, J36miles, JBW, JMatthews, Jarble, Java-Edits, Jim1138, Jk2q3jrklse, Joerg Reiher~enwiki, JonathanLivingston~enwiki, Jonon, Jordanarseno, Julian3833, KevinTeague, Klaus3b, Luís Felipe Braga, M4gnum0n, MCSH, MER-C, Magioladitis, Marudubshinki, Materialscientist, Matinict, Matthiaspaul, Maximno, MichaelRWolf, Monkeyget, MrOllie, Mshravan wiki, Msjegan, Mtasic, Muirski, Mxn, NE Ent, Nbarth, Niceguyedc, Nnemo, Noamtm, OrangeDog, Pcb21, PfhorSlayer, Pkbwcgs, PriyankaSabharwal, Psg5p, RA0808, RedWolf, Rimshot, Roger.wernersson, Ronslow, Ruud Koot, Sae1962, Saketmodi96, Samsara, SergejDergatsjev, Sietse Snel, Simplexity22, Sir Nicholas de Mimsy-Porpington, Slaykovsky, Spoon!, Stalker314314, Stamptrader, SteinbDJ, Stephen.mcmaster, Strib, Synchronism, TakuyaMurata, Tarquin, Tea2min, TheParanoidOne, ThomasO1989, Trashtoy, Tuntable, Vanderjoe, Vanmaple, Vghuston, Vikalpsingh, Vovanada, Wapcaplet, WeNDoR, Wickorama, Wikiluwatar, Wikipelli, Wookietreiber, 233 anonymous edits

Bridge pattern Source: http://en.wikipedia.org/w/index.php?title=Bridge_pattern Contributors: Abednigo, Alainr345, Albert cheng, Andriiko, Andy Dingley, Anthony Appleyard, Areicher, Argel1200, Augurar, Beland, BenFrantzDale, Billyblind, Blurrymoi, Bthachdev, Burns700, Bytebear, Cdunn2001, Chimply, Chochopk, Cipherynx, Cmdrjameson, Cra88y, CruftForce7, Cruscant3, DCEdwards1966, DHN-bot~enwiki, Daydreamer302000, Dddenton, Deathy, Diannaa, Djmckee1, Drrngrvy, Długosz, Eacameron, Eahlay, Edenphd, Editorfun, ErikHaugen, Faradayplank, Frap, Frecklefoot, Fred Bradstadt, Ftiercel, GiM, Gronk Oz, Hao2lian, Heron, Hnc14, Honestshrubber, Hu12, ImageObserver, Ira Leviton, Iridescent, Jaecheol.shin, JasonR., Java-Edits, Javier.eguiluz, Jimlonj, Joke de Buhr, Kazubon~enwiki, Kellen, Khalid hassani, Kleuske, Lacypaperclip, Lathspell, Lexxdark, Lukasz.gosik, Luís Felipe Braga, Lylez, M.mateeullah, M4gnum0n, MER-C, Magioladitis, Malaki12003, Manoel.rui, MattGiuca, Matěj Suchánek, Mcavigelli, MichalKwiatkowski, Mikemill, Mintguy, Mjworthey, Mkell85, Mormat, Msjegan, Mtasic, Mxn, My-2-bits, Narcelio, NickelShoe, Odie5533, Omicronpersei8, Patrick Schneider, Pcb21, Phil Boswell, Pmussler, Pratyya Ghosh, Profaisal, Ptbotgourou, Quuxplusone, RedWolf, Rimian, RobinHood70, Rouven Thimm, Rror, Ryanvolpe, S.K., Sae1962, Saw303, Seanhalle, Seethefellow, Slaykovsky, Spintendo, Springnuts, Sugarfish, Supadawg, Supersid01, TakuyaMurata, Tea2min, TheMandarin, Thomas Linder Puls, Tim.simpson, Topdeck, Torc2, Umreemala, Unyoyega, Usmanmyname, Vanderjoe, Vermiceli, Vghuston, Vladimir Bosnjak, Wapcaplet, Wiki Raja, Wikidicted, Ykhwong, Zundark, 249 anonymous edits

Composite pattern Source: http://en.wikipedia.org/w/index.php?title=Composite_pattern Contributors: A876, Aaron Rotenberg, Abednigo, AdrianHesketh, Al Legorhythm, Alainr345, Albert cheng, Andrewtkchan, Anonymous2420, Anthony Appleyard, Bangbang.S, BenFrantzDale, BradBeattie, Braiam, Bravegag, Bthachdev, Bunnyhop11, CMosher01, CatharticMoment, Charles Matthews, Chimply, Coffeeflower, DCrazy, Damien Cassou, Darkspots, Decltype, Dycedarg, Dysprosia, Edenphd, Emufarmers, Ewger, FrankTobia, Fred Bradstadt, Gaurav1146, Gene Thomas, Gilliam, Gkarlic, Hairy Dude, Hao2lian, Harborsparrow, Hephaestos, Here2help, Hervegirod, Hu12, Hujintao hjt, ImageObserver, InverseHypercube, J.delanoy, J0no, Java-Edits, Jeepday, Jicksonp, Jogerh, Joyous!, Judgesurreal777, Kars~enwiki, Kate, Kstone999, KylieTastic, Larry laptop, Lathspell, Lukasz.gosik, Luís Felipe Braga, M4gnum0n, MER-C, Matekm, Matěj Grabovský, Mefyl~enwiki, Mik01aj, MikalZiane, Mike926908240680, MrOllie, Mrwojo, Msjegan, Mtasic, Nagnatron, Narcisse, Nataliepis, Nick1915, Nikai, OccultZone, Pearle, Pinguin.tk~enwiki, Pmussler, Ptbotgourou, RedWolf, Rishichauhan, RobinHood70, Sebras, Shabbirbhimani, Shellwood, Shivendradayal, Simplexity22, Skapur, Skarebo, Slaykovsky, Sneftel, Stwalkerster, TakuyaMurata, Thamaraiselvan, The Thing That Should Not Be, Thomas Linder Puls, Trashtoy, Tubalubalu, Umreemala, Uzume, Vanderjoe, Vermiceli, Vinhphunguyen, Vishalmamania, VoABot II, Vonkje, Waggers, Wainstead, Whirlium, Will2k, Winnwang, Wkjyh, Zarcadia, Zoz, Zymut, 220 anonymous edits

Decorator pattern Source: http://en.wikipedia.org/w/index.php?title=Decorator_pattern Contributors: Adam Zivner, Ahoerstemeier, Aihtdikh, Anakin101, Andy Dingley, Anthony Appleyard, Arny, Awistaiw, BenFrantzDale, Benediamond, Betseg, Bob Stein - VisiBone, Booler80, Bravegag, Bthachdev, C++Bro123, Cedar101, ClueBot NG, Codysnider, Conditioner1, Cybercobra, DHN-bot~enwiki, Dantheman531, Dineshmore, Dnesteruk, Doradus, Download, EdC~enwiki, Edenphd, Eellor, Einsub, Eitan Behar, EliHunter173, Eric-Wester, FatalError, Francesco Terenzani~enwiki, Frap, Gasparovicm, Gerel, Ggenellina, Ghinrael, Grokus, Gslockwood, Gwern, Harborsparrow, Hesperian, Hipal, Htmlboss, Hu12, Hunting dog, ISynpi, Itai, J.lonnee~enwiki, J1o1h1n, Java-Edits, Jim1138, Joriki, João Guilherme Farias Duda, Khmer42, Kstone999, MER-C, Maggyero, Maksudmasud, Manohar reddy123123, Materialscientist, Matt Crypto, Mild Bill Hiccup, Mipiro, Mjresin, Mortense, Motine, Msjegan, Mtasic, Murtasa, Nafeezabrar, Nbarth, Nheirbaut, Nichobouma, Odie5533, Pharaoh of the Wizards, Photonique, Phresnel, Pljungqv, Pmussler, Qwertyus, RUL3R, Radiodef, RobD1, Rrburke, Rtc, Sae1962, Seanhalle, Servel333, SheriffIsInTown, Sjö, Steinm07, Subhammittal08, Tashuhka, Tdslk, Tea2min, Terry Rod, Tgwizard, ThomHehl, Tomerfiliba, Trashtoy, Umlcat, Urhixidur, Vanderjoe, Vghuston, Wackimonki, Widr, Wikidrone, Wildewouter, XcepticZP, Yuqingalex, Zwker yu, Zymut, ʘx, 277 anonymous edits

Facade pattern Source: http://en.wikipedia.org/w/index.php?title=Facade_pattern Contributors: A5b, Abatishchev, Abdull, Abednigo, Aff123a, Andy Dingley, Andyluciano~enwiki, Anthony Appleyard, Arch4ngel, Arvindkumar.avinash, Ashlux, B3t, BOTarate, Beland, BenFrantzDale, C++Bro123, Cedar101, ChamithN, Chestertan, ClueBot NG, Cuongtransc, Cybercobra, DHN-bot~enwiki, Darkmane, Deepfriedokra, Deflective, Demonkoryu, Dkeithmorris, Dorsetonian, Dotancohen, Dreftymac, Dw31415, Dysprosia, FeRDNYC, Forseti, Frap, Frederikton, Fuhrmanator, Hairy Dude, Hangy, Hao2lian, Hofoen, Hu12, IanLewis~enwiki, Immure, ImperfectlyInformed, Jandalhandler, Jarble, Java architect, Jellysandwich0, Jfalvarez, Joe Schmedley, Jogloran, John of Reading, Johndoe312, Jorend, Jussist, Kaartic, Kaikko~enwiki, KatnissEverdeen, Khishig.s, Kstone999, Kwamikagami, Lathspell, Leonard G., LeonardoRob0t, Lpenz, Lukasz.gosik, Luís Felipe Braga, M4c0~enwiki, MER-C, Magioladitis, Mahanga, Materialscientist, Moggie2002, MrOllie, Msjegan, Mtasic, Mvc045, Mxn, Narcissus, Nate Silva, Nibblus, Nickshanks, Otterfan, Owen214, PBS, Puchiko, Rajeevrvis, RedCrystal, RedWolf, RobinHood70, Sae1962, Santihollmann, Scullder, Slaykovsky, Stevegrunwell, Svick, Synook, TakuyaMurata,

Tea2min, Thadius856, TheRealMoser, Thtatithticth, Tony Sidaway, Tormit, Trashtoy, Vald, Vanderjoe, Wainson, Wavelength, Wookie2u, Wwjdcsk, XaeroDegreaz, Xiaoddkkwe, Xrm0, 에 멜

무 지 로~enwiki, 188 anonymous edits

Flyweight pattern Source: http://en.wikipedia.org/w/index.php?title=Flyweight_pattern Contributors: Abednigo, Abhi2434, Accelerometer, Ageekymonk, Alanjds, Albert cheng, AlphaWiki~enwiki, Amniarix, Andy Dingley, Anirudhvyas010, Anthonygerrard, Anticipation of a New Lover's Arrival, The, Artcoding, Beland, BenFrantzDale, Beryllium, BigDunc, Blastthisinferno, Bthachdev, CMosher01, CayceBalara, Cedar101, Cgodley, Chase.Gilliam, Chris the speller, Cline22, ClueBot NG, Cmthacker, Ctxppc, DHN-bot~enwiki, DanielBrauer, DannyS712, DaveLiu, DavidHarkness, Debajit, Demonkoryu, Dennis714, Diego Moya, Ebswift, Emj, Empatiia, Entropy, Frap, FroZman, Gnp, Hao2lian, Henke37, Hmglasgow, Hrs2, Hu12, Ira Leviton, Java architect, JeslieC, Jk2q3jrklse, John of Reading, Justo, Kri, Kstone999, Kurt Jansson, Lambda Fairy, Lathspell, Lazeroptyx, Lylez, LyricCoder, MER-C, Markuzo, Martnym, Maxim, Mdjpurdon, Micah hainline, Mrsoto, Msjegan, Mtasic, Mxn, Mylesmcdonnell, Naasking, Nearinfinity, Neils51, Nexus26, Night Goblin, Northerly Star, Odie5533, Op12, Oualid.alami, Pauljohanneskraft, Pcb21, PierreAbbat, Pkinsky, Ptbotgourou, Qzd, Ramram 43210, Ray Van De Walker, Raymond.naseef, Rdhettinger, RedWolf, RobinHood70, Roboto de Ajvol, Rooterk, Rudolf Adamkovic, Ryanl, Sae1962, Senu, SolskGaer, Sproul, Sun Creator, SuperDuffMan, TakuyaMurata, Teglsbo, The Wild Falcon, Trappist the monk, Tshak, Twyford, Vanderjoe, Vipinhari, Vltsu, Vusalalishov, Warren, WestwoodMatt, Wizgob~enwiki, ZacBowling, Zhaojianhua, Zozakral~enwiki, Zymut, 147 anonymous edits

Front controller Source: http://en.wikipedia.org/w/index.php?title=Front_controller Contributors: AlanUS, Andreas Kaufmann, Angrytoast, BBL5660, Bcosca, Bevo, Biosunbj, Bmarriner, CaritasUbi, Chadmyers, Dewritech, Dmforcier, Dsimic, Ekerazha, Favonian, Frank.blaauw, Frap, Griba2010, Hmglasgow, Ian (Wiki Ed), IznoRepeat, Jase21, Jb10210, Jpp, Kazfernandes, Kentoshi, Kku, Ludde23, Matekm, Mindmatrix, MrOllie, Narky Blert, Nperriault, Prasanna143, Qizhongzhi, RHaworth, Sae1962, Softzen, TheImaCow, TheJJJunk, Tourorist, Userform, Uzume, Washi, Wavelength, 62 anonymous edits

Marker interface pattern Source: http://en.wikipedia.org/w/index.php?title=Marker_interface_pattern Contributors: Abdull, Arthena, Ashutosh.shukla, Avivey, Codename.venice, Crystallizedcarbon, Doug Bell, Elf, EmphasisMine, Erechtheus, Frap, Gwern, Jay, Jogloran, Jpp, Julesd, KevinTeague, KylieTastic, Magioladitis, MoraSique, NickBush24, OpenFuture, Piano non troppo, PolyGlot, Quagmire, RedWolf, RobinHood70, SAE1962, Texture, Timwi, 42 anonymous edits

Module pattern Source: http://en.wikipedia.org/w/index.php?title=Module_pattern Contributors: Bearcat, Bgwhite, CWenger, Comatmebro, Frap, Gamemaster eleven, Hmglasgow, Igorcadelima, John of Reading, Johnswolter, Jonathan2112, Lfstevens, Niceguyedc, Rearhh, Redrose64, Rjwilmsi, Sun Creator, Ted Wulf, Umlcat, Wenerme, 36 anonymous edits

Proxy pattern Source: http://en.wikipedia.org/w/index.php?title=Proxy_pattern Contributors: 0612, Abdull, Abednigo, Abelson, Ad1976, Andy Dingley, Anonymous2420, Anthony Appleyard, Audriusa, Avocado, Azanin, BOTarate, Babomb, Beland, BenFrantzDale, Bobertyy, Bravegag, Brownb2, Bthachdev, C++Bro123, CAPTAIN RAJU, Cholmes75, Christoph hausner, Cjeyabalan, ClueBot NG, D3xter, Decltype, Demonkoryu, Ebswift, Edenphd, Edivorce, Elector101, Espresso1000, Frap, Fred Bradstadt, Fritz freiheit, Ftiercel, Hao2lian, Hofmic, Hu12, Jamelan, Jauerback, Java-Edits, Jay, Jd gordon, JeR, Jthiesen, LaM3a, Lathspell, Laughmetal, Livebreeze, LokeshRavindranathan, Lukasz.gosik, Lumingz, Lusum, MBAMALU KENNEDY, MER-C, Mangostaniko, Marianobianchi, Markonator, Matekm, Materialscientist, Msaada, Msjegan, NathanBeach, Nbarth, Nonomy, Noscripter, Nunopicado, Nurg, Nzroller, Octaperi, Odie5533, P0per, Pateeludg, Pham Phi Long 1606, Philip Trueman, Prickus, Puplan, Quuxplusone, RedWolf, Rich Farmbrough, Rich257, RobinHood70, Royalguard11, Sae1962, SanthoshRadhakrishnan, Shea.m.brennan, Shlomif, Slaykovsky, Snaxe920, Softzen, TakuyaMurata, TheParanoidOne, TravisHein, Ubiquity, Undefined2023, Uzume, Valodzka, Vanderjoe, VladM, Will2k, Wlievens, Zalmoksis, Zolookas, Zozakral~enwiki, Zymut, 180 anonymous edits Article Sources and Contributors 166

Twin pattern Source: http://en.wikipedia.org/w/index.php?title=Twin_pattern Contributors: Dgpop, EdiTBls, Frap, Gronk Oz, Jarble, Raymie, Shevonsilva, 10 anonymous edits

Blackboard (design pattern) Source: http://en.wikipedia.org/w/index.php?title=Blackboard_%28design_pattern%29 Contributors: Beland, Clon1x, ClueBot NG, DecaChambry, Eugeneiiim, Graf von Monte Christo, HistoryTeacher4272, Jamietw, Joshua Scott, Lfstevens, LilHelpa, Myasuda, Nuker12345, Sae1962, Shevonsilva, Sprhodes, Vexations, 5 anonymous edits

Chain of responsibility pattern Source: http://en.wikipedia.org/w/index.php?title=Chain_of_responsibility_pattern Contributors: Abdull, Abednigo, AboutMM, AlanUS, AnotherWikiOne, Arch4ngel, Architectureblog, Arjunkul, B3t, Bearcat, BenFrantzDale, Bin Sowparnika, Bravegag, Brenont, Brian428, Bthachdev, Celephicus, Chris6647, ClueBot NG, Cmdrjameson, Courcelles, Cristian.bogdan, Ctxppc, Danny, Demonkoryu, Eknv, Ermunishsodhi, Estevoaei, Fmstephe, FoCuSandLeArN, Fowlerwill, Frap, Gmamaladze, Gotovikas, Hao2lian, Hipal, Hu12, Ilion2, Itschris, JDL440, Jarble, Jessejohnsohn, Jhatax, Jldupont~enwiki, JoaoRicardo, Jokes Free4Me, Khalid hassani, Khym Chanur, King Lopez, Kinguy, Kstone999, Lathspell, Lylez, M4c0~enwiki, MCEmperor, MER-C, Marcelo Pinto, Max siberian, Merutak, Mikaey, MrOllie, Nomad7650, Olbat, Patient dino, Pavel ryzhov, Pcraven, Porqin, Premil, RedWolf, Reyjose, Rhomboid, Rice Yao, RobinHood70, Roboto de Ajvol, Rtc, Seaphoto, Shades97, Slaykovsky, Soubok~enwiki, Struggling wang, Sun Creator, Tabletop, TakuyaMurata, TechnicallyCorrectEngineer, TheParanoidOne, Thomas Linder Puls, Tnimas, Tudor497, UY Scuti, Vanderjoe, Vangelis.ts, Varuncnitw, Vghuston, Vikasgoyal77, Vina-iwbot~enwiki, Vyuschuk, WOSlinker, Wbstory, Wikidrone, Zaletskyy, anonymous edits 137 ,رهظم ,Zyx

Command pattern Source: http://en.wikipedia.org/w/index.php?title=Command_pattern Contributors: Abdull, Abednigo, Acmeacme, Arjayay, Ascánder, B3t, Barry Fruitman, Beland, BenFrantzDale, Bennor, Bgwhite, Bipedalpedia, Bluemoose, Bravegag, C++Bro123, Cerkit, ChesMartin, Chester Markel, Chris the speller, Cloudmonkey, ClueBot NG, Crazyblocks, Crhopkins, Darklilac, DavidBourguignon, Daydreamer302000, Dazhiruoyu, Demonkoryu, Dewritech, Dharesign, Dhruv Paranjape, DotnetCarpenter, Doug Bell, Druckles, Drypht, Dtbullock, Ebainomugisha, Edward.in.Edmonton, Ehn, Elaz85, Evan.wondrasek, Exe, Eyewax, Frap, Fred Bradstadt, Gene Thomas, Gmoore19, GregorB, Gwern, Hao2lian, Happyser, HasharBot~enwiki, Hipal, Hooperbloob, Hu12, IanVaughan, Informatik01, JHunterJ, Jensck93, Jeremy Bidet, Jevansen, JoaoTrindade, John Lindquist, Jorend, Karuppiah, Kate, King Lopez, Kku, Kstone999, Lightdarkness, LilHelpa, MER-C, Mahanga, Materialscientist, Mernen, Mjworthey, Mloskot, Modify, MrOllie, Nakon, Napstr4u, Nathan Ra, OldCoder, Omegatron, Orangeroof, Oster54, Oubless, Owentaylor25, Patient dino, Pcb21, Pharaoh of the Wizards, Pi Delport, PoundingCode, Rahul verma india, RedWolf, RexxS, Rijkbenik, Rmembrives, Roboto de Ajvol, Ryannnnnnn, Ryanzp, SJP, Sae1962, Scottywong, Seanhalle, Seaphoto, ShyhHuaHung, Sir Dirt, Sjw17, Sleepful, Smsiebe, Svick, TakuyaMurata, Tea2min, Techno mancer, Telekobold, Terheyden, Terry Rod, Terry.kfwong, TheParanoidOne, Tnimas, Trevor Johns, Unseenacademic, Uzume, Vald, Vanderjoe, Vermiceli, Vghuston, Vikasgoyal77, Volvens, Vsync, Warren, Widefox, Will2k, Zixyer, Zozakral~enwiki, 235 anonymous edits

Interpreter pattern Source: http://en.wikipedia.org/w/index.php?title=Interpreter_pattern Contributors: Abednigo, Allan McInnes, Andy Dingley, Andypayne, Asciilifeform, BenFrantzDale, Borderj, Cedar101, ClueBot NG, Cmccormick8, Cybercobra, Davewho2, Felix558, Frap, Fredrik, Furrykef, Gelinp, Gwalla, Hao2lian, Hipal, Hu12, Humble java, Iskarky, Jamesdhutton, Jarble, Java-Edits, Jerryobject, John of Reading, Komap, L30nc1t0, Lathspell, Lonelybug, Lukasz.gosik, Magioladitis, Mahanga, Matekm, Mecanismo, Melcous, Merutak, Mikhail Ryazanov, MithrandirMage, Mrwojo, NingWei.DE, Odie5533, Pcb21, RJFJR, RedWolf, Rice Yao, RobinHood70, Rogerwhitney, Rosiestep, Sae1962, SamePaul, Seaphoto, Svick, TakuyaMurata, TheParanoidOne, Trappist the monk, Vanderjoe, Vghuston, WoodZzzzz, Yuqingalex, Zozakral~enwiki, 73 anonymous edits

Iterator pattern Source: http://en.wikipedia.org/w/index.php?title=Iterator_pattern Contributors: Abdull, Abednigo, Albert cheng, Andy Dingley, Angilly, Anna Lincoln, Ayvengo21, Beland, BenFrantzDale, Bgwhite, Bnedelko, BrownHairedGirl, Btx40, Bytebear, CanisRufus, Cedar101, Chmarkine, ClueBot NG, Cybercobra, D chivaluri, Dcirovic, Dhulme, Eaolson, Eknv, Frap, Galiusk, Ghthor, Greenrd, Hao2lian, Hipal, Hu12, Iridescence, IznoRepeat, J04n, Java architect, Jerryobject, Jogloran, KAMEDA, Akihiro, Kmilotxm, Lababidi, Leibniz, Luijar, Magioladitis, Marj Tiefert, Matekm, Mfilatov, Mhitza, Mormat, Mtamazlicaru, Nij4t2, Odie5533, Ogmios~enwiki, PraveenKumarVR, Radagast83, Ravindra Josyula, RedWolf, Sae1962, Seffer, Shane.lockwood, TakuyaMurata, TechTony, Tomtheeditor, Trashtoy, Usien6, Vanderjoe, Vghuston, Vishnuvardhan leela, Winxa, Woodlot, Yuqingalex, Zerokitsune, Zozakral~enwiki, Zymut, ʘx, 112 anonymous edits

Mediator pattern Source: http://en.wikipedia.org/w/index.php?title=Mediator_pattern Contributors: 16@r, Abednigo, Addshore, Adelesse, Alex.proca, Amit.tejwani, Anonymous2420, BRW, Balu213, Bayesianese, BenFrantzDale, Bender235, Bkonrad, Brian Tomasik, Bwolfington, C3foncea, CiaPan, ClueBot NG, Colonies Chris, Crissov, Cybercobra, Dawynn, Dcflyer, Download, Exe, Flammifer, Frap, Furrykef, Galhalee, GhostInTheMachine, Grancalavera, Grizzly33, Hao2lian, Hipal, Hu12, Ibic, If R-rated movies are porn, it was porn, Jarble, Java-Edits, Jebdm, Jellysandwich0, Job Noorman, JosRog, Jrockley, KarenJoyce, Kimoaen, Kku, Lathspell, Leafyplant, Mariolopes, Mhaeusser, Mormat, Nagnatron, Nexus26, Pietrodn, Ptbotgourou, RedWolf, Rjnienaber, RobDe68, RobinHood70, RoyBoy, Royalguard11, Rsrikanth05, Sae1962, TakuyaMurata, TheParanoidOne, ThomasO1989, TomCerul, Toreau, Twyford, Vanderjoe, Vghuston, Vijayekm, VladM, Yuqingalex, Zozakral~enwiki, Zymut, 137 anonymous edits

Memento pattern Source: http://en.wikipedia.org/w/index.php?title=Memento_pattern Contributors: Aaron Rotenberg, Abdull, Abednigo, Airsplit, Alainr345, Alvin-cs, Andy Dingley, BenFrantzDale, Bsivanov, CountRazumovsky, DHN-bot~enwiki, Frap, Galyathee, Gqbriggs, GregorB, Hao2lian, Heron, Hu12, JLaTondre, JorisvS, Kingturtle, Lathspell, Magic sergeant, MaheshZ, Mild Bill Hiccup, Mormat, Odie5533, Pcb21, Qwertyus, Rajah9, Ray Van De Walker, RedWolf, Rich257, RobinHood70, Royalguard11, Sardak, Seethefellow, Shadowjams, Slaykovsky, Spoon!, Stuart Yeates, Sushi Tax, TakuyaMurata, Tiagopsousa, Uv1234, Vanderjoe, Vghuston, VladM, Zeno Gantner, Zigmar, Zozakral~enwiki, Zymut, Æneas, 82 anonymous edits

Null Object pattern Source: http://en.wikipedia.org/w/index.php?title=Null_Object_pattern Contributors: 16@r, Abdull, Alexander Gorbylev, Andy Dingley, Annrules, Autarch, Bunnyhop11, C xong, C++Bro123, Carlosayam, Cedar101, ChrisGualtieri, ChuckTerry, Citation bot 1, Codename Lisa, Ctxppc, Cybercobra, Demonkoryu, Dhruv Paranjape, Dirk Riehle, Dpleibovitz, Eofster, FGRibreau, Favonian, Ferdinand Pienaar, FinalCodeDrop, Frap, GermanJoe, Gqqnb, Hairy Dude, Ice Keese~enwiki, Jarble, Jerome Kohl, Johndkane, Jpp, Kwikkode, MCSDWVL, Mahanga, Me, Myself, and I are Here, Michael Anon, Mild Bill Hiccup, Milhouse228, Mmaaco, Neelix, Nklv, Nnemo, Paulecoyote, Quitsspray, RandomDSdevel, Rjwilmsi, Rlss, Ruijoel, Smjg, Snaxe920, Spiritia, Svick, Teles, Teukros, Thelazwiki, Timwi, Tom Morris, Unclegene, Vaclav.Makes, Yegor256, Yossi Gil, Zawl, Zozakral~enwiki, 101 anonymous edits

Observer pattern Source: http://en.wikipedia.org/w/index.php?title=Observer_pattern Contributors: Aaronshaver, Alejandro.isaza, Andy Dingley, Anna Lincoln, Antonschastny, Ariadie, Arvindraivns, Avijeetsahoo, Bdanee, Beland, BenFrantzDale, Bkil, Bmusician, Briefstyle, C. lorenz, Capricorn42, Cbmeeks, Ch!p, Chaithanyaganta, ClueBot NG, Cosmicnet, Cosmin varlan, Countchoc, Darth Panda, DdEe4Aai, Decatur-en, Deineka, Devshop.me, Dough34, Dramartistic, Dudu90, Ebrahim, EcthelionGenesis, Ed Poor, EdijsKolesnikovics, Edward, Eknv, Emurphy42, Emw, Eric Le Bigot, Evertw, Excirial, Frap, Gang65, GeneralNotability, Gilliam, Gracefool, GregorB, Gregorybleiker, Götz, Hervegirod, Hipal, HurryPeter, Hyuga, InverseHypercube, Ipatrol, Jarble, Jebdm, JnRouvignac, JohnPython, Jphollanti, Kaquito, Karl gregory jones, Katieh5584, Kku, Komap, Kstevenham, Kudchikarsk, Labviewportal, Lartoven, Leem02, Lpsiphi, M.amjad.saeed, Mahanga, Marie Poise, Martnym, Matthiaspaul, Mattjball, Mecanismo, MichaelPTaylor, Mratzloff, Mynameisbhaskarmishra, Mzyxptlk, Nbarth, Nebenots, Niceguyedc, Nickolas.pohilets, Oeoi, Ohnoitsjamie, OlEnglish, Oni.lore, Opera fera, OrangeDog, Pashute, PersonWhoLivesInHollyhurst, Peterl, Petrb, Philipp Weis, Pkbwcgs, Pmercier, Pmussler, Pratikpanda93, RatherDrunk, Reaper555, Redroof, Robbiemuffin, Rotaercz, Royote, SamuelHuckins, Sdesalas, Senthilblogs, Serols, Shane.lockwood, Shirtwaist, SlubGlub, Smk65536, Stephan Leeds, Terry.kfwong, Trustable, Tungmetal, UKoch, Uzume, Vahrokh, Vanderjoe, Vanished user giiw8u4ikmfw823foinc2, Vipinhari, Vishnuvardhan leela, Voyvf, VvV, WikiSolved, Willpwillp, Y.P.Y, YordanGeorgiev, Yuqingalex, Zozakral~enwiki, Zymut, トリプ, 289 anonymous edits

Publish/subscribe Source: http://en.wikipedia.org/w/index.php?title=Publish/subscribe Contributors: 4th-otaku, Abdull, Akb.wiki, Aliekens, Altenmann, Anaholic, B2u9vm1ea8g, Bagnolm, Beland, Bender235, Berndfo, Bjfletcher, Bob Wyman, Bosstiat, Bostwickenator, Bunnyhop11, Buzz-tardis, CanisRufus, Carbon Caryatid, Clarevoyent, ClueBot NG, Cmcqueen1975, Damiens.rf, DesolateReality, Dhauptman, Dougher, Dpm64, DuncanCragg, Edward Vielmetti, Enochlau, Fordsfords, Francesco-lelli, Frap, FuzzyBSc, Gaius Cornelius, Gbennett71, Group29, Harburg, Hidbaty223, Hobsonlane, Hussein.Juybari, ImaginationDave, IznoRepeat, JHunterJ, Jacobolus, Jamelan, Jauerback, Jerryobject, John at Lancelotlinc, Jolest, Josemariasaldana, Juergen.Boehm, KagamiNoMiko, KartikSinghal, Ken Birman, Kernel.package, Kgardner2007, Kku, Kmorozov, Kstevenham, Kyle Hardgrave, L200817s, Lant3rn1969, Logan, Lwihwr, Mahavishnu-ramakrishnan, Malin Tokyo, Mandarax, MeltBanana, Mfrisch, Michael.jaeger, Mild Bill Hiccup, Mohan8990, Mxn, Namlemez, Nanodance, Neustradamus, Nick Stavros, Nickg, Obcg, Peter Hitchmough, Pmerson, Pnm, Psy0rz, Puffin, Ray Van De Walker, Reflex Reaction, Rhekniz, RichardBanks, Richlitt, Robina Fox, Ruud Koot, S.borchers, SCFrench, Schollii, Sconaomi, Secretkeeper81, Skyerise, Wilbury, Staples1055, Stephan Leeds, Stewartm82, Subversive.sound, Supriyadevidutta, Suruena, SymlynX, T.J.A. Uhm, Tedernst, Tervela,

Themfromspace, Tzoght, UphillAnemone, VasilDimov, Vegaswikian, Venkykadali, Wavelength, WikHead, Willpwillp, Zhangsongyang, ✓, 用 心 阁, 166 anonymous edits

Design pattern Servant Source: http://en.wikipedia.org/w/index.php?title=Design_pattern_Servant Contributors: Aerovistae, AzaToth, Beoros, Combovercool, Crionell, Dexp, Dthomsen8, Faisalbegins, Happyser, Ibic, Ilya Kogan, Invitrovanitas, Jarble, Mathwiz777, Qwertyus, RHaworth, Rudyment, Ryoga Godai, Stfg, Twhitmore.nz, VeselyBrumla, Zorrinito, 16 anonymous edits

Specification pattern Source: http://en.wikipedia.org/w/index.php?title=Specification_pattern Contributors: Agerace, Alexei.surovi, Andy Dingley, Asd.and.Rizzo, B4hand, Beland, CanisRufus, Code.Combustion, Demonkoryu, Dewritech, Esowteric, Frap, GhostInTheMachine, Gilbertxenodike, GoingBatty, Happyser, Ivant, IznoRepeat, Juancadavid, Kku, Maralia, Merarischroeder, Mirko Raner, MovGP0, Narky Blert, Neoneye, Ofungus, RickBeton, Sotonika, Squishymaker, Svallory, Torc2, Ts.skowronski, WOSlinker, Wavell2003, WobblyWibbly, anonymous edits 49 ,םודנר ,Zozakral~enwiki

State pattern Source: http://en.wikipedia.org/w/index.php?title=State_pattern Contributors: Abednigo, Aehomay, Allan McInnes, Anonymous2420, Babomb, BenFrantzDale, BennyD, CanisRufus, Cedar101, Cth027, Deltaflux, Edenphd, Eknv, Ertwroc, Estevoaei, Frap, Frigoris, FunnyMan3595, Garyczek, GhostInTheMachine, Goddardpk, Hao2lian, Hariharank12, Hu12, IanVaughan, IceWelder, Jamesontai, Java-Edits, Jeepday, Jlechem, JoaoTrindade, John of Reading, Joshua Scott, Julesd, Laughmetal, LuckyStarr, Luigi30, M4bwav, Magioladitis, Matěj Grabovský, Mecanismo, Miroseyn, MithrandirMage, Mormat, MrOllie, Naasking, Nitin.nizhawan, NiveditaSancheti, Pageofswords, Pdhooper, Pilotguy, Pmussler, RedWolf, Roboto de Ajvol, Rory O'Kane, Ruud Koot, Sae1962, Subtractive, Suniltg, TakuyaMurata, Tassedethe, Tea2min, Terheyden, TheParanoidOne, ThomasO1989, Tom.Reding, Userask, Vanderjoe, Vghuston, Zymut, 94 anonymous edits Article Sources and Contributors 167

Strategy pattern Source: http://en.wikipedia.org/w/index.php?title=Strategy_pattern Contributors: AR15DUDE, Abdull, Abednigo, Aingeruzuria, Andy Dingley, Anirudhvyas010, Ap0st8c, Atree, Auraxangelic, AustinBlues, BOTarate, Banool1000, Beland, BenFrantzDale, BlueTaRaKa, Bocsika, Candide124, ClueBot NG, Codepolarbear, Cst17, Cybercobra, DAVilla, DHN-bot~enwiki, Daemonicky, Danny childs19, DavidLeighEllis, Dcadenas, Ddonnell, Decltype, Denisarona, Dngache, Dougher, Dybowskijr, Edenphd, Equendil, EwgB, Feliperomero3, Finked, Flex, Frap, GeoffMacartney, Gf1809, Ghazi20734, GhostInTheMachine, Gluegadget, Gracefool, GünniX, Hao2lian, Helmerh, Hipal, Hosamaly, Hu12, Humble java, Integralsun, InverseHypercube, Ionut Penciuc, Java-Edits, Jems420, Jerryobject, Jncraton, Jonasschneider, Joswig, Jpablo.romero, JustinKoser, Kameshwarg, Kensenjohn, Kingfishr, Kku, Landisdesign, Liko81, Liorkoren77, Loadmaster, Lotje, Luís Felipe Braga, M.kumar1982, M4gnum0n, MER-C, Mahanga, Marco Krohn, MaxS 33, Md2perpe, MichalKwiatkowski, Mik01aj, Minddog, Mjchonoles, Mlibby, MrOllie, Nnemo, Omer Hassan, Ospalh, Owenjonesuk, PJonDevelopment, PeterRitchie, Pgan002, Pinethicket, Platypus222, Pmussler, Ptoonen, Ptyxs, Pzrq, Quuxplusone, Qwertyus, Radon210, RedWolf, Redroof, Richard.a.paul, Rikesh kisnah, Riki, RobinHood70, Roboto de Ajvol, Ruud Koot, Sae1962, Schan2001, SlubGlub, Snaxe920, SnowCambodia, Solvemon, Southen, Spookylukey, SpuriousQ, Sumanthtamma, Sungur, Supadawg, Tafadzwakombe, The Wild Falcon, ThomasO1989, Tim-bezhashvyly, TjerkWol~enwiki, Todd, Tombomp, Torc2, Uzume, Vanderjoe, Vghuston, Vgrund, Wenerme, Wikidrone, Wmwallace, Woohookitty, XcepticZP, Zozakral~enwiki, 259 anonymous edits

Template method pattern Source: http://en.wikipedia.org/w/index.php?title=Template_method_pattern Contributors: 49TL, AHMartin, Abednigo, AleaB, AllenDowney, Allstarecho, Andreas Kaufmann, Andy Dingley, Anjsimmo, Anonymous2420, Antonielly, Arenaaz, Arjayay, Asorgiu, Beland, BenFrantzDale, Chriki, Coconut99 99, Cp111, DaveLiu, David.moreno72, Dorftrottel, Dougher, Dysprosia, Edenphd, Exe, Fanzhao1986, Frap, Fredrik, GiedrBac, Hao2lian, Hipal, Hu12, I dream of horses, Ibadibam, Iridescent, Jcodetips, JonatanAndersson, Jonesey95, JovianEuropa, Jsmith030416, KJS77, KJedi, Kennethaw88, Kgeis, Klodr, LanceBarber, Liko81, LordTorgamus, MER-C, Magioladitis, Mahanga, Mange01, Merutak, Michael Hardy, MiguelMunoz, Mormat, Mrwojo, NingWei.DE, Normandomac, NuclearDuckie, Nyq, Oleg Alexandrov, Ontist, Pbyhistorian, Pmussler, Pne, Ptbotgourou, Quuxplusone, Rafsan 033, RedWolf, Reinis, Remcelfr, Remuel, Richard Katz, Rjwilmsi, Roadrunner, Rob*, Russell Triplehorn, Ruud Koot, Sae1962, Supadawg, T1mmyb, TJ09, TakuyaMurata, Teles, TheParanoidOne, Theprogrammer, Tonymarston, Unnikked, Vanderjoe, Vegaswikian, Vghuston, Vladimir Bosnjak, Wavelength, Zarkonnen, Zhen Lin, Zozakral~enwiki, 130 anonymous edits

Visitor pattern Source: http://en.wikipedia.org/w/index.php?title=Visitor_pattern Contributors: --, Aeolian145, Ahappyboy191666, Akanksh, AlanUS, Alfatrion~enwiki, Alksentrs, Andrewman327, Andy Dingley, Andy.m.jost, Anirudhvyas010, Anonymous2420, Autarch, B3t, Beland, Bellowhead678, BenFrantzDale, Bennor, Billegge, Brandon, Bravegag, Bricegeumez, C++Bro123, C3foncea, CardinalDan, Cedar101, Cic, Computerwguy, Creamyhorror, D chivaluri, Decltype, Demonkoryu, Dnesteruk, Dominikwidomski, Edenphd, Eight40, Enormator, Eosrei, Fizzbann1234, FoCuSandLeArN, Frap, Ftiercel, Fuhrmanator, Fylwind, Gandalfgeek, Gereon K., GhostInTheMachine, Goyalsachin22, GregorB, Gsgg, Gyrobo, H662, HGoat, Hairy Dude, Hajatvrc, Hazard-SJ, Hedwig in Washington, Hipal, Hu12, Humble java, Ibic, Int19h, InverseHypercube, JamesPoulson, Jarble, Jcarroll, Jerryobject, Jjdawson7, Joel falcou~enwiki, Jokes Free4Me, Joswig, Jrduncans, KGirlTrucker81, KH-1, Kee.nam, Kraftlos, Kvng, Luiscolorado, M4gnum0n, MER-C, Maghnus, Magioladitis, Marau~enwiki, Martnym, Materialscientist, MattGiuca, Mfwitten, Michael-stanton, Mild Bill Hiccup, My Name is Christopher, Ntalamai, Objarni, Oerjan, Ohnoitsjamie, Ozba, Peter Erwin, Pewchies, Pkbwcgs, PolyGlot, Prodigel, PuercoPop, Pweifan, R5IJwcw2, Rahab rx, Rich Farmbrough, Riki, Sae1962, Salix alba, Sergei49, Skarkkai, Slaykovsky, Sleske, Stokkie64, Sun Creator, Svick, Szeder, Tea2min, ThePenultimateOne, Thinking Stone, Timenkov Fedor, Vanderjoe, Versus22, Vghuston, Vir4030, VoluntarySlave, WansWeter, Wikipodium, YahyA, Zozakral~enwiki, Zymut, ʘx, Ржавый Хомяк, 237 anonymous edits

SOLID Source: http://en.wikipedia.org/w/index.php?title=SOLID Contributors: 94rain, Abatishchev, Abelmoschus Esculentus, AlterEgo, Amakuru, Angela Harms, Antifrag, Arbautjc, Ashmoo, Bastie, Billinghurst, Billykirsch, Cambalachero, Cb22hh, Cipak, ClueBot NG, Comp.arch, Control.valve, CornellEngr2008, Cyfal, Danielflippance, DannyS712, DiscantX, Doc James, Dw122339, Fiftysquid, Flyer22 Frozen, Frap, GünniX, Hairhorn, Hartrik, HickoryOughtShirt?4, Hydrargyrum, Hyperforin, ImperfectlyInformed, IronGargoyle, Izno, Jengelh, Jeroen De Dauw, JorisvS, Joseph.l.hunsaker, Juisoo, Justapersona, KathirvelNatarajan, LeeRyanCampbell, LordOfPens, Magioladitis, Manoelcampos, Mcsee, Megabeing, MelbourneStar, Michael B. Trausch, Michael Hardy, MikeVitale, Mitzi Laszlo, Morignoratio, Mosrod, Mr. Smart LION, MrOllie, Nightfly85, NotMe45000, Npostolovski, Onlineworkeratwiki, Oshwah, Pablomendes, Pakaraki, Pcap, Prad Nelluru, Ptrb, Quiddity, Raztus, Rob Bednark, Rockin291, Rsrikanth05, Sae1962, SamCordes, Shintsu, Softzen, Stohn, Subversive.sound, Svick, Theprogrammer, Tim Ivorson, Vroo, Widr, YourMomIsFatAndUglyAndIDidHerLastNight321, ʘx, 112 anonymous edits

Single responsibility principle Source: http://en.wikipedia.org/w/index.php?title=Single_responsibility_principle Contributors: Andreas Kaufmann, Architectureblog, AxelBoldt, Cagliost, Cambalachero, Cfeltus, ClueBot NG, Colonies Chris, Coolzagger12, Cybercobra, Dawidl, Diego Moya, Duncan.sparrell, Grahamaaron, Hedgehog83, Ibrahim Rasel, IbrahimMNada, Iel1966, K4rol, Klodr, KylieTastic, Lightkey, Ligulem, LordOfPens, Mahanga, Mark Renier, Materialscientist, Mbkelly, Michael Hardy, MikeSchinkel, Mikeblas, MrOllie, Myrmecophagavir, NetherGranite, Oxy201, Ptrb, RDBrown, Scottmacpherson, Shaded0, Tlesher, Widefox, Wqwt, Wwheeler, YordanGeorgiev, 59 anonymous edits

Open-closed principle Source: http://en.wikipedia.org/w/index.php?title=Open-closed_principle Contributors: .digamma, Architectureblog, B3t, BenFrantzDale, Bevo, Cambalachero, Charlesb, Chronodm, ClueBot NG, Colonies Chris, Connelly, Craig.larman, Cybercobra, Dekimasu, Denisarona, DixonD, Doradus, Doug Pardee, Dough34, Echancrure, Fuzzybair, Gunsoft, Ivo.nascimento, Jgorman2, Jim1138, JorisvS, Kubanczyk, Lightkey, M4gnum0n, Maggyero, Mahanga, Marek69, Matt Crypto, Merlinsorca, Michael Hardy, Mortense, PJonDevelopment, PabloStraub, Pindakaas, Praveenv253, Ptrb, Rich Farmbrough, Sagaciousuk, Senyor, Spayrard, Srasku, Tombart, 57 anonymous edits

Liskov substitution principle Source: http://en.wikipedia.org/w/index.php?title=Liskov_substitution_principle Contributors: 1ForTheMoney, A8UDI, Aaronchall, AdventurousSquirrel, Aftalavera, Akim Demaille, Alexey Muranov, Amakuru, Autarch, Bart Jacobs (Leuven), Beland, Bevo, Bgusiev, Btyner, Cambalachero, Cedar101, Cema, CiaPan, ClueBot NG, CornellEngr2008, Cth027, Cyde, DaltonSerey, Dha2019, DixonD, Doradus, Edward, Encladeus, Favonian, Foodgoesintummy, François Robere, Fredrik, Furrykef, Galobtter, Graue, Gregbard, GregorB, Gunsoft, Gzornenplatz, Headbomb, Hello71, Hronir, IMSoP, Imabuddha, Jamelan, Jennasloan, Jghaines, Jgorman2, Jhertel, Jochen Burghardt, Jwmurphy, Kate, Keplervic, LOL, Leibniz, Lightkey, MMSequeira, Macademe, Magioladitis, Manthonyaiello, Math120, Matěj Grabovský, Max613, MaxEnt, Mfwitten, Michael Hardy, Mike Schwartz, Miket25, Milliams, Nihiltres, Northamerica1000, OriumX, Oxy201, PabloStraub, Pcap, Phlebas, Pierre5018, Plasticup, Quinxorin, R. S. Shaw, RedWolf, Ricardohz, Ruud Koot, Sagaciousuk, Sasuke Sarutobi, Scott.fredericksen, Sct72, Serverside6, Simeon, Spayrard, StephenH, Stephenamills, Sumsum2010, TakuyaMurata, Tburket, Tea2min, The Anome, ThomasOwens, Tijfo098, Tronick, Widr, Yetiitey, 93 anonymous edits

Interface segregation principle Source: http://en.wikipedia.org/w/index.php?title=Interface_segregation_principle Contributors: Aaronchall, AlanUS, Alexsykie, AnturCynhyrfus, BBUCommander, Bevo, Bsdocke1, Cambalachero, DMSchneide, David Edgar, Digitalthom, Endpoint, GimliDotNet, Hcalvin, Huppybanny, Jhertel, Jinlye, Ketiltrout, Lightblade, Lightkey, LupusDei108, Magioladitis, MasonM, Michael Hardy, PabloStraub, Philu, Run1moore, SDX2000, Sae1962, Senyor, Tommy2010, 47 anonymous edits

Dependency inversion principle Source: http://en.wikipedia.org/w/index.php?title=Dependency_inversion_principle Contributors: 3enoit3, Alpinu, Andreas Kaufmann, Ashmoo, B2u9vm1ea8g, Barkeep, Beland, Bevo, Blaisorblade, Bmhm, Bpfurtado, Brettright, Cambalachero, Cyplo, Davewho2, David Edgar, Derekgreer, Dewritech, Diego Moya, Dlutz52, Długosz, Eaglizard, Ferdinand Pienaar, Ghinrael, HansLollo, Happy5214, I dream of horses, Ibadibam, JNBBoytjie, Jamieday, Jarble, Jeroen De Dauw, Jhertel, KLBot2, Kaartic, Kjkolb, Klodr, Lightkey, Ligulem, Linh.hoangng, Ljr1981, Loadmaster, Lpsiphi, Magioladitis, Majorsheisskopf, Martnym, MaxEnt, Mintwhip, Mister Mormon, Mk85 2, Mrflay, NickPenguin, Oneiros, Pwnage97, QueBurro, QuentinUK, R'n'B, Rafael Kenneth, Renaud Bancel, RitigalaJayasena, Ruud Koot, Sae1962, ShadowPhox, The wub, TomCerul, TomaszPierzchala, TommyX12, Tonymarston, Trophygeek, VictorYarema, WiseWoman, Xonqnopp, 108 anonymous edits Image Sources, Licenses and Contributors 168 Image Sources, Licenses and Contributors

Image:Abstract factory UML.svg Source: http://en.wikipedia.org/w/index.php?title=File:Abstract_factory_UML.svg License: Creative Commons Attribution-Sharealike 2.5 Contributors: Giacomo Ritucci File:Abstract factory.svg Source: http://en.wikipedia.org/w/index.php?title=File:Abstract_factory.svg License: GNU Free Documentation License Contributors: DoktorMandrake File:w3sDesign Abstract Factory Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Abstract_Factory_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Abstract Factory in LePUS3 vector.svg Source: http://en.wikipedia.org/w/index.php?title=File:Abstract_Factory_in_LePUS3_vector.svg License: Public Domain Contributors: B3t, Jdcollins13, Sarang File:Wikibooks-logo-en-noslogan.svg Source: http://en.wikipedia.org/w/index.php?title=File:Wikibooks-logo-en-noslogan.svg License: Creative Commons Attribution-Sharealike 3.0 Contributors: User:Bastique, User:Ramac et al. File:Commons-logo.svg Source: http://en.wikipedia.org/w/index.php?title=File:Commons-logo.svg License: logo Contributors: Anomie, Callanecc, CambridgeBayWeather, Jo-Jo Eumerus, RHaworth File:w3sDesign Builder Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Builder_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Builder UML class diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Builder_UML_class_diagram.svg License: Public Domain Contributors: Trashtoy File:w3sDesign Dependency Injection Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Dependency_Injection_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:w3sDesign Factory Method Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Factory_Method_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:New WikiFactoryMethod.png Source: http://en.wikipedia.org/w/index.php?title=File:New_WikiFactoryMethod.png License: unknown Contributors: User:Rforuupt File:Multiton.svg Source: http://en.wikipedia.org/w/index.php?title=File:Multiton.svg License: Creative Commons Zero Contributors: Sae1962 File:w3sDesign Prototype Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Prototype_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Prototype UML.svg Source: http://en.wikipedia.org/w/index.php?title=File:Prototype_UML.svg License: Creative Commons Attribution-Sharealike 2.5 Contributors: User:Giacomo Ritucci File:Singleton UML class diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Singleton_UML_class_diagram.svg License: Public Domain Contributors: Trashtoy File:w3sDesign Adapter Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Adapter_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:ObjectAdapter.png Source: http://en.wikipedia.org/w/index.php?title=File:ObjectAdapter.png License: Public domain Contributors: Albedo-ukr, BotMultichill, File Upload Bot (Magnus Manske), Flappiefh, Ftiercel, JuTa, LoStrangolatore, OgreBot 2, Rodhullandemu, 2 anonymous edits File:Adapter(Object) pattern in LePUS3.png Source: http://en.wikipedia.org/w/index.php?title=File:Adapter(Object)_pattern_in_LePUS3.png License: Public Domain Contributors: Amnon Eden (User:Edenphd) File:ClassAdapter.png Source: http://en.wikipedia.org/w/index.php?title=File:ClassAdapter.png License: Public domain Contributors: Albedo-ukr, BotMultichill, File Upload Bot (Magnus Manske), Joey-das-WBF, Liftarn, LoStrangolatore, OgreBot 2, Rodhullandemu, 2 anonymous edits File:Adapter(Class) pattern in LePUS3.png Source: http://en.wikipedia.org/w/index.php?title=File:Adapter(Class)_pattern_in_LePUS3.png License: GNU Free Documentation License Contributors: Edenphd File:w3sDesign Bridge Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Bridge_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Bridge UML class diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Bridge_UML_class_diagram.svg License: Public Domain Contributors: Trashtoy Image:Bridge pattern in LePUS3.1.gif Source: http://en.wikipedia.org/w/index.php?title=File:Bridge_pattern_in_LePUS3.1.gif License: Public Domain Contributors: Ian Atkin (User:Sugarfish) [correction of image originally created by Amnon Eden (User:Edenphd)] File:w3sDesign Composite Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Composite_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:w3sDesign Composite Design Pattern Type Safety UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Composite_Design_Pattern_Type_Safety_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Composite UML class diagram (fixed).svg Source: http://en.wikipedia.org/w/index.php?title=File:Composite_UML_class_diagram_(fixed).svg License: Public Domain Contributors: Composite_UML_class_diagram.svg: Trashtoy derivative work: « Aaron Rotenberg « Talk « Image:Composite pattern in LePUS3.png Source: http://en.wikipedia.org/w/index.php?title=File:Composite_pattern_in_LePUS3.png License: Public Domain Contributors: Amnon Eden (User:Edenphd) File:Decorator UML class diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Decorator_UML_class_diagram.svg License: Public Domain Contributors: Trashtoy Image:UML2 Decorator Pattern.png Source: http://en.wikipedia.org/w/index.php?title=File:UML2_Decorator_Pattern.png License: Creative Commons Attribution-Sharealike 3.0 Contributors: Nheirbaut (talk) File:w3sDesign Decorator Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Decorator_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe file:Facade Design Pattern Class Diagram UML.svg Source: http://en.wikipedia.org/w/index.php?title=File:Facade_Design_Pattern_Class_Diagram_UML.svg License: Creative Commons Attribution-Share Alike Contributors: FeRDNYC file:Facade Design Pattern Sequence Diagram UML.svg Source: http://en.wikipedia.org/w/index.php?title=File:Facade_Design_Pattern_Sequence_Diagram_UML.svg License: GNU Free Documentation License Contributors: FeRDNYC File:Example of Facade design pattern in UML.png Source: http://en.wikipedia.org/w/index.php?title=File:Example_of_Facade_design_pattern_in_UML.png License: GNU Free Documentation License Contributors: Fuhrmanator File:w3sDesign Flyweight Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Flyweight_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Front Controller.svg Source: http://en.wikipedia.org/w/index.php?title=File:Front_Controller.svg License: Creative Commons Attribution-Sharealike 3.0 Contributors: User:MovGP0 File:Module-software-design-pattern.png Source: http://en.wikipedia.org/w/index.php?title=File:Module-software-design-pattern.png License: Creative Commons Attribution-Sharealike 3.0 Contributors: User:Umlcat File:w3sDesign Proxy Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Proxy_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:proxy_pattern_diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Proxy_pattern_diagram.svg License: GNU Free Documentation License Contributors: Traced by User:Stannered, created by en:User:TravisHein File:Proxy pattern in LePUS3.gif Source: http://en.wikipedia.org/w/index.php?title=File:Proxy_pattern_in_LePUS3.gif License: Creative Commons Attribution-Sharealike 3.0 Contributors: Amnon Eden (talk) File:Többszörös öröklés (iker minta nélkül).png Source: http://en.wikipedia.org/w/index.php?title=File:Többszörös_öröklés_(iker_minta_nélkül).png License: unknown Contributors: User:PV Betti File:Iker minta.png Source: http://en.wikipedia.org/w/index.php?title=File:Iker_minta.png License: unknown Contributors: User:PV Betti File:Blackboad_pattern_system_structure.png Source: http://en.wikipedia.org/w/index.php?title=File:Blackboad_pattern_system_structure.png License: Public Domain Contributors: passz Image Sources, Licenses and Contributors 169

File:w3sDesign Chain of Responsibility Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Chain_of_Responsibility_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:w3sDesign Command Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Command_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Command pattern.svg Source: http://en.wikipedia.org/w/index.php?title=File:Command_pattern.svg License: unknown Contributors: User:Sae1962 File:w3sDesign Interpreter Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Interpreter_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Interpreter_UML_class_diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Interpreter_UML_class_diagram.svg License: unknown Contributors: User:Sae1962 File:w3sDesign Iterator Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Iterator_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Iterator UML class diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:Iterator_UML_class_diagram.svg License: Public Domain Contributors: Trashtoy File:w3sDesign Mediator Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Mediator_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Mediator design pattern.png Source: http://en.wikipedia.org/w/index.php?title=File:Mediator_design_pattern.png License: Public Domain Contributors: Kostyantyn Yuriyovich Kolesnichenko File:w3sDesign Memento Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Memento_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:w3sDesign Observer Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Observer_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Observer w update.svg Source: http://en.wikipedia.org/w/index.php?title=File:Observer_w_update.svg License: unknown Contributors: User:Gregorybleiker File:DesignPatternServantFigure1.png Source: http://en.wikipedia.org/w/index.php?title=File:DesignPatternServantFigure1.png License: Creative Commons Attribution-Sharealike 3.0 Contributors: Creator:VeselyBrumlaVeselyBrumla File:DesignPatternServantFigure2.png Source: http://en.wikipedia.org/w/index.php?title=File:DesignPatternServantFigure2.png License: Creative Commons Attribution-Sharealike 3.0 Contributors: Creator:VeselyBrumlaVeselyBrumla Image:Specification_UML_v2.png Source: http://en.wikipedia.org/w/index.php?title=File:Specification_UML_v2.png License: GNU Free Documentation License Contributors: IToshkov File:w3sDesign State Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_State_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:State Design Pattern UML Class Diagram.svg Source: http://en.wikipedia.org/w/index.php?title=File:State_Design_Pattern_UML_Class_Diagram.svg License: Creative Commons Attribution-Sharealike 3.0 Contributors: State_Design_Pattern_UML_Class_Diagram.png: JoaoTrindade (talk) Original uploader was JoaoTrindade at en.wikipedia derivative work: Ertwroc (talk) File:w3sDesign Strategy Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Strategy_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Strategy Pattern in UML.png Source: http://en.wikipedia.org/w/index.php?title=File:Strategy_Pattern_in_UML.png License: Public Domain Contributors: Jason S. McDonald Image:Strategy pattern in LePUS3.gif Source: http://en.wikipedia.org/w/index.php?title=File:Strategy_pattern_in_LePUS3.gif License: Creative Commons Attribution-Sharealike 3.0 Contributors: Amnon Eden (User:Edenphd) Image:StrategyPattern IBrakeBehavior.svg Source: http://en.wikipedia.org/w/index.php?title=File:StrategyPattern_IBrakeBehavior.svg License: Creative Commons Zero Contributors: Cathy Richards, Ptoonen~commonswiki, Sae1962, 2 anonymous edits File:w3sDesign Template Method Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Template_Method_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe Image:Template Method pattern in LePUS3.gif Source: http://en.wikipedia.org/w/index.php?title=File:Template_Method_pattern_in_LePUS3.gif License: Public Domain Contributors: Amnon Eden (User:Edenphd) File:w3sDesign Visitor Design Pattern UML.jpg Source: http://en.wikipedia.org/w/index.php?title=File:W3sDesign_Visitor_Design_Pattern_UML.jpg License: unknown Contributors: User:Vanderjoe File:Visitor design pattern.svg Source: http://en.wikipedia.org/w/index.php?title=File:Visitor_design_pattern.svg License: Creative Commons Attribution 3.0 Contributors: Sae1962, ShakespeareFan00 File:Visitor pattern class diagram in LePUS3.gif Source: http://en.wikipedia.org/w/index.php?title=File:Visitor_pattern_class_diagram_in_LePUS3.gif License: Creative Commons Attribution-Share Alike Contributors: Iliya.Velkov File:UML diagram of an example of the Visitor design pattern.png Source: http://en.wikipedia.org/w/index.php?title=File:UML_diagram_of_an_example_of_the_Visitor_design_pattern.png License: GNU Free Documentation License Contributors: Fuhrmanator File:Traditional Layers Pattern.png Source: http://en.wikipedia.org/w/index.php?title=File:Traditional_Layers_Pattern.png License: unknown Contributors: User:Klodr File:DIPLayersPattern.png Source: http://en.wikipedia.org/w/index.php?title=File:DIPLayersPattern.png License: unknown Contributors: User:Klodr File:Dependency inversion.png Source: http://en.wikipedia.org/w/index.php?title=File:Dependency_inversion.png License: unknown Contributors: User:Mrflay File:DIPLayersPattern v2.png Source: http://en.wikipedia.org/w/index.php?title=File:DIPLayersPattern_v2.png License: unknown Contributors: User:Klodr File:DIP concrete example.png Source: http://en.wikipedia.org/w/index.php?title=File:DIP_concrete_example.png License: unknown Contributors: User:Klodr License 170 License

Creative Commons Attribution-ShareAlike 3.0 Unported - Deed

This is a human-readable summary of the Creative Commons Attribution ShareAlike 3.0 Unported License (http:/ / en. wikipedia. org/ wiki/ Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3. 0_Unported_License) You are free: • to Share—to copy, distribute and transmit the work, and • to Remix—to adapt the work Under the following conditions: • Attribution—You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work.) • Share Alike—If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. With the understanding that: • Waiver—Any of the above conditions can be waived if you get permission from the copyright holder. • Other Rights—In no way are any of the following rights affected by the license: • your fair dealing or fair use rights; • the author's moral rights; and • rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights.

• Notice—For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do that is with a link to https:/ / creativecommons. org/ licenses/ by-sa/ 3. 0/

GNU Free Documentation License

As of July 15, 2009 Wikipedia has moved to a dual-licensing system that supersedes the previous GFDL only licensing. In short, this means that text licensed under the GFDL can no longer be imported to Wikipedia. Additionally, text contributed after that date can not be exported under the GFDL license. See Wikipedia:Licensing update for further information.

Version 1.3, 3 November 2008 Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The "publisher" means any person or entity that distributes copies of the Document to the public. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements". 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. License 171

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new

problems or concerns. See http:/ / www. gnu. org/ copyleft/ . Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING "Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (c) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.