text:
Iterator pattern

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a 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 23 well-known "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 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 iterators 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.".

UML class and sequence diagram
In the above UML class diagram, the  class refers (1) to the   interface for creating an   object  and (2) to the   interface for traversing an   object. The  class implements the   interface by accessing the   class.

The UML sequence diagram shows the run-time interactions: The  object calls   on an   object, which creates an   object and returns it to the. The  uses then   to traverse the elements of the   object.

Example
Some languages standardize syntax. C++ and Python are notable examples.

C++
C++ implements iterators with the semantics of 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, increment, and decrement. This has the advantage that C++ algorithms such as  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.

This C++11 implementation is based on chapter "Generalizing vector yet again".

The program output is

title: Iterator pattern


text:
Interpreter pattern

In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client. See also Composite pattern.

Overview
The Interpreter 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 Interpreter design pattern solve?
Source:

 * A grammar 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 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  class hierarchy and implementing an   operation.
 * Represent a sentence in the language by an abstract syntax tree (AST) made up of  instances.
 * Interpret a sentence by calling  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.

UML class and object diagram

In the above UML class diagram, the  class refers to the common   interface for interpreting an expression . The  class has no children and interprets an expression directly. The  class maintains a container of child expressions and forwards interpret requests to these.

The object collaboration diagram shows the run-time interactions: The  object sends an interpret request to the abstract syntax tree. The request is forwarded to (performed on) all objects downwards the tree structure. The  objects  forward the request to their child expressions. The  objects  perform the interpretation directly.

Example
This C++11 implementation is based on the pre C++98 sample code in the book.

The program output is:

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Interpreter pattern


text:
Talk:Flyweight pattern

Bug in Java example?
Note: I just fixed the bug described below. —Preceding unsigned comment added by 74.68.108.87 (talk) 21:59, 8 April 2010 (UTC)

I believe there's an intermittent bug in the Java example. Here's the part I'm concerned about, in the create method:

Here's the problem: Suppose you call the create method with a certain set of parameters, for the first time. The method constructs a new FontData object (call it d0), and the local variable data refers to it. So, d0 is added to FLY_WEIGHT_DATA, and the method returns d0. No problem so far.

Now imagine that the return value of create is discarded, i.e., there are no more references to d0 except for the weak references in FLY_WEIGHT_DATA. Suppose that the garbage collector has not yet run, and that you call create again, with the same parameters that gave you the original d0. The lines quoted above construct a new FontData object that equals d0, but it's not identical to d0. FLY_WEIGHT_DATA.containsKey(data) returns true because data.equals(d0) is true. Now suppose that the garbage collector kicks in after this check, but before the return statement. Now FLY_WEIGHT_DATA.get(data) will return null because the key d0 has disappeared, and so FLY_WEIGHT_DATA.get(data).get will fail with a NullPointerException.

Another kind of failure occurs if the garbage collecture runs after get(data) but before get. In that case, get(data) will return the desired weak reference, but then get will return null, presumably leading to a NullPointerException somewhere down the road.

By the way, the documentation of WeakHashMap warns of exactly this kind of problem (see the paragraph on checking for equality with ==, as well as the paragraph after that). —Preceding unsigned comment added by 74.68.108.87 (talk) 15:58, 4 March 2010 (UTC)

comment
Flyweight is a software design pattern.

The sentence above is how the articles title "builder pattern", "adapter pattern", etc. should begin. Someone who is ignorant of computer software looking at those articles should be told right at the beginning that that is what the article is about. -- Mike Hardy

Chnged the method printAtPosition to a static one as the point of a flyweight object was to save memory. -- Jari Mustonen

each GraphicChar takes 10 bytes of heap space (8 overhead + 2 char + 4 string pointer for font) 8 + 2 + 4 = 14, not 10 --195.6.224.137 15:17, 18 October 2006 (UTC)

I'm removing the two paragraphs that start "Often the desire to use a flyweight pattern indicates another design problem" because they seem way off-topic, they contain errors (see comment above regarding addition error), and they sound a lot like original research. CMosher01 17:16, 24 October 2006 (UTC)

As the author said that this is structural pattern, According to me its not structural or object oriented pattern, it's a hybrid pattern which consist both kind of pattern.--- Sanket Patel

Thread safety issue
The article should outline the importance of being thread-safe when the Flyweight is static. The Java example should also be thread-safe, some one who doesnt know this pattern may fall in this trap. —Preceding unsigned comment added by 81.252.131.1 (talk) 09:11, 15 April 2009 (UTC)

Memory issue in the Java example
The Java example adds WeakReferences into the flyweightData map but at no point removes them. This could in time lead to a very large map, whose values would mostly end up being null-valued WeakReferences.

Actually it doesn't because the map used is a WeakHashMap and the keys are the same as the referenced value. This approach works nicely when object creation cost is low and the object itself can be used as the key.

When object creation is high and needs to be avoided as well as keeping memory usage down some sort of other key needs to be used. If the object's hashCode can be replicated with the same parameters given in the constructor then the hashCode is a good choice. But now you definitely have the problem of the map potentially growing large with null-valued WeakReferences. The solution is to attach a ReferenceQueue that removes the entry from the map.

org.apache.commons.collections.map.ReferenceMap provides a basic solution for this, but there exists a superior solution, also open sourced, here http://sesat.no/projects/sesat-commons/commons-reference-map/

> This implementation improves over org.apache.commons.collections.map.ReferenceMap > in that the synchronisation and concurrency is determined through delegation to the > map supplied in the constructor as described above.

Michaelsembwever (talk) 21:48, 20 March 2008 (UTC)

VB.Net example: Is this a flyweight?
I removed this section from the article:

VB.NET
To me it doesn't look like a Flyweight. It may be a pattern to save memory, but to me it doesn't look anything like the Flyweight pattern. Am I wrong? --Teglsbo (talk) 12:50, 21 April 2008 (UTC)

