bar
.";
$code_examples = <<<'EOT'
interface Command{ void execute();}
static class foo implements Command{
public void execute(){
System.out.println("quux");
}
}
static class bar implements Command{
public void execute(){
System.out.println("baz");
}
}
public static List generateRequests(){
List queue = new ArrayList();
queue.add(new foo());
queue.add(new bar());
return queue;
}
public static void doRequests(List queue){
for(Iterator iter = queue.iterator(); it.hasNext();){
((Command)iter.next()).execute();
}
}
public static void main(String[] args){
List queue = generateRequests();
doRequests(queue);
}
// output:
quux
baz
EOT;
$related_patterns = array("Observer", "Chain of Responsibility", "Memento (mementos can be used to maintain the state for undo operations)");
break;
case "observer":
$page_header = "Observer";
$problem = "Large design doesn't scale well as new graphics and monitoring requirements are added.";
$solution = "Establish a one-to-many dependency between objects so that when a state changes, all dependents are notified and updated automatically. A "Model" object maintains data and business logic. It can be connected to an external storage device or other implementation of data storage. Observers register themselves with the Model (Subject) when they are created. Any changes to the Subject are broadcast to all Observers.";
$discussion = "Essentially, we are separating the data from its representation. This allows the view to be pluggable and dynamic: the number and type of view objects can be configured on the fly.";
$examples = "One of the most common examples of the Observer pattern is the View part of Model-View-Controller systems. One central Model is designated the Subject for all Observer objects, which query for relevant data when they receive an update()
broadcast. update()
method.";
$code_examples = <<<'EOT'
class Observer{
int value;
public:
Observer(Subject *model, int value){
model->attach(this);
this.value = value;
}
void update(int value){
cout << value << " mod "<< this.value << " = " << value % this.value << endl;
}
}
class Subject{
int value;
vector views;
public:
notify(){
for(int i = 0; i < views.size(); i++) views[i]->update(value);
}
setVal(int value){
this.value = value;
}
attach(Observer *obs){
views.push(obs);
}
}
int main(){
Subject subj;
Observer obs1(&subj, 3);
Observer obs2($subj, 4);
subj.setVal(20);
}
// output:
20 mod 3 = 2
20 mod 4 = 0
EOT;
$related_patterns = array("Mediator", "Command", "Chain of Responsibility");
break;
case "mediator":
$page_header = "Mediator";
$problem = "Designing reusable components generally results in the "spaghetti code" phenomenon. Dependencies between pieces tend towards all or nothing.";
$solution = "Represent the interactions between objects in a system with a Mediator object. The many-to-many relationships between peers is promoted to "full object status".";
$discussion = "Colleagues (or peers) do not interact with each other directly. Instead, they speak with the Mediator, which knows and conducts the others. It's important to note that not all interacting objects would benefit from mutual decoupling, however it can be useful to abstract those interactions into a new class.";
$examples = "The Mediator pattern could be useful in the design of a user and group permissions system in an operating system. If a group can have zero or more users, and a user can be a member of zero or more groups, the Mediator pattern provides a flexible approach to mapping and managing users and groups. visit()
and accept()
methods.";
$discussion = "The main purpose of the visitor pattern is to abstract away functionality that can be applied to any number of objects within a hierarchy (collection) of objects. This encourages building lightweight element classes because processing is no longer among the list of responsibilities. New functionality can easily be added to the original inheritance hierarchy by simply adding a new Visitor subclass. process()
es the proper Image.";
$code_examples = <<<'EOT'
interface Image{
String process();
}
static class Sepia implements Image{
public String process(){return "Sepia";}
}
static class BW implements Image{
public String process(){return "B/W";}
}
static class Processor{
private static java.util.Random rand = new java.util.Random();
private static int nextId = 1;
private int id = nextId++;
public boolean handle(Image img){
if(rand.nextInt(2) != 0){
System.out.println("Processor " + id + " is busy.");
return false;
}
System.out.println("Processor " + id + ": " + img.process());
return true;
}
}
public static void main(String[] args){
Image[] imgs = {new Sepia(), new BW(), new BW(), new Sepia(), new BW()};
Processor[] processors = {new Processor(), new Processor(), new Processor()};
for(int i = 0, j; i < input.length; i++){
j = 0;
while(!procs[j].handle(imgs[i])) j = (j+1) % processors.length;
}
}
EOT;
$related_patterns = array("Command", "Mediator", "Observer", "Composite");
break;
case "templatemethod":
case "template":
$page_header = "Template Method";
$problem = "When two (or more) components do not share common interface or implentation but do have significant functional similarities, duplicate effore will be expended to make one change to both.";
$solution = "Define the skeleton of an algorithm, allowing the most important parts to be filled in by client subclasses. The Template Method pattern lets subclasses tweak parts of an algorithm to suit its purpose without changing the algorithm itself.";
$discussion = "The algorithm designer decides which parts of the algorithm are standard to all subclasses and which parts are variable (left to the subclasses to define). Variable parts can be given a default implementation or left purposely blank.";
$examples = "The Template pattern is used prominently in the design and implementation of frameworks. Placeholders are left in place for the user to fill in as needed. This pattern book uses the Template pattern extensively: common headers are templated and included where needed.";
$code_explanation = "This function generates the HTML markup (including the proper CSS classes) for a Bootstrap Dropdown Menu from an associative array of links. If the first level is a link, it is included directly in the markup. Otherwise, if an item contains an array (meant here as a submenu), menu items are added for each link in the submenu array. This helps reduce the need for messy HTML markup and also we can change the menu with one change to a menu array (when we are using a common header).";
$code_examples = <<<'EOT'
function build_bootstrap_dropdown_menu($arr){
$ret = "";
foreach($arr as $name => $val){
if(is_array($val)){
$ret .= "pull()
'd every time that a line is read from stdin. The state of the pullchain cycles through, giving a different behavior depending on the current state.";
$code_examples = <<<'EOT'
class Chain{
private int state;
public Chain(){state = 0;}
public void pull(){
if(state > 3) state++;
else state = 0;
System.out.println(state);
}
}
public class Demo{
public static void main(String[] args) throws IOException{
InputStreamReader ins = new InputStreamReader(System.in);
int ch;
Chain chain = new Chain();
while(true){
System.out.print("Press enter");
ch = is.read();
ch = is.read();
chain.pull();
}
}
}
EOT;
$related_patterns = array("Wrapper", "Singleton", "Strategy", "Bridge");
break;
case "strategy":
$page_header = "Strategy";
$problem = "A standard value of software development has been "maximize cohesion and minimize coupling". Over time, objects become more entwined and less flexible to new implementations.";
$solution = "Define a family of interchangeable encapsulated algorithms. The Strategy pattern allows the algorithm to vary based on the clients that use it.";
$discussion = "Clients should prefer interfaces rather than direct connections with peer objects. An interface can represent an abstract base class or the method signatures to be expected.";
$examples = "Different modes of transportation to an arbitrary goal are an example of a Strategy. Any of the different modes will get a traveler to the destination, which can be applied based on tradeoffs between convenience, speed, and cost.";
$code_explanation = "The Comparator.sort()
method in the Java utils is a great example of the Strategy pattern. By implementing the Comparator in our class, we can override the compare()
method and then make our own compare algorithm based on the compareMode set during initialization.";
$code_examples = <<<'EOT'
public class PersonComparator implements ComparatorFubar::make_fubar()
returns a proper new instance of the subtype that you select in the main loop.";
$code_examples = <<<'EOT'
class Fubar{
public:
static Fubar *make_fubar(int c);
virtual void print_name();
}
int main(){
vector fubars;
int choice;
while(1){
cout << "Foo(1) Bar(2) or Quux(3)? Do(0) ";
cin >> choice;
if(!choice) break;
fubars.push(Fubar::make_fubar(choice));
}
for(int i = 0; i < roles.size(); i++) fubars[i]->print_name();
for(int i = 0; i < roles.size(); i++) delete fubars[i];
}
class Foo: public Fubar{
public:
void print_name(){cout << "Foo" << endl;}
}
class Bar: public Fubar{
public:
void print_name(){cout << "Bar" << endl;}
}
class Quux: public Fubar{
public:
void print_name(){cout << "Quux" << endl;}
}
Fubar *Fubar::make_fubar(int c){
if(c == 1) return new Foo;
else if(c == 2) return new Bar;
else return new Quux;
}
EOT;
$related_patterns = array("Template Method (Factory is to object instantiation as Template Method is to algorithm implementation)", "Abstract Factory", "Prototype (creation through delegation, as Factory is creation through inheritance)");
break;
case "doubledispatch":
$page_header = "Double Dispatch";
$problem = "Sometimes the computational path in a program needs to differ based on the runtime arguments it was called with.";
$solution = "The Double Dispatch pattern prescribes a mechanism to call different concrete functions depending on the types of objects involved in the call.";
$discussion = "Double Dispatch is prominently used in the Visitor pattern, where different operations on an object produce different results based on the type of the calling object.";
$code_examples = <<<'EOT'
class foo{
public:
virtual void foobar(foo& f);
}
class bar{
void foobar(foo& f){
cout << "Foo" << endl;
}
void foobar(int& i){
cout << "I am an int" << endl;
}
public:
void getType(foo& f){
f.foobar(*this);
}
}
EOT;
$code_explanation = "Foo and bar are C++ classes. If bar::foobar()
is called, the overloaded method will be selected based on the type of the argument selected by the method signature.";
$examples = "The Visitor pattern usees an implementation of Double Dispatch.";
$related_patterns = array("Visitor");
break;
case "prototype":
$page_header = "Prototype";
$problem = "The new
operator hard-wires the type of object to be created.";
$solution = "Specify the kinds of objects you'd like to be able to create, build a prototypical instance of that, and create new objects by cloning those prototypes.";
$discussion = "Clients clone()
the abstract base class, supplying an optional data type designating the desired subtype. The new
operator is abandoned in favor of prototype cloning.";
$examples = "JavaScript uses prototypes extensively for object creation. The object constructor function in JS is the prototype for that object (which can be called with the new
operator).";
$code_explanation = "JavaScript has string built-in support for prototypes:";
$code_examples = <<<'EOT'
var myprototype = function myprototypeobj(){
this.foo = function(){alert("foo");};
this.bar = function(){alert("bar");};
}
var myobj.prototype = myprototype;
myobj.foo(); myobj.bar(); // myobj is created with the methods of myprototype
EOT;
$related_patterns = array("Factory (creation through inheritance, where Prototype is creation through delegation)", "Abstract Factory", "Composite", "Decorator", "Singleton");
break;
case "abstractfactory":
$page_header = "Abstract Factory";
$problem = "Application portability between platforms is often not considered in advance. The application will need to support different databases, windowing systems, and operating systems. Case statements with options for each platform to be supported begin to appear everywhere throughout the codebase.";
$solution = "Provide an interface for creating families of related and dependent objects without specifying their concrete classes. Create a hierarchy that can encapsulate the appropriate constructions for each supported platform.";
$discussion = "The Abstract Factory defines a Factory Method per product. Clients never create platform objects directly. Instead, they ask the Abstract Factory to do that. Because the service provided is so pervasive, it is often implemented as a Singleton.";
$examples = "A real-world example of the Abstract Factory pattern would be part stamping machines in an actual factory. When different parts need to be stamped, a different form can be swapped into the presses.Singleton
class is defined globally and will only have one instance of itself.";
$code_examples = <<<'EOT'
class Singleton{
int val;
public:
Singleton(int v = 0){val = v;}
int get_value(){return val;}
void set_value(int v){val = v;}
}
Singleton *singleton = 0;
void foo(){
if(!singleton) singleton = new Singleton;
singleton->set_value(1);
cout << "foo: Singleton is " << singleton->get_value() << endl;
}
void bar(){
if(!singleton) singleton = new Singleton;
singleton->set_value(2);
cout << "bar: Singleton is " << singleton->get_value() << endl;
}
int main(){
if(!singleton) singleton = new Singleton;
cout << "main: Singleton is " << singleton->get_value() << endl;
foo(); bar();
}
// output:
main: Singleton is 0
foo: Singleton is 1
bar: Singleton is 2
EOT;
$related_patterns = array("State", "Prototype", "Abstract Factory", "Facade");
break;
case "nullobject":
$page_header = "Null Object";
$problem = "Conditional code adds bloat and decreases speed as the logic branches further and further.";
$solution = "We create a object that implements the desired interface and helps to eliminate conditional code by defining the behavior by defining a default behavior for an empty body.";
$discussion = "The Null Object is very predictable and allows us to test certain conditions without explicitly checking them in a conditional. It's useful precisely because it does nothing.";
$examples = "We can iterate through a linked list. The last node in the chain will be a Null node. When we access it, it halts the iteration process. That way, we don't have to check each node to see if it's null, the standard way to check the existence. The end-of-list behavior we are trying to create is defined in our Null Object, therefore eliminating the need for costly conditionals.";
$code_explanation = "This Null List allows us to visit the entire list (See Visitor Pattern). If we don't use the Null Object, we would get many NullObjectExceptions. With it, the Null Object itself knows what to do.";
$code_examples = <<<'EOT'
public abstract class List{
public abstract List getTail();
}
public class LList extends List{
private Object head;
private Object next;
public LList(Object head, Object next){
this.head = head;
this.next = next;
}
public Object getHead(){return head;}
public List getNext(){return next;}
}
public NullList extends List{
private static final NullList instance = new NullList();
private NullList(){}
public static NullList Singleton(){return instance;}
public List getNext(){return this;}
}
EOT;
$related_patterns = array("Iterator", "State", "Strategy", "Singleton (Null Objects are Singletons)");
break;
/////////////////////////
// STRUCTURAL PATTERNS //
/////////////////////////
case "facade":
$page_header = "Facade";
$problem = "A complex system needs a public interface. The inner workings of that system should not be available to every other system.";
$solution = "Provide a simplified public interface for the use by other systems. Wrap the whole complicated thing in that interface.";
$discussion = "Providing the interface lowers the learning curve required to successfully utilize our system by other clients. It also promotes decoupling from other potential clients. On the other hand, it could limit the features and flexibility available to "power users".";
$examples = "A website can be a Facade to a more complicated subsystem. For example, databases can be accessed and updated from the web, a common task accomplished by server-side scripting. The user only interacts with the public website, which hides the inner complexity of the actual system.";
$code_explanation = "Here, FooFacade is a Facade for Foo and Bar. When we call foo.start()
from main, the internals of the Facade are also initialized.";
$code_examples = <<<'EOT'
class Foo{
public:
quuz(){cout << "quuz" << endl;}
quux(){cout << "quux" << endl;}
}
class Bar{
public:
baz(){cout << "baz" << endl;}
qux(){cout << "qux" << endl;}
}
class FooFacade{
private:
Foo foo; Bar bar;
public:
FooFacade(){
this.foo = new Foo();
this.bar = new Bar();
}
start(){
foo.quuz();
foo.quux();
bar.baz();
bar.qux();
}
}
int main(){
FooFacade foo = new FooFacade();
foo.start();
}
// output:
quuz
quux
baz
qux
EOT;
$related_patterns = array("Adapter", "Flyweight", "Mediator", "Abstract Factory");
break;
case "composite":
$page_header = "Composite";
$problem = "An application needs to manipulate a combination of primitive and complex objects. If the handling differs between those, it would be undesirable to always query the type of object being handled.";
$solution = "Compose objects into recursive tree structures to represent hierarchies. Define an abstract base class that specifies the behavior to be exercised uniformly across all primitive and composite objects.";
$discussion = "Each Composite object only couples itself with the abstract type as it manages its children. Use this pattern whenever you have composites than can contain either components or other composites.";
$examples = "Arithmetic expressions can be represented as Composites. Each operand is the root of a tree. Child nodes can be other operands or a number, a terminal node. With the abstract class, we can treat this Composite as one expression and let the Composite handle that.";
$code_explanation = "This JavaScript snippet defines a tree structure where a node can have some value as its name
and any number of children in an array.";
$code_examples = <<<'EOT'
var Node = function(name){
this.children = [];
this.name = name;
}
Node.prototype = {
add:function(child){
this.children.push(child);
},
remove:function(child){
for(var i = 0; i < this.children.length; i++){
if(this.children[i] === child){
this.children.splice(i, 1);
return;
}
}
},
getChild:function(i){return this.children[i];}
hasChildren:function(){return this.children.length > 0}
}
function traverse(indent, node){
console.log(Array(indent++).join("--") + node.name);
for(var i = 0; i < node.children.length; i++){
traverse(indent, node.getChild(i));
}
}
EOT;
$related_patterns = array("Decorator", "Iterator", "Chain of Responsibility", "Mediator", "Flyweight (on terminal symbols in leaf nodes)");
break;
case "decorator":
$page_header = "Decorator";
$problem = "We want to add functionality to a static object, which is not possible using Inheritance because it is static and would apply that to the entire class.";
$solution = "Attach additional functionality to the object dynamically by wrapping it recursively on the client-side.";
$discussion = "Ensure that we have a single core component and several optional embellishments. The Decorator class attaches additional responsibilities as needed.";
$examples = "The ornaments we put on a Christmas tree are examples of embellishments added by the Decorator. Regardless of how many things we add, it will still be recognizable as a Christmas tree. The added functionality would be the ability to light the tree up.";
$code_explanation = "Python has built-in support for decorators.";
$code_examples = <<<'EOT'
def debug_pop_stack(func):
def debug_print_caller(func):
print('() was called')
return debug_print_caller
@debug
def foo(a, b, c):
print(a, b, c)
#output:
foo was called
EOT;
$related_patterns = array("Adapter", "Proxy", "Composite", "Chain of Responsibility");
break;
case "future":
$page_header = "Future";
$problem = "Some parts of the application require other parts, and may be as yet undefined. We need to test the existing part without writing the whole application.";
$solution = "Define a wrapper class to handle a message that has yet to come.";
$discussion = "The Future pattern is very useful for asynchronous operations, as well as during active development.";
$examples = "We could implement a database connection as a Future. That means we can use the shell interface until we are able to set up the database and connect that properly.";
$code_explanation = "Here, the implementation of Future can be changed in the future to reflect other parts of the system.";
$code_examples = <<<'EOT'
class Future{
int toBeImplemented;
public:
Future(int f){toBeImplemented = f;}
int getval(){return toBeImplemented;}
}
int main(){
Future f = new Future(3);
}
EOT;
$related_patterns = array("Facade", "Proxy", "Adapter", "Bridge");
break;
case "bridge":
$page_header = "Bridge";
$problem = "Applications that try to support many platforms often end up becoming brittle and bloated. Alternate implementations are locked in at compile time to their interfaces.";
$solution = "Create another layer of abstraction: decouple the abstraction from its implementation so the two can vary independently. Goes beyond encapsulation to insulation. This allows run-time flexibility compared to compile-time flexibility.";
$discussion = "The Bridge pattern is applicable when you need run-time binding of client implementation and when you need to share an implementation among several objects. Applying the Bridge pattern results in a decoupled object interface while improving extensibility and hiding unnecessary details from clients.";
$examples = "The action of a switching something on and off can be represented with the Bridge pattern. When you need to switch something, the Bridge will decide at run-time what kind of switch we're interacting with and perform the correct operation, be it a normal lightswitch, a pull-chain, or some sort of knob.";
$code_explanation = "Bridge
is a Bridge for Shapes and Windows.";
$code_examples = <<<'EOT'
class Shape{
$x; $y;
}
class Window{
$w; $h;
}
class Bridge{
$shape = new Shape(400, 500);
$window = new Window(800, 600);
}
EOT;
$related_patterns = array("Adapter (Adapter makes intends to make things work after they're designed, while Bridge intends to make them work before they're designed)", "State", "Strategy", "Abstract Factory");
break;
case "adapter":
$page_header = "Adapter";
$problem = "A new component or dependency is not compatible with the current system architecture.";
$solution = "Convert the interface for the incompatible object into something that the rest of the system expects and understands. Wrap an existing class with a new interface.";
$discussion = "Just as we use adapters for hardware, software often needs an adapter to ease communication between the parts. The Adapter pattern is about creating an intermediary interface object that we can use to talk to incompatible or legacy components.";
$examples = "Many adapters are found in the real world. Display cables are found in several variations (VGA, DVI, DisplayPort, HDMI). The display device that you would like to connect to does not always have the same port as your device. We use adapters to enable the use of these cables and displays.";
$code_explanation = "A database interface in any language is an adapter for systems that aren't directly compatible.";
$code_examples = <<<'EOT'
$db = new OracleOCI('localhost', 'sys', 'password', 'schema');
$query = "select * from DUAL";
$results = $db->query($query);
while($data = oci_fetch_object($results)) echo $data->DUMMY;
EOT;
$related_patterns = array("Bridge (Bridge intends to make things work as they are bring designed, Adapter intends to make older incompatible things work with the current system)", "Proxy", "Decorator", "Facade");
break;
case "flyweight":
$page_header = "Flyweight";
$problem = "Using objects to define a system all the way down to the most specific level provides optimal flexibility, but we often find recurring, related object types at a low level. Creating and managing these objects is unacceptably expensive in terms of memory usage and performance.";
$solution = "Share objects to support many related objects efficiently.";
$discussion = "Flyweight variations are stored in the repository of the application's Factory. Flyweight is generally only useful when the object overhead in a system reaches a critical point.";
$examples = "Storing each graphical glyph for text is an extremely bloated way to store that information. Instead, a commonly-known code for that glyph is stored. When we need to display that again, we pull the glyph corresponding to that code from the local Factory's repository.";
$code_explanation = "ASCII is a Flyweight for characters. The ASCIIchar class prints the internal values as an int and as a char, to represent the table of characters with a value.";
$code_examples = <<<'EOT'
class ASCIIchar{
private:
int c; char ch;
public:
ASCIIchar(int c){
this.c = c;
ch = c;
}
void print(){
cout << (int)c << " " << ch << endl;
}
}
ASCIIchar foo = new ASCIIchar(65);
ASCIIchar bar = new ASCIIchar(110);
int main(){
foo->print();
bar->print();
}
EOT;
$related_patterns = array("Factory", "Composite", "Facade", "State", "Interpreter");
break;
case "proxy":
$page_header = "Proxy";
$problem = "An application needs to support certain resource-hungry objects and operations. We would like to avoid instantiating such objects or performing such operations until they are needed.";
$solution = "Provide a placeholder shell object that can control access to the real object.";
$discussion = "There are several common use cases of the Proxy pattern: DBConnection
is implemented. Additionally, once it is implemented, it will be the interface to that DBConnection. We can use that to interface with the database, changing nothing once it's implemented.";
$code_examples = <<<'EOT'
class ProxyPlaceholder{
DBConnection db;
public:
ProxyPlaceholder(){db = new DBConnection;}
getCon(){return db;}
}
int main(){
string query = "select * from PERSONS";
ProxyPlaceholder db = new ProxyPlaceholder();
db->query(query);
}
EOT;
$related_patterns = array("Adapter", "Decorator", "Future");
break;
default:
header("Location: http://euclid.nmu.edu/~benharri/patternbook/?error¬found=$pattern"); die();
break;
}
$page_header .= " Pattern";
?>
=$problem?>
=$solution?>
=$discussion?>
=$examples?>
=ifsetor($code_explanation)?>
=htmlspecialchars($code_examples)?>