Design Pattern Quick Reference

Total Page:16

File Type:pdf, Size:1020Kb

Design Pattern Quick Reference APPENDIX A Design Pattern Quick Reference Quick Checks for the Code 1. Singleton Pattern 2. Prototype Pattern 3. Factory Pattern 4. Builder Pattern 5. Adapter Pattern 6. Decorator Pattern 7. Facade Pattern 8. Proxy Pattern 9. Chain of Responsibility Pattern 10. Composite 11. Command Pattern 12. Interpreter Pattern 13. Iterator Pattern 14. Observer Pattern 15. State Pattern 16. Strategy Pattern 327 © Wessel Badenhorst 2017 W. Badenhorst, Practical Python Design Patterns, https://doi.org/10.1007/978-1-4842-2680-3 APPENDIX A DESIGN PaTTERN QUICK REFERENCE 17. Template Method Pattern 18. Visitor Pattern 19. Model–View–Controller Pattern 20. Publisher–Subscriber Pattern Singleton singleton.py class SingletonObject(object): class __SingletonObject(): def __init__(self): self.val = None def __str__(self): return "{0!r} {1}".format(self, self.val) # the rest of the class definition will follow here, as per the previous logging script instance = None def __new__(cls): if not SingletonObject.instance: SingletonObject.instance = SingletonObject.__SingletonObject() return SingletonObject.instance def __getattr__(self, name): return getattr(self.instance, name) def __setattr__(self, name): return setattr(self.instance, name) 328 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Prototype prototype_1.py from abc import ABCMeta, abstractmethod class Prototype(metaclass=ABCMeta): @abstractmethod def clone(self): pass concrete.py from prototype_1 import Prototype from copy import deepcopy class Concrete(Prototype): def clone(self): return deepcopy(self) Factory factory.py import abc class AbstractFactory(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def make_object(self): return class ConcreteFactory(AbstractFactory): def make_object(self): # do something return ConcreteClass() 329 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Builder form_builder.py from abc import ABCMeta, abstractmethod class Director(object, metaclass=ABCMeta): def __init__(self): self._builder = None @abstractmethod def construct(self): pass def get_constructed_object(self): return self._builder.constructed_object class Builder(object, metaclass=ABCMeta): def __init__(self, constructed_object): self.constructed_object = constructed_object class Product(object): def __init__(self): pass def __repr__(self): pass class ConcreteBuilder(Builder): pass class ConcreteDirector(Director): pass 330 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Adapter third_party.py class WhatIHave(object): def provided_function_1(self): pass def provided_function_2(self): pass class WhatIWant(object): def required_function(): pass adapter.py from third_party import WhatIHave class ObjectAdapter(object): def __init__(self, what_i_have): self.what_i_have = what_i_have def required_function(self): return self.what_i_have.provided_function_1() def __getattr__(self, attr): # Everything else is handled by the wrapped object return getattr(self.what_i_have, attr) Decorator decorator.py from functools import wraps def dummy_decorator(f): @wraps(f) def wrap_f(): print("Function to be decorated: ", f.__name__) print("Nested wrapping function: ", wrap_f.__name__) return f() return wrap_f 331 APPENDIX A DESIGN PaTTERN QUICK REFERENCE @dummy_decorator def do_nothing(): print("Inside do_nothing") if __name__ == "__main__": print("Wrapped function: ",do_nothing.__name__) do_nothing() Facade simple_ facade.py class Invoice: def __init__(self, customer): pass class Customer: Altered customer class to try to fetch a customer on init or creates a new one def __init__(self, customer_id): pass class Item: # Altered item class to try to fetch an item on init or creates a new one def __init__(self, item_barcode): pass class Facade: @staticmethod def make_invoice(customer): return Invoice(customer) @staticmethod def make_customer(customer_id): return Customer(customer_id) @staticmethod def make_item(item_barcode): return Item(item_barcode) # ... 332 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Proxy proxy.py import time class RawClass(object): def func(self, n): return f(n) def memoize(fn): __cache = {} def memoized(*args): key = (fn.__name__, args) if key in __cache: return __cache[key] __cache[key] = fn(*args) return __cache[key] return memoized class ClassProxy(object): def __init__(self, target): self.target = target func = getattr(self.target, 'func') setattr(self.target, 'func', memoize(func)) def __getattr__(self, name): return getattr(self.target, name) 333 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Chain of Responsibility chain_of_responsibility.py class EndHandler(object): def __init__(self): pass def handle_request(self, request): pass class Handler1(object): def __init__(self): self.next_handler = EndHandler() def handle_request(self, request): self.next_handler.handle_request(request) def main(request): concrete_handler = Handler1() concrete_handler.handle_request(request) if __name__ == "__main__": # from the command line we can define some request main(request) Alternative chain_of_responsibility_alt.py class Dispatcher(object): def __init__(self, handlers=[]): self.handlers = handlers def handle_request(self, request): for handler in self.handlers: request = handler(request) return request 334 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Command command.py class Command: def __init__(self, receiver, text): self.receiver = receiver self.text = text def execute(self): self.receiver.print_message(self.text) class Receiver(object): def print_message(self, text): print("Message received: {}".format(text)) class Invoker(object): def __init__(self): self.commands = [] def add_command(self, command): self.commands.append(command) def run(self): for command in self.commands: command.execute() if __name__ == "__main__": receiver = Receiver() command1 = Command(receiver, "Execute Command 1") command2 = Command(receiver, "Execute Command 2") invoker = Invoker() invoker.add_command(command1) invoker.add_command(command2) invoker.run() 335 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Composite composite.py class Leaf(object): def __init__(self, *args, **kwargs): pass def component_function(self): print("Leaf") class Composite(object): def __init__(self, *args, **kwargs): self.children = [] def component_function(self): for child in children: child.component_function() def add(self, child): self.children.append(child) def remove(self, child): self.children.remove(child) Interpreter interpreter.py class NonTerminal(object): def __init__(self, expression): self.expression = expression def interpret(self): self.expression.interpret() class Terminal(object): def interpret(self): pass 336 APPENDIX A DESIGN PaTTERN QUICK REFERENCE Iterator classic_iterator.py import abc class Iterator(metaclass=abc.ABCMeta): @abc.abstractmethod def has_next(self): pass @abc.abstractmethod def next(self): pass class Container(metaclass=abc.ABCMeta): @abc.abstractmethod def getIterator(self): pass class MyListIterator(Iterator): def __init__(self, my_list): self.index = 0 self.list = my_list.list def has_next(self): return self.index < len(self.list) def next(self): self.index += 1 return self.list[self.index - 1] class MyList(Container): def __init__(self, *args): self.list = list(args) def getIterator(self): return MyListIterator(self) 337 APPENDIX A DESIGN PaTTERN QUICK REFERENCE if __name__ == "__main__": my_list = MyList(1, 2, 3, 4, 5, 6) my_iterator = my_list.getIterator() while my_iterator.has_next(): print(my_iterator.next()) Alternative iterator_alt.py for element in collection: do_something(element) Observer observer.py class ConcreteObserver(object): def update(self, observed): print("Observing: {}".format(observed)) class Observable(object): def __init__(self): self.callbacks = set() self.changed = False def register(self, callback): self.callbacks.add(callback) def unregister(self, callback): self.callbacks.discard(callback) def unregister_all(self): self.callbacks = set() 338 APPENDIX A DESIGN PaTTERN QUICK REFERENCE def poll_for_change(self): if self.changed: self.update_all def update_all(self): for callback in self.callbacks: callback(self) State state.py class State(object): pass class ConcreteState1(State): def __init__(self, state_machine): self.state_machine = state_machine def switch_state(self): self.state_machine.state = self.state_machine.state2 class ConcreteState2(State): def __init__(self, state_machine): self.state_machine = state_machine def switch_state(self): self.state_machine.state = self.state_machine.state1 class StateMachine(object): def __init__(self): self.state1 = ConcreteState1(self) self.state2 = ConcreteState2(self) self.state = self.state1 def switch(self): self.state.switch_state() 339 APPENDIX A DESIGN PaTTERN QUICK REFERENCE def __str__(self): return str(self.state) def main(): state_machine = StateMachine() print(state_machine) state_machine.switch() print(state_machine) if __name__ == "__main__": main() Strategy strategy.py def executor(arg1, arg2, func=None): if func is None: return "Strategy not implemented..." return func(arg1, arg2) def strategy_1(arg1, arg2): return f_1(arg1, arg2) def strategy_2(arg1, arg2): return f_2(arg1, arg2) Template Method template_method.py import abc class TemplateAbstractBaseClass(metaclass=abc.ABCMeta): def template_method(self): self._step_1() self._step_2() self._step_n() 340 APPENDIX A DESIGN PaTTERN QUICK REFERENCE @abc.abstractmethod def _step_1(self): pass @abc.abstractmethod def _step_2(self): pass @abc.abstractmethod def _step_3(self): pass class ConcreteImplementationClass(TemplateAbstractBaseClass): def _step_1(self): pass def _step_2(self): pass def _step_3(self):
Recommended publications
  • Customizing and Extending Powerdesigner SAP Powerdesigner Documentation Collection Content
    User Guide PUBLIC SAP PowerDesigner Document Version: 16.6.2 – 2017-01-05 Customizing and Extending PowerDesigner SAP PowerDesigner Documentation Collection Content 1 PowerDesigner Resource Files.................................................... 9 1.1 Opening Resource Files in the Editor.................................................10 1.2 Navigating and Searching in Resource Files............................................ 11 1.3 Editing Resource Files........................................................... 13 1.4 Saving Changes................................................................13 1.5 Sharing and Embedding Resource Files...............................................13 1.6 Creating and Copying Resource Files.................................................14 1.7 Specifying Directories to Search for Resource Files.......................................15 1.8 Comparing Resource Files........................................................ 15 1.9 Merging Resource Files.......................................................... 16 2 Extension Files................................................................18 2.1 Creating an Extension File.........................................................19 2.2 Attaching Extensions to a Model....................................................20 2.3 Exporting an Embedded Extension File for Sharing.......................................21 2.4 Extension File Properties......................................................... 21 2.5 Example: Adding a New Attribute from a Property
    [Show full text]
  • IPBES Workshop on Biodiversity and Pandemics Report
    IPBES Workshop on Biodiversity and Pandemics WORKSHOP REPORT *** Strictly Confidential and Embargoed until 3 p.m. CET on 29 October 2020 *** Please note: This workshop report is provided to you on condition of strictest confidentiality. It must not be shared, cited, referenced, summarized, published or commented on, in whole or in part, until the embargo is lifted at 3 p.m. CET/2 p.m. GMT/10 a.m. EDT on Thursday, 29 October 2020 This workshop report is released in a non-laid out format. It will undergo minor editing before being released in a laid-out format. Intergovernmental Platform on Biodiversity and Ecosystem Services 1 The IPBES Bureau and Multidisciplinary Expert Panel (MEP) authorized a workshop on biodiversity and pandemics that was held virtually on 27-31 July 2020 in accordance with the provisions on “Platform workshops” in support of Plenary- approved activities, set out in section 6.1 of the procedures for the preparation of Platform deliverables (IPBES-3/3, annex I). This workshop report and any recommendations or conclusions contained therein have not been reviewed, endorsed or approved by the IPBES Plenary. The workshop report is considered supporting material available to authors in the preparation of ongoing or future IPBES assessments. While undergoing a scientific peer-review, this material has not been subjected to formal IPBES review processes. 2 Contents 4 Preamble 5 Executive Summary 12 Sections 1 to 5 14 Section 1: The relationship between people and biodiversity underpins disease emergence and provides opportunities
    [Show full text]
  • Design Patterns Promote Reuse
    Design Patterns Promote Reuse “A pattern describes a problem that occurs often, along with a tried solution to the problem” - Christopher Alexander, 1977 • Christopher Alexander’s 253 (civil) architectural patterns range from the creation of cities (2. distribution of towns) to particular building problems (232. roof cap) • A pattern language is an organized way of tackling an architectural problem using patterns Kinds of Patterns in Software • Architectural (“macroscale”) patterns • Model-view-controller • Pipe & Filter (e.g. compiler, Unix pipeline) • Event-based (e.g. interactive game) • Layering (e.g. SaaS technology stack) • Computation patterns • Fast Fourier transform • Structured & unstructured grids • Dense linear algebra • Sparse linear algebra • GoF (Gang of Four) Patterns: structural, creational, behavior The Gang of Four (GoF) • 23 structural design patterns • description of communicating objects & classes • captures common (and successful) solution to a category of related problem instances • can be customized to solve a specific (new) problem in that category • Pattern ≠ • individual classes or libraries (list, hash, ...) • full design—more like a blueprint for a design The GoF Pattern Zoo 1. Factory 13. Observer 14. Mediator 2. Abstract factory 15. Chain of responsibility 3. Builder Creation 16. Command 4. Prototype 17. Interpreter 18. Iterator 5. Singleton/Null obj 19. Memento (memoization) 6. Adapter Behavioral 20. State 21. Strategy 7. Composite 22. Template 8. Proxy 23. Visitor Structural 9. Bridge 10. Flyweight 11.
    [Show full text]
  • Writing Mathematical Expressions in Plain Text – Examples and Cautions Copyright © 2009 Sally J
    Writing Mathematical Expressions in Plain Text – Examples and Cautions Copyright © 2009 Sally J. Keely. All Rights Reserved. Mathematical expressions can be typed online in a number of ways including plain text, ASCII codes, HTML tags, or using an equation editor (see Writing Mathematical Notation Online for overview). If the application in which you are working does not have an equation editor built in, then a common option is to write expressions horizontally in plain text. In doing so you have to format the expressions very carefully using appropriately placed parentheses and accurate notation. This document provides examples and important cautions for writing mathematical expressions in plain text. Section 1. How to Write Exponents Just as on a graphing calculator, when writing in plain text the caret key ^ (above the 6 on a qwerty keyboard) means that an exponent follows. For example x2 would be written as x^2. Example 1a. 4xy23 would be written as 4 x^2 y^3 or with the multiplication mark as 4*x^2*y^3. Example 1b. With more than one item in the exponent you must enclose the entire exponent in parentheses to indicate exactly what is in the power. x2n must be written as x^(2n) and NOT as x^2n. Writing x^2n means xn2 . Example 1c. When using the quotient rule of exponents you often have to perform subtraction within an exponent. In such cases you must enclose the entire exponent in parentheses to indicate exactly what is in the power. x5 The middle step of ==xx52− 3 must be written as x^(5-2) and NOT as x^5-2 which means x5 − 2 .
    [Show full text]
  • How Many Bits Are in a Byte in Computer Terms
    How Many Bits Are In A Byte In Computer Terms Periosteal and aluminum Dario memorizes her pigeonhole collieshangie count and nagging seductively. measurably.Auriculated and Pyromaniacal ferrous Gunter Jessie addict intersperse her glockenspiels nutritiously. glimpse rough-dries and outreddens Featured or two nibbles, gigabytes and videos, are the terms bits are in many byte computer, browse to gain comfort with a kilobyte est une unité de armazenamento de armazenamento de almacenamiento de dados digitais. Large denominations of computer memory are composed of bits, Terabyte, then a larger amount of nightmare can be accessed using an address of had given size at sensible cost of added complexity to access individual characters. The binary arithmetic with two sets render everything into one digit, in many bits are a byte computer, not used in detail. Supercomputers are its back and are in foreign languages are brainwashed into plain text. Understanding the Difference Between Bits and Bytes Lifewire. RAM, any sixteen distinct values can be represented with a nibble, I already love a Papst fan since my hybrid head amp. So in ham of transmitting or storing bits and bytes it takes times as much. Bytes and bits are the starting point hospital the computer world Find arrogant about the Base-2 and bit bytes the ASCII character set byte prefixes and binary math. Its size can vary depending on spark machine itself the computing language In most contexts a byte is futile to bits or 1 octet In 1956 this leaf was named by. Pages Bytes and Other Units of Measure Robelle. This function is used in conversion forms where we are one series two inputs.
    [Show full text]
  • Automatically Adapting Programs for Mixed-Precision Floating-Point Computation
    Automatically Adapting Programs for Mixed-Precision Floating-Point Computation Michael O. Lam and Bronis R. de Supinski and Jeffrey K. Hollingsworth Matthew P. LeGendre Dept. of Computer Science Center for Applied Scientific Computing University of Maryland Lawrence Livermore National Laboratory College Park, MD, USA Livermore, CA, USA [email protected], [email protected] [email protected], [email protected] ABSTRACT IEEE standard provides for different levels of precision by As scientific computation continues to scale, efficient use of varying the field width, with the most common widths being floating-point arithmetic processors is critical. Lower preci- 32 bits (\single" precision) and 64 bits (\double" precision). sion allows streaming architectures to perform more opera- Figure 1 graphically represents these formats. tions per second and can reduce memory bandwidth pressure Double-precision arithmetic generally results in more ac- on all architectures. However, using a precision that is too curate computations, but with several costs. The main cost low for a given algorithm and data set leads to inaccurate re- is the higher memory bandwidth and storage requirement, sults. In this paper, we present a framework that uses binary which are twice that of single precision. Another cost is instrumentation and modification to build mixed-precision the reduced opportunity for parallelization, such as on the configurations of existing binaries that were originally devel- x86 architecture, where packed 128-bit XMM registers can oped to use only double-precision. This framework allows only hold and operate on two double-precision numbers si- developers to explore mixed-precision configurations with- multaneously compared to four numbers with single preci- out modifying their source code, and it enables automatic sion.
    [Show full text]
  • Programming Curriculum
    PARC VLP PROGRAMMING CURRICULUM WWW.PARCROBOTICS.ORG Overview Study of programming languages, paradigms and data structures. Chapter 1: Programming Basics Sections A. What is programming? B. What is a programming language? C. Writing source code D. Running your code E. Using IDE Chapter 2: Programming Syntax Sections A. Why Python?A. Why Python? B. Basic statementsB. Basic statements and expressions and expressions C. Troubleshooting issues C. Troubleshooting issues Chapter 3: Variables and Data Types Sections A. IntroductionA. to Introductionvariables and to data variables types and data types B. WorkingB.W withorking variables with variables across Languages across Languages C. Working with numbers C. Working with numbers D. Working with strings E. WorkingD. with commentsWorking with strings E. Working with comments Chapter 4: Conditional Code Sections: A. Making decisions in code B. Exploring conditional code C. Working with simple conditions D. Conditionals across languages PAN-AFRICAN ROBOTICS COMPETITION 1 Chapter 1 SECTION A What is programming? Programming is the process of converting ideas into instructions that a computer can understand and execute. These instructions are specific and sequential. You can think of it as a recipe. Let's you want to prepare your favorite food; you would need first a list of ingredients and then a set of instructions as to which ingredients go in first. If you have ever cooked before or watched someone cook before you will know that the amount of each ingredient can dramatically affect the outcome. Computers are very literal. They try to execute our commands exactly. When we give them bad instructions, we might introduce bugs or even make the computer crash.
    [Show full text]
  • Dependency Injection in Unity3d
    Dependency Injection in Unity3D Niko Parviainen Bachelor’s thesis March 2017 Technology, communication and transport Degree Programme in Software Engineering Description Author(s) Type of publication Date Parviainen, Niko Bachelor’s thesis March 2017 Language of publication: English Number of pages Permission for web publi- 57 cation: x Title of publication Dependency Injection in Unity3D Degree programme Degree Programme in Software Engineering Supervisor(s) Rantala, Ari Hämäläinen, Raija Assigned by Psyon Games Oy Abstract The objective was to find out how software design patterns and principles are applied to game development to achieve modular design. The tasks of the research were to identify the dependency management problem of a modular design, find out what the solutions offered by Unity3D are, find out what the dependency injection pattern is and how it is used in Unity3D environment. Dependency management in Unity3D and the dependency injection pattern were studied. Problems created by Unity3D’s solutions were introduced with examples. Dependency in- jection pattern was introduced with examples and demonstrated by implementing an ex- ample game using one of the available third-party frameworks. The aim of the example game was to clarify if the use of dependency injection brings modularity in Unity3D envi- ronment and what the cost of using it is. The principles of SOLID were introduced with generic examples and used to assist depend- ency injection to further increase the modularity by bringing the focus on class design. Dependency injection with the help of SOLID principles increased the modularity by loosely coupling classes even though slightly increasing the overall complexity of the architecture.
    [Show full text]
  • Text File Text File Example Text Reading Overview
    CS106A, Stanford Handout #53 Fall, 2003-04 Nick Parlante Files Text File The simple "text file" is one of the oldest and simplest types of file. For that reason, text files are one of the most universally standard ways to store information. A text file is something you could type up in a word processor, and save with the "plain text" option. A text file is made of a sequence of characters, organized as a series of horizontal lines of text. There is no notion of bold or italic or color applied to the characters; they are just plain text characters, as we would store in a String. Historically, text files have been made of the familiar roman keyboard alphabet – abcdef..xyz012..89!@#$.. – with the extremely standard ASCII encoding (American Standard Code for Information Interchange). More recently, text has grown to include the idea of unicode characters like ø and !, but the encodings for those are not yet as standard as ASCII. The .java files where we write our Java code are examples of text files. The text file is such a simple, flexible way to store information, it will be with us for a long time to come. If you want to store information in a simple, non-proprietary way, the text file is a great choice. XML files, which are a very modern way to store information, are a type of text file. Text File Example This is the first line of my 4 line text file, and this here is the 2nd. The above line is blank! The above example text file is 4 lines long.
    [Show full text]
  • Facet: a Pattern for Dynamic Interfaces
    Facet: A pattern for dynamic interfaces Author: Eric Crahen SUNY at Buffalo CSE Department Amherst, NY 14260 201 Bell Hall 716-645-3180 <[email protected]> Context: Wherever it is desirable to create a context sensitive interface in order to modify or control the apparent behavior if an object. Problem: How can I modify the behavior of an existing object so that different behaviors are shown under different circumstances; and yet still maintain a clean separation between the policy (when each behavior is available) and implementation of each behavior allowing them to be developed independently of one another? Forces: Interfaces provide an essential level of abstraction to object oriented programming. Generally, objects are able define aspects of their function very well using interfaces. At times, this may not be enough. When dealing with two or more classes whose responsibilities are distinctly separate, but whose behavior is closely related, classes can begin to resist modularization. For example, adding security to an application means inserting code that performs security checks into numerous locations in existing classes. Clearly, these responsibilities are distinct; the original classes being responsible for the tasks they were designed to perform, and the security classes being responsible for providing access control. However, making those original classes secure means intermingling code that deals with security. When the classes dealing with security are changed many classes are going to be impacted. One method of adding new behavior to an existing class might be to simply create a subclass and embed that new behavior. In the security example, this would mean creating a subclass for each class that needs to be secure and adding calls to the security code.
    [Show full text]
  • Dependency Injection with Unity
    D EPEN DEPENDENCY INJECTION WITH UNITY Over the years software systems have evolutionarily become more and more patterns & practices D ENCY complex. One of the techniques for dealing with this inherent complexity Proven practices for predictable results of software systems is dependency injection – a design pattern that I allows the removal of hard-coded dependencies and makes it possible to Save time and reduce risk on your NJECT assemble a service by changing dependencies easily, whether at run-time software development projects by or compile-time. It promotes code reuse and loosely-coupled design which incorporating patterns & practices, I leads to more easily maintainable and flexible code. Microsoft’s applied engineering ON guidance that includes both production The guide you are holding in your hands is a primer on using dependency quality source code and documentation. W I injection with Unity – a lightweight extensible dependency injection TH DEPENDENCY INJECTION container built by the Microsoft patterns & practices team. It covers The guidance is designed to help U software development teams: various styles of dependency injection and also additional capabilities N I of Unity container, such as object lifetime management, interception, Make critical design and technology TY and registration by convention. It also discusses the advanced topics of selection decisions by highlighting WITH UNITY enhancing Unity with your custom extensions. the appropriate solution architectures, technologies, and Microsoft products The guide contains plenty of trade-off discussions and tips and tricks for for common scenarios managing your application cross-cutting concerns and making the most out of both dependency injection and Unity. These are accompanied by a Understand the most important Dominic Betts real world example that will help you master the techniques.
    [Show full text]
  • Design Patterns in Ocaml
    Design Patterns in OCaml Antonio Vicente [email protected] Earl Wagner [email protected] Abstract The GOF Design Patterns book is an important piece of any professional programmer's library. These patterns are generally considered to be an indication of good design and development practices. By giving an implementation of these patterns in OCaml we expected to better understand the importance of OCaml's advanced language features and provide other developers with an implementation of these familiar concepts in order to reduce the effort required to learn this language. As in the case of Smalltalk and Scheme+GLOS, OCaml's higher order features allows for simple elegant implementation of some of the patterns while others were much harder due to the OCaml's restrictive type system. 1 Contents 1 Background and Motivation 3 2 Results and Evaluation 3 3 Lessons Learned and Conclusions 4 4 Creational Patterns 5 4.1 Abstract Factory . 5 4.2 Builder . 6 4.3 Factory Method . 6 4.4 Prototype . 7 4.5 Singleton . 8 5 Structural Patterns 8 5.1 Adapter . 8 5.2 Bridge . 8 5.3 Composite . 8 5.4 Decorator . 9 5.5 Facade . 10 5.6 Flyweight . 10 5.7 Proxy . 10 6 Behavior Patterns 11 6.1 Chain of Responsibility . 11 6.2 Command . 12 6.3 Interpreter . 13 6.4 Iterator . 13 6.5 Mediator . 13 6.6 Memento . 13 6.7 Observer . 13 6.8 State . 14 6.9 Strategy . 15 6.10 Template Method . 15 6.11 Visitor . 15 7 References 18 2 1 Background and Motivation Throughout this course we have seen many examples of methodologies and tools that can be used to reduce the burden of working in a software project.
    [Show full text]