That is the use of a proxy pattern. The Flyweight pattern is there to prevent needing a cartesian product number of classes, not to prevent accessing a huge class. Loek Bergman (talk) 10:56, 27 June 2009 (UTC)

Illustration
The illustration seems to illustrate an object pool, not a flyweight setup. While object pools can be handy when dealing with flyeights, it isn't directly relevant to the design pattern. The illustration outright fails at communicating the concept correctly.--Henke37 (talk) 19:07, 8 July 2012 (UTC)

 * While we're on the subject, i would say that every code example on the page indicates to me that their authors did not understand this pattern. They do not illustrate the pattern as described at all. I am inclined to remove them. --Rob* (talk) 08:17, 14 November 2015 (UTC)

Python __slots__ example
The construct '__slots__' in Python does not, as the article states, 'automatically enable the Flyweight pattern for that class.' It simply removes the backing dictionary ('__dict__') in favor of a tuple. As the definition of Flyweight states at the beginning of the article, the requirement for this pattern is 'sharing as much data as possible with other similar objects.' Two slotted Python classes initialized to the same value will be different objects. 'arr=[foo(1) for i in range(1000)]' will contain 1000 different objects, not 1000 references to the same object. NO PYTHON OBJECT IS IMMUTABLE. For this reason, I don't believe this Python example is valid and should be removed. — Preceding unsigned comment added by 207.10.138.156 (talk) 22:38, 24 November 2013 (UTC)

A valid Python example would be getting the immutable attributes from a singleton, via __getattr__, and denying its override via __setattr__. But would be simpler to use class-level attributes. This ones resides on the class space and are not copied over instances. However this ones could be overwriten if not denied via __setattr__ — Preceding unsigned comment added by Alanjds (talk • contribs) 14:49, 31 January 2017 (UTC)

Java example is a joke
Can somebody please fix this? The complexity, BMW advertising and lack of clarity (say Vs C# original Coffee example) is astounding. The original Coffee example, pre BMW, whilst a lot shorter and simpler is also flawed, using ConcurrentHashMap but then also using synchronize everywhere. It's like nobody has read Concurrency In Practice/even bothered learning that those 2 APIs are intended to be (mostly) mutually exclusive replacements for each other. — Preceding unsigned comment added by 2A02:C7D:31E1:4600:41DD:FF41:6751:5860 (talk) 09:46, 14 October 2018 (UTC)

C# example is confusing
What's up with class ReducedMemoryFootprint in the C# example? It appears it does the same thing as MinimumMemoryFootprint only worse, and is harder to read and understand. The class names are confusing, as you'd expect MinimumMemoryFootprint to use less memory than ReducedMemoryFootprint, but it doesn't. There's no text to explain the code; not even comments. The private method AddFlavourToCache(object state) takes an object instead of a CoffeeFlavour for no discernible reason. I think the example should be removed, leaving just the "Simple Implementation" example. Am I missing something?

-

I agree strongly. Adding cache locks for concurrency seems particularly confusing for anyone who just wants to see what the pattern looks like in action. If nobody objects, I'll remove the large example soon. Telemachus12389 (talk) 11:30, 9 June 2021 (UTC)

Implementation details section is unsourced, complex, and basically unreadable
I've made some minor edits to remove language in this section that sounds like it came from a tutorial (lots of 'you should do this in your application...'). But in general I'm unsure most of the detail here is really relevant - can someone with deep knowledge on the topic highlight any sections that it would be fine to remove in the sake of concision and clarity?

This also seems to be common on other design pattern pages, but I'm not sure what's gained by having examples from nine different languages - especially when some of them, like Java and C#, are so similar. The examples take up over three-quarters of the page, making it feel more like a reference manual than an encyclopedia page. Can any examples by removed? Telemachus12389 (talk) 11:28, 9 June 2021 (UTC)

Large changes, feel free to revert if felt necessary
I've gone ahead and cut out big swathes of the implementation details section and several of the code examples. The page still doesn't have enough citations for the implementation details section, but hopefully it now reads more like an encyclopedia page and less like a design manual. Deciding which language examples to cut out was ultimately arbitrary, of course, but I decided to remove some of the slightly less popular languages (Scala, Crystal) and the Java example, since the language is similar to C#.

I'm aware these are big changes, so feel free to revert the edits. But if you do, I would appreciate hearing why you think the material was worth bringing back, as it would help contextualise its place in the article and improve the piece overall.

Telemachus12389 (talk) 11:31, 12 June 2021 (UTC)

PHP example - cache implementation using WeakReference
I think the way how WeakReference object is used in CoffeeFlavour::intern function does not make sense. The WeakReference object should be stored in the cache. In the example classical reference (not weak reference) is stored in the cache which means it will be preserved in the cache all the time. The function should also deal with situation when weak reference has already been forgotten and should refresh it in that case. For that reason, I think the function should return the object itself rather than WeakReference.

Here is an example fix of the function.

Secondly, we should also remove ->get from Order::of function, because ::intern function already returns the object itself now.

See also this example of WeakReference usage (example no. 2) which is similar to my fix.

Mk90461 (talk) 14:02, 20 July 2021 (UTC)

Python example - wrong and off topic?
The Python example seems to be based on an incorrect understanding of the pattern. It's simply inserting and retrieving from a shared dictionary, but a shared dictionary by itself is not a flyweight pattern. Besides it seems to be largely original research and contains a large off-topic discussion of immutability in Python's data model. I'm WP:BOLDLY removing the section as the other examples illustrate the concept better. 2A02:A44A:5C96:1:D66A:D92F:5729:7268 (talk) 12:14, 30 April 2023 (UTC)

title: Talk:Flyweight pattern


text:
Mediator pattern

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

In object-oriented programming, programs often consist of many classes. Business logic and computation are distributed among these classes. However, as more classes are added to a program, especially during maintenance 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.

Overview
The mediator design pattern is one of the twenty-three well-known 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.

===Problems that the mediator design pattern can 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.

Solutions described by the mediator design pattern

 * Define a separate (mediator) object that encapsulates the interaction between a set of objects.
 * 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.

UML class and sequence diagram

In the above UML class diagram, the  and   classes do not refer to (and update) each other directly. Instead, they refer to the common  interface for controlling and coordinating interaction, which makes them independent from one another with respect to how the interaction is carried out. The  class implements the interaction between   and.

The UML sequence diagram shows the run-time interactions. In this example, a  object mediates (controls and coordinates) the interaction between  and   objects.

Assuming that  wants to interact with   (to update/synchronize its state, for example),   calls   on the   object, which gets the changed data from   and performs an   on.

Thereafter, calls  on the   object, which gets the changed data from   and performs an   on.

Class diagram

Mediator - defines the interface for communication between Colleague objects
 * Participants

ConcreteMediator - 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 Mediator

ConcreteColleague - implements the Colleague interface and communicates with other Colleagues through its Mediator

C#
The mediator pattern ensures that components are loosely 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.

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 remoting. Using raw sockets would not allow for the delegate callbacks (people subscribed to the Mediator class’ MessageReceived event).

Java
In the following example, a  object controls the values of several   objects, forcing the user code to access 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 ) that controls the list of the observers (implemented using the observer pattern).

title: Mediator pattern


text:
Observer pattern

In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It is often used for implementing distributed event-handling systems in event-driven software. In such systems, the subject is usually named a "stream of events" or "stream source of events" while the observers are called "sinks of events." The stream nomenclature alludes to a physical setup in which the observers are physically separated and have no control over the emitted events from the subject/stream source. This pattern thus suits any process by which data arrives from some input that is not available to the CPU at startup, but instead may arrive at arbitrary or indeterminate times (HTTP requests, GPIO data, user input from peripherals and distributed databases, etc.).

Overview
The observer design pattern is a behavioural pattern listed among the 23 well-known "Gang of Four" design patterns that address recurring design challenges in order to design flexible and reusable object-oriented software, yielding objects that are easier to implement, change, test and reuse.

The observer pattern addresses the following problems:
 * A one-to-many dependency between objects should be defined without making the objects tightly coupled.
 * When one object changes state, an open-ended number of dependent objects should be updated automatically.
 * An object can notify multiple 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. However, it might be applicable from a performance point of view or if the object implementation is tightly coupled (such as low-level kernel structures that execute thousands of times per second). Tightly coupled objects can be difficult to implement in some scenarios and are not easily reused because they refer to and are aware of many objects with different interfaces. In other scenarios, tightly coupled objects can be a better option because the compiler is able to detect errors at compile time and optimize the code at the CPU instruction level.

 * Define  and   objects.
 * 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  operation. The responsibility of observers is to register and unregister themselves with a subject (in order to be notified of state changes) and to update their state (to synchronize their state with the 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.

Strong vs. weak reference
The observer pattern can cause memory leaks, known as the lapsed listener problem, because in a 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 if the subject holds weak references to the observers.

Coupling and typical publish-subscribe implementations
Typically, the observer pattern is implemented so that the 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, forcing both the observers and the subject to be aware of each other and have access to their internal parts, creating possible issues of scalability, 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 (non-polling) implementations of the publish-subscribe pattern, this is solved by creating a dedicated message queue 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 and knowing (or not knowing, in some cases) about only the expected message, while knowing nothing about the message sender itself; the sender may also 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.

In early implementations of multi-window operating systems such as OS/2 and Windows, the terms "publish-subscribe pattern" and "event-driven software development" were used as synonyms for the observer pattern.

The observer pattern, as described in the Design Patterns book, is a very basic concept and does not address removing interest in changes to the observed subject or special logic to be performed by the observed subject before or after notifying the observers. The pattern also does not deal with recording change notifications or guaranteeing that they are received. These concerns are typically handled in message-queueing systems, in which the observer pattern plays only a small part.

Related patterns include publish–subscribe, mediator and singleton.

Uncoupled
The observer pattern may be used in the absence of publish-subscribe, as when model status is frequently updated. Frequent updates may cause the view to become unresponsive (e.g., by invoking many repaint calls); such observers should instead use a timer. Instead of becoming 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 bars, in which the underlying operation's progress changes frequently.

UML class and sequence diagram

In this UML class diagram, the  class does not update the state of dependent objects directly. Instead,  refers to the   interface  for updating state, which makes the   independent of how the state of dependent objects is updated. The  and   classes implement the   interface by synchronizing their state with subject's state.

The UML sequence diagram shows the runtime interactions: The  and   objects call   on   to register themselves. Assuming that the state of  changes,   calls   on itself. calls  on the registered   and  objects, which request the changed data  from   to update (synchronize) their state.

Example
While the library classes and  exist, they have been deprecated in Java 9 because the model implemented was quite limited.

Below is an example written in Java that takes keyboard input and handles each input line as an event. When a string is supplied from, the method   is then called in order to notify all observers of the event's occurrence, in the form of an invocation of their update methods.

C++
This is a C++11 implementation. The program output is like

Delphi
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:

JavaScript
JavaScript has a deprecated Object.observe function that was a more accurate implementation of the observer pattern. This would fire events upon change to the observed object. Without the deprecated Object.observe function, the pattern may be implemented with more explicit code:

title: Observer pattern


text:
State pattern

The state pattern is a behavioral 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, 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.

Overview
The state design pattern is one of twenty-three design 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 the class, 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
In the accompanying Unified Modeling Language (UML) class diagram, the  class doesn't implement state-specific behavior directly. Instead,  refers to the   interface for performing state-specific behavior, which makes   independent of how state-specific behavior is implemented. The  and   classes implement the   interface, that is, implement (encapsulate) the state-specific behavior for each state. The UML sequence diagram shows the run-time interactions:

The  object delegates state-specific behavior to different   objects. First,  calls   on its current (initial) state object, which performs the operation and calls   on   to change context's current state to. The next time,  again calls   on its current state object, which performs the operation and changes context's current state to.

title: State pattern


text:
Strategy pattern

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a family of algorithms to use.

Strategy lets the algorithm vary independently from clients that use it. 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 runtime 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 code duplication.

Typically, the strategy pattern stores a reference to 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.

UML class and sequence diagram
In the above UML class diagram, the  class does not implement an algorithm directly. Instead,  refers to the   interface for performing an algorithm, which makes   independent of how an algorithm is implemented. The  and   classes implement the   interface, that is, implement (encapsulate) an algorithm. The UML sequence diagram shows the runtime interactions: The  object delegates an algorithm to different   objects. First,  calls   on a   object, which performs the algorithm and returns the result to. Thereafter,  changes its strategy and calls   on a   object, which performs the algorithm and returns the result to.

Class diagram

Strategy and open/closed principle
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 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, 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 runtime as well as at design-time. For instance, a car object's brake behavior can be changed from  to   by changing the   member to:

title: Strategy pattern


text:
Template method pattern

In object-oriented programming, the template method is one of the behavioral design 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 methods, in which case subclasses are required to provide concrete implementations, or hook methods, which have empty bodies in the superclass. Subclasses can (but are not required to) customize the operation by overriding 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.

Overview
This 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.

UML class diagram

In the above UML class diagram, the  defines a   operation that defines the skeleton (template) of a behavior by
 * implementing the invariant parts of the behavior and
 * sending to self the messages   and  , which, because they are implemented in   , allow that subclass to provide a variant implementation of those parts of the algorithm.

Usage
The 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 overriding of the hook 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.

C++ example
This C++14 implementation is based on the pre C++98 implementation in the book.

The program output is

title: Template method pattern


text:
Talk:Lilo & Stitch

Copyright
I really, really, really think this is copyrighted material. -- Zoe

Thinly reworded of.

I added that link as an external reference. With that, plus the rewording, I suspect we're ok. However, I'll try checking with the copyright owners to see if they want to raise an objection. Martin

I edited the page to remove the "Dean DuBlois said that ..." stuff -- it would be nice to have attributed quotes, but since the stuff they said is fairly generic and not direct quotes, I don't see a need to attribute it. I also removed some things which to me sounded questionable or didn't make much sense. I believe the article now is not just a copy of the copyrighted page linked above. Brian Kendig 05:07, 12 Apr 2004 (UTC)

Some of the items listed as evidence of a Phantom Menace influence (like a Galactic Federation and hyperspace) long predate 1999 (and 1977 for that matter). George Lucas didn't invent science fiction. MK 06:21, 3 Sep 2004 (UTC)

Yes, I fully agree. On the other hand Wikipedia does not have enough good articles on science fiction to make links to support these things and dropping names like Damon Knight, Poul Anderson and Harry Harrison is not enough. I was planning to start to "balance" that section by adding another one on parallels with Star Trek and then graduate to more classic written things, but it fell by the wayside. What were you thinking of doing? AlainV 22:43, 3 Sep 2004 (UTC)

 * Ummm, writing that last note? Seriously, while I know enough science fiction history to recognize some errors in the article, I don't know enough to post the correct facts. I'd be more likely to just substitute my errors for the existing ones. I figured I'd call attention to the problem and hope someone better informed on the subject would come along and make the revisions. MK 03:56, 4 Sep 2004 (UTC)

Parodies and references
Someone deleted the entire "Parodies and references" section without comment, which is being a bit overly bold. However, that section did have a lot of questionable info - notably the supposed Star Wars/Star Trek connections, which as as mentioned above involve elements that were well established in science fiction before Lucas and Roddenberry used them, or that are common dramatic conceits. I've deleted those sections and added the Miyazaki reference (admitted by Dean DeBlois). Ergative rlt 21:17, 12 April 2006 (UTC)

1985
Could someone fill in info about the whole '1985' thing? There's the "1985 concept sketch" of Stitch, but not a single shred of information on how it came to take 17 years to produce. Did it sit in an idea vault? Were there any scrapped official tries? Anything? I'd love to know =) --76.213.168.86 07:58, 26 January 2007 (UTC)

Live Action Movie?
I read something in this article about a live action version that even named actors, but it had no referances. As far as I know, this isn't going to happen. If it is, a referance is greatly appreciated. Until then, I think it better that the unsourced information be removed sooner than later, so that in the likely chance it's wrong, people won't be misinformed. Ovni 18:25, 31 May 2007 (UTC)

Parodies, References & Trivia
I moved this section further down the page because it was disrupting the flow of the article. It is also way too long, and Wikipedia clearly states that trivia sections are discouraged. If someone has time, I suggest reading Wikipedia's suggestions on how to trim down this section, or even remove it entirely. —Preceding unsigned comment added by Fluffyblue (talk • contribs) 04:40, 16 April 2008 (UTC)

 * While I agree that the trivia section needs to be trimmed, I don't agree with removing it. At the very least the 4 trailers that parodies previous Disney films should be kept.   3:14, 25 June 2008 ( ~ )(UTC)

 * If I have time, I'll start taking the noteworthy trivia and integrating it into other parts of the article. 青い(Aoi) (talk) 00:27, 30 June 2008 (UTC)

Box office
Perhaps a section on movie's profitability? http://www.imdb.com/title/tt0275847/business —Preceding unsigned comment added by Petzl (talk • contribs) 23:03, 29 June 2008 (UTC)

Herbie
The Parodies and References section stated this:

 * In a scene when Stitch attacks Jumba with a car, the car is actually Herbie from the The Love Bug.

The car Stitch throws to Jumba is blue (Stitch actually says so), and everyone knows Herbie is yellow. I deleted it therefore. --Midasminus (talk) 14:13, 27 August 2008 (UTC)

 * ..."everyone" except those of us who know Herbie is white. Have you seen any of the movies? PacificBoy  08:07, 8 March 2010 (UTC)

41st or 42nd?
The introductory paragraph says it's both. —Preceding unsigned comment added by 81.100.53.107 (talk) 21:29, 9 December 2008 (UTC)
 * Originally, it was the 41st. But, for some unknown reason, Disney decided Dinosaur should be in its canon, and all the films after it but before Chicken Little were pushed up by one. Georgia guy (talk) 23:56, 10 November 2011 (UTC)

introduction paragraph
"which ultimately went to another Daviegh Chase film Spirited Away." that sounds like he made or directed spirited away but i'm sure he was just in charge for the US adaption because japanese animation studio ghibli made the film. maybe someone can change that. —Preceding unsigned comment added by 92.228.74.102 (talk) 23:52, 8 February 2009 (UTC)

 * Daveigh Chase is the little girl who was the voice of Lilo. PacificBoy  08:08, 8 March 2010 (UTC)

Info That Should Be Relocated or Removed

 * The song Disney used to advertise the film was Suspicious Minds, performed by Gareth Gates, who became famous on the UK TV program Pop Idol. Interesting information, but specific information like this probably should be removed from article's introduction. It's already mentioned under the advertising section, so removal from introduction is not too significant.

 * Coincidentally, Stitch can be said to vaguely resemble the spined aliens of the Critters series, which took place in Kansas, and also had a hunter dispatched to stop them. Speculative and probably not worth mentioning unless someone can provide a source that shows that this fact somehow influenced Stitch's character design.

Trivia
''I've removed the entire trivia section here. Trivia sections are discouraged by Wikipedia guidelines, see WP:TRIVIA.

 * Social worker Cobra Bubbles, formerly of the CIA, is modeled on the mysterious "Men in Black" (of urban legends and several hit movies) who work to prevent an alien takeover of Earth and to persuade humans that aliens do not exist.

 * The end of the movie features snapshots of the future "family" life of Stitch with Lilo and the others, each of them variations of classic images like famous Norman Rockwell illustrations.

 * Chris Sanders, one of the directors of the film, also served as co-screenwriter, co-character designer, and provided the voice of Stitch, a character he actually first created in 1985.

 * Earth is referred as being in Quadrant 17, Section 005, Area "51" in the Galactic charts, one of several references to Area 51.

 * During the introduction of Stitch to Lilo's room, he finds a book of "road maps of Iowa" which pokes fun at the idea that Iowa has enough road maps to fill a large book but when he pulls a page from it, it shows a global map with two islands and a large body of water.

 * The alien text that the Galactic Federation uses is known as "Tantalog" text and was designed for the film. The text can be downloaded and used in word processing programs.

 * When Lilo and Stitch walk past the store selling calendars with images from around the world, the "Orlando" calendar has a picture of the Magic Kingdom.

 * There are several "hidden Mickeys" in the film: one is visible on Jumba's platform in the Grand Council scene, another is a clothing logo on one of Lilo's photo subjects on her bedroom wall, and another is one of the gauges on the control panel of Gantu's ship.

 * Near the beginning of the film, during the trial, Stitch is asked by the Grand Councilwoman to provide some sign that he understands what's going on. He responds by licking the inside of his glass cage. The saliva trail is in the famous "D" shape in the Walt Disney logo.

 * After the trial as Jumba is taken into prison, you can hear the sound of a Probe Droid from The Empire Strikes Back.

 * The sign on Lilo's door is the Hawaiian word "kapu" that loosely translates as "keep out" and is also the Hawaiian version of the Tahitian word "Tabu"; more commonly known as "taboo."

 * All of the license plates in the film (VW, Nani's car, the gas tanker, the fire engine, and Cobra Bubbles' car) are A113, the same as the number on Mrs. Davis's license plate in Toy Story and Mater's plate number in Cars; it's also used in many other Disney and Pixar films. It refers to a room number at California Institute of the Arts where many of the animators at those two companies received their education.

 * The A113 license can also be seen during Stitch's reign of terror on his model of San Francisco.

 * When Stitch is attacking the city of San Francisco he made out of blocks, he parodies Godzilla.

 * The two hover car presents given to Lilo and Stitch make the same sounds as the flying cars in "The Jetsons".

 * According to Stitch's dog license at the shelter, the adoption official is "Susan Hegarty", the name of the actress who voiced the character. Also per the license, Lilo and Nani's last name is "Pelekai".

 * The words on Stitch's dog license at the shelter are part of a resolution thanking people for their support during the making of the film. The words are difficult to make out, but the last part reads, "as well as our partners at Disney MGM Studios for their participation and support during the making of Lilo and Stitch." The viewer can see a close-up of them during the last few lines in the scene where "Susan" stamps the Seal of the State of Hawaii on the cetificate of adoption.

 * In one scene, a pink jeep car can briefly be seen in the lower-left corner of the screen. This is a reference to the Elvis movie Blue Hawaii, in which he drove such a car.

 * Near the end, the tracking screen Captain Gantu uses to locate Stitch on Hawaii shows the icon for the Disney theme park in Florida, Epcot - Spaceship Earth.

 * Running gag: Every time Pleakley looks at or tries to show someone information about Earth, the device used is a "ViewMaster". ViewMasters create the illusion that the viewer is looking at a three-dimensional image, but it's actually created by each eye looking at slightly different pictures. The basic premise is that the person looking in it has two eyes to create the effect, but Pleakley is a one-eyed creature and therefore wouldn't see the 3-D effect. Adding to the gag is when he hands the ViewMaster to Dr. Jumba, a one-eyed alien handing a four-eyed alien a viewing device intended for two-eyed humans.

 * The grocery store where Nani tries to get a job is owned by a "Mrs. Hasegawa", a reference to the famous "Hasegawa's General Store" in the town of Hana on Maui.

 * After Stitch breaks the water gun apart, Cobra is shown looking disappointed, as a crowd of people run by in terror. The last two people to run by are cartoon versions of Chris Sanders and Dean DeBlois- Chris is the one with blond hair and sunglasses, Dean is the big man with a beard.

 * In the subtitles for the Chinese version, a line spoken by Stitch in his alien language is translated into Chinese despite it having no corresponding English meaning. The reason for this is thought to be because Stitch's line sounded a lot like Ni Qu De (Go to your place), an offensive Chinese phrase used to tell somebody to go away. The actual Chinese translation was a lot more family-friendly. This line is placed at an earlier point than the first understandable dialog spoken by Stitch in the English version of the film.

 * The voice of Stitch was a difficult one to dub for other languages and that's why Dutch voice artist Bob van der Houven does the voice of Stitch in the Dutch, German, Flemish and Italian versions of the film.

 * When Jumba is ripping up the newspaper, some of the pictures look like past experiments: one next to the bed resembles Sprout (509), another Woops (600) and one looks like a white Loch Ness Monster.
 * After the scene where Lilo's house explodes and Stitch flies out of it, he comes out of the rubble with his spines and extra two arms protruding, but when Nani's legs rushes past him, his spines disappear and he has two arms instead of four. This could be because he quickly retracted them before she could see, and exploit him.

 * At the beginning of the film, the Grand Councilwoman seems not to know the Planet Earth (since she doesn't recognise it and doesn't know it's almost completely covered in water). However, in the end of the film, she claims she has already been on Earth in the Roswell incident, and she has met Cobra Bubbles.

 * The truck that Stitch steals to save Lilo from Gantu resembles the vehicle mode of the Transformers: Armada character Optimus Prime.

 * When Stitch throws Nani's VW Beetle at Jumba the horn goes on and it sounds like Herbie's horn as seen in The Love Bug.

 * In the scene just after Lilo has bought Stitch, Stitch is watching a part from the film Earth vs. The Spider (1958), shown on the televisions in an electronics shop. Deltasim (talk) 21:51, 11 December 2009 (UTC)

Comparisons to Classic Disney
''I have removed this section from the article. Once again, there is a lot of interesting information in here, but much of it is speculative, not NPOV, or unverified. If citations can be provided, it would be an interesting addition to the article.

 * The Fox and the Hound, the beauty of nature and realities of life are present in both films, and both films don't really have a true villain. Case in point: Gantu was just doing his job, Amos Slade was just hunting for a fox. With Stitch leaving, you think, "Have a Seen This Before?" Answer: Yes, you have. It brings back true Disney because remember: Goodbye Seem Forever, Farwell is Like the End, But in my Heart's a Memory, and There You'll Always Be! (cry is now being heard all around the world)

 * Dumbo and The Ugly Duckling: As meantoned before, Stitch walking down the path with the ugly ducking book is from Disney's version of the famous wonderful Hans Christian Anderson story. This tone, along with the storyline of Stitch being an ugly ducking, equal great comparison. Also, items in the background of both Lilo and Nani's rooms reference other Disney films. Lilo has a stuffed Dumbo doll on her art easel, while Nani has a movie poster for Mulan on her wall. Additionally, a restaurant called "Mulan Wok" is visible during the scene where Stitch sees "Earth vs. the Spider" in a shop-window television. The directors had worked on Mulan.

The character of Lilo is obviously inspired by Dumbo. She is cute, like Dumbo, and is shunned upon because of her difference. When Lilo shows her doll to the other kids, this is similar how they react in fear to how the other elephants reacted in fear to Dumbo, and gasped as they heard about Dumbo's mother being locked up. Seeing Lilo be alone is just like Dumbo and Tod, and the Fox and the Hound may be one of the very most underrated films of ALL time.

 * Lady and the Tramp: When Stitch awakes at the dog pound, there are a number of dogs shaking in fear in the corner of his cell. They're the same dog breeds that Lady encounters in her trip to the dog pound in Lady and the Tramp (1955). Here, they don't know that Stitch is an alien, but they know he's not a dog. It could also be a reference to John Carpenter's "The Thing".

Once again, classic value is shown.

 * Not Disney, but still notable: Famous Japanese animator Hayao Miyazaki's film Kiki's Delivery Service is given a nod by the appearance of "Kiki's Coffee House". Another reference to Miyazaki's work is the scene following Stitch's crash-landing on Earth, reminiscent of the bus stop scene from My Neighbor Totoro.

When Nani pleeds that Lilo can stay with her, and Stitch watches silently, and hands Lilo her photo back, this is reminiscent of in Tototo, Satsuki is crying thinking their mom is dying, or already dead, Mei watches silently, and heads on to bring the corn to their mom.

 * Bambi: As previously meantined, silent scenes, and also childood innocence, life joy, danger, heart, comedy, ect.

Lilo & Stitch is an excellent Disney film, just like all of these mentioned films, and like The Fox and the Hound, is definitely underrated.

Spelling correction from "repectively" to "respectively" in paragraph 4, "Prodution" to "Production"

Done Celestra (talk) 13:50, 30 April 2009 (UTC)

Hang on are you calling Lilo & Stitch, Bambi, The Fox and the Hound, Lady and the Tramp, Dumbo

Lilo & Sdtitch 86% Bambi           91% The fox & the hound 69% Lady & the tramp 89% Dumbo 97%

What fool has or will underestimate that.

Preceding unsigned comment added by 92.236.79.4 (talk) 13:14, 18 January 2013 (UTC) — Preceding unsigned comment added by 77.98.167.114 (talk)

Lilo & Stitch 3
Lilo & Stitch 3 is an upcoming computer-animated feature film presented by 20th Century Fox Feature Animation.

 * I would really love to see your source. BOVINEBOY 2008 21:30, 10 March 2011 (UTC)

Who or what does “andie butlet” in the infobox refer to?
I’ve just fixed two minor errors in the infobox (a tag that hadn’t been closed properly, and correcting the name of David Ogden Stiers in the cast list; before it listed Ogden Stiers). Next to Tia Carrere is the phrase “andie butlet”. I don’t want to remove it in case it’s something useful, but consulting various cast lists, I can’t find a cast member who this name obviously corresponds to.

Is it a legitimate typo, and if so, what should it be, and if not, should we get rid of it?

Alexwlchan (talk) 19:22, 16 February 2013 (UTC)

 * Yes check.svg Done It was a test edit by an anon IP, if we were to assume good faith. It's been taken care of now. -- McDoob  AU93  19:27, 16 February 2013 (UTC)

Lilo & Stitch - Circle of Life
The song "Circle of Life" is not featured in Lilo & Stitch (2002), it was seen in The Lion King (1994). — Preceding unsigned comment added by 68.147.198.171 (talk) 00:32, 20 June 2014 (UTC)

UK 2-Disc DVD
A 2-disc special edition DVD of the film was released in the United Kingdom on August 22, 2005. --TheLennyGriffinFan1994 (talk) 01:39, 11 May 2016 (UTC)
 * , it's unclear if you're proposing this information as an addition, or what. If so, you'll need to provide a reference. Thanks. Cyphoidbomb (talk) 01:44, 11 May 2016 (UTC)

External links modified
Hello fellow Wikipedians,

I have just modified one external link on Lilo & Stitch. Please take a moment to review my edit. If you have any questions, or need the bot to ignore the links, or the page altogether, please visit this simple FaQ for additional information. I made the following changes:
 * Added archive https://web.archive.org/web/20121024025330/http://blogs.orlandosentinel.com/entertainment_movies_blog/2009/04/lilo-stitch-disney-feature-animation-floridas-finest-hourremembered.html to http://blogs.orlandosentinel.com/entertainment_movies_blog/2009/04/lilo-stitch-disney-feature-animation-floridas-finest-hourremembered.html

When you have finished reviewing my changes, you may follow the instructions on the template below to fix any issues with the URLs.

Cheers.— InternetArchiveBot  (Report bug) 18:16, 20 April 2017 (UTC)

title: Talk:Lilo & Stitch


text:
Märkisch-Oderland

Märkisch-Oderland is a Landkreis (district) in the eastern part of Brandenburg, Germany. Neighboring this district are (from the north clockwise) the district of Barnim, the country of Poland, the district-free city of Frankfurt (Oder), the district of Oder-Spree and the Bundesland of Berlin. The administrative seat is the town of Seelow but the largest town is Strausberg.

Geography
The district extends from the outskirts of Berlin in the west to the Oder river and the Polish border in the east. It includes a swampy area along the Oder known as the Oderbruch, about 60 km in length and 17 km in width. The Oderbruch was partially drained and populated in the 18th century. The rest of the district is mainly agricultural land.

History
The district dates back to the district of Lebus and the district of Oberbarnim, which were both created in 1816. The district of Lebus dates back to the Land Lebus, the region around the town of Lebus. In 1863 Seelow became the seat of the administration of the district of Lebus, and in 1950 the district was renamed to Kreis Seelow. In 1952 the districts were split into three parts, the districts of Bad Freienwalde, Seelow and Strausberg. In 1993 the three parts were merged to form the current district - the new name refers to Northmarch lands at the Oder river.

Coat of arms
The coat of arms shows the eagle of Brandenburg in the upper half. The upper half also resembles the coat of arms of the former district of Oberbarnim. In the lower half are two boat-hooks and a star, both taken from the coat of arms of the former district of Seelow. The wavy line in the bottom represents the Oder river.

title: Märkisch-Oderland


text:
Balking pattern

The balking pattern is a software design pattern that only executes an action on an object when the object is in a particular state. For example, if an object reads ZIP files and a calling method invokes a get method on the object when the ZIP file is not open, the object would "balk" at the request. In the Java programming language, for example, an  might be thrown under these circumstances.

There are some specialists in this field who consider balking more of an anti-pattern than a design pattern. If an object cannot support its API, it should either limit the API so that the offending call is not available, or so that the call can be made without limitation. It should:
 * Be created in a "sane state";
 * not make itself available until it is in a sane state;
 * become a facade and answer back an object that is in a sane state.

Usage
Objects that use this pattern are generally only in a state that is prone to balking temporarily but for an unknown amount of time. If objects are to remain in a state which is prone to balking for a known, finite period of time, then the guarded suspension pattern may be preferred.

Implementation
Below is a general, simple example for an implementation of the balking pattern. As demonstrated by the definition above, notice how the "synchronized" line is utilized. If there are multiple calls to the job method, only one will proceed while the other calls will return with nothing. Another thing to note is the  method. The reason it is synchronized is because the only way to guarantee another thread will see a change to a field is to synchronize all access to it. Actually, since it is a boolean variable, it could be left not explicitly synchronized, only declared volatile - to guarantee that the other thread will not read an obsolete cached value.

title: Balking pattern


text:
Guarded suspension

In concurrent programming, guarded suspension is a software design pattern for managing operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed. The guarded suspension pattern is typically applied to method calls in object-oriented programs, and involves suspending the method call, and the calling thread, until the precondition (acting as a guard) is satisfied.

Usage
Because it is blocking, the guarded suspension pattern is generally only used when the developer knows that a method call will be suspended for a finite and reasonable period of time. If a method call is suspended for too long, then the overall program will slow down or stop, waiting for the precondition to be satisfied. If the developer knows that the method call suspension will be indefinite or for an unacceptably long period, then the balking pattern may be preferred.

Implementation
In Java, the Object class provides the  and   methods to assist with guarded suspension. In the implementation below, originally found in, if there is no precondition satisfied for the method call to be successful, then the method will wait until it finally enters a valid state.

An example of an actual implementation would be a queue object with a  method that has a guard to detect when there are no items in the queue. Once the  method notifies the other methods (for example, a   method), then the   method can exit its guarded state and proceed with a call. Once the queue is empty, then the  method will enter a guarded state once again.

title: Guarded suspension


text:
Double-checked locking

In software engineering, double-checked locking (also known as "double-checked locking optimization" ) is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock. Locking occurs only if the locking criterion check indicates that locking is required.

The original form of the pattern, appearing in Pattern Languages of Program Design 3, has data races, depending on the memory model in use, and it is hard to get right. Some consider it to be an anti-pattern. There are valid forms of the pattern, including the use of the keyword in Java and explicit memory barriers in C++.

The pattern is typically used to reduce locking overhead when implementing "lazy initialization" in a multi-threaded environment, especially as part of the Singleton pattern. Lazy initialization avoids initializing a value until the first time it is accessed.

Motivation and original pattern
Consider, for example, this code segment in the Java programming language:

The problem is that this does not work when using multiple threads. A lock must be obtained in case two threads call  simultaneously. Otherwise, either they may both try to create the object at the same time, or one may wind up getting a reference to an incompletely initialized object.

Synchronizing with a lock can fix this, as is shown in the following example:

This is correct and will most likely have sufficient performance. However, the first call to  will create the object and only the few threads trying to access it during that time need to be synchronized; after that all calls just get a reference to the member variable. Since synchronizing a method could in some extreme cases decrease performance by a factor of 100 or higher, the overhead of acquiring and releasing a lock every time this method is called seems unnecessary: once the initialization has been completed, acquiring and releasing the locks would appear unnecessary. Many programmers, including the authors of the double-checked locking design pattern, have attempted to optimize this situation in the following manner:

 * 1) Check that the variable is initialized (without obtaining the lock). If it is initialized, return it immediately.
 * 2) Obtain the lock.
 * 3) Double-check whether the variable has already been initialized: if another thread acquired the lock first, it may have already done the initialization. If so, return the initialized variable.
 * 4) Otherwise, initialize and return the variable.

Intuitively, this algorithm is an efficient solution to the problem. But if the pattern is not written carefully, it will have a data race. For example, consider the following sequence of events:

 * 1) Thread A notices that the value is not initialized, so it obtains the lock and begins to initialize the value.
 * 2) Due to the semantics of some programming languages, the code generated by the compiler is allowed to update the shared variable to point to a partially constructed object before A has finished performing the initialization. For example, in Java if a call to a constructor has been inlined then the shared variable may immediately be updated once the storage has been allocated but before the inlined constructor initializes the object.
 * 3) Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B (either because A has not finished initializing it or because some of the initialized values in the object have not yet percolated to the memory B uses (cache coherence)), the program will likely crash.

Most runtimes have memory barriers or other methods for managing memory visibility across execution units. Without a detailed understanding of the language's behavior in this area, the algorithm is difficult to implement correctly. One of the dangers of using double-checked locking is that even a naive implementation will appear to work most of the time: it is not easy to distinguish between a correct implementation of the technique and one that has subtle problems. Depending on the compiler, the interleaving of threads by the scheduler and the nature of other concurrent system activity, failures resulting from an incorrect implementation of double-checked locking may only occur intermittently. Reproducing the failures can be difficult.

Usage in C++11
For the singleton pattern, double-checked locking is not needed:

"If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization."

- § 6.7 [stmt.dcl] p4

C++11 and beyond also provide a built-in double-checked locking pattern in the form of  and  :

If one truly wishes to use the double-checked idiom instead of the trivially working example above (for instance because Visual Studio before the 2015 release did not implement the C++11 standard's language about concurrent initialization quoted above ), one needs to use acquire and release fences:

Usage in POSIX
must be used to initialize library (or sub-module) code when its API does not have a dedicated initialization procedure required to be called in single-threaded mode.

Usage in Java
As of J2SE 5.0, the volatile keyword is defined to create a memory barrier. This allows a solution that ensures that multiple threads handle the singleton instance correctly. This new idiom is described in and.

Note the local variable "localRef", which seems unnecessary. The effect of this is that in cases where helper is already initialized (i.e., most of the time), the volatile field is only accessed once (due to "return localRef;" instead of "return helper;"), which can improve the method's overall performance by as much as 40 percent.

Java 9 introduced the class, which allows use of relaxed atomics to access fields, giving somewhat faster reads on machines with weak memory models, at the cost of more difficult mechanics and loss of sequential consistency (field accesses no longer participate in the synchronization order, the global order of accesses to volatile fields).

If the helper object is static (one per class loader), an alternative is the initialization-on-demand holder idiom (See Listing 16.6 from the previously cited text.)

This relies on the fact that nested classes are not loaded until they are referenced.

Semantics of final field in Java 5 can be employed to safely publish the helper object without using volatile:

The local variable tempWrapper is required for correctness: simply using helperWrapper for both null checks and the return statement could fail due to read reordering allowed under the Java Memory Model. Performance of this implementation is not necessarily better than the volatile implementation.

Usage in C#
In .NET Framework 4.0, the  class was introduced, which internally uses double-checked locking by default (ExecutionAndPublication mode) to store either the exception that was thrown during construction, or the result of the function that was passed to  :

title: Double-checked locking