MSDT Design Patterns

@design @patterns

Modern Software Development Techniques | Lectures 6-10 on Design Patterns

Some notes on UML:

@uml

Diagrams show relationships between classes.

In an actual problem the actual relationships are between objects of that class type.

The cardinality of the relation can be indicated next to the relation.

  • Inheritance
    • "is-a" relation
    • A $\rightarrow$ B with "open arrow" means that A is a B.
    • Actual instantiation can be indicated with a filled in arrow.
  • Aggregation
    • A $\rightarrow$ B with "open diamond arrow" means B "aggregates" A, i.e. B contains objects of type A.
  • Composition /Containment?
    • A $\rightarrow$ B with "black filled diamond arrow" means that B is composed of A, and that A is part of B.
    • Can be enforced by instantiating B with final private A.
  • Dependency (Association)
    • A $\rightarrow$ B with "dotted arrow" means that A depends on B, because B is used by A.
    • N.B. All other relations usually are drawn with an up-facing arrow, whereas this one is down-facing.

Q: What does a filled in arrow mean, compared to an open arrow?

Q: What is the exact difference between aggregation and composition?

A: The difference is subtle. Composition is stronger than aggregation, which is reflected by filling in the diamond. Composition (B is composed of A, and A is part of B) means that A cannot meaningfully exist without its "parent" B, of which it is a component. This requirement does not hold for aggregration.

Example: A car engine is part of a car, and cannot function without the car (Composition). Conversely, a player in team is part of the team, but the player individually can still perform meaningful actions (Aggregation).

Q: Where does "containment" come in? A: I think synonymous for aggregation and/or composition?

Notation:

  • :Classname
  • -name (data)
  • +/- getMethod() (public/private)

UML Sequence Diagrams

Overview of interaction dynamics:

1) Lifecycle of objects (construction/destruction) 2) Sequence of important messages / returns

UML Sequence Diagram

UML State Diagrams

High level transition diagram between program states. Arrows indicate transitions with their conditions.

UML state diagram

This example diagram is incomplete because from state 3 no final state is reachable: the program hangs.

Lecture 6: Introduction Design Patterns

Ask yourself: Where does the variability in the program come from, what type is it, and how do I encapsulate it?

Traditional OO solution without further patterns:

1) Describe correspondence in mother classes 2) Encapsulate variability in daughter classes

Example: The corresponding functionality that each car door has is captured in a "car door" class, whereas the specific behavior of specific car depends for a particular car brands implementation of a car door. Now on top of that, imagine that there are two general car door types, that again each have their own implementation. We now have two sources of variability.

We thus have:

  • Variation in abstraction (functionality of the two different car doors)
  • Variation in how each car manufacturer implements these car doors

Limitations:

The traditional OO solution approaches variability by specializing.

  • Although it encapsulates variability, it does not localize it
    • Sources of variability should remain independent, instead of coupling them in one class
    • This leads to complex hierarchy, and combinatorial explosion of classes due to combination of variation sources.
    • Lot of redudancy: for each car door-implementation we have to write a new class with almost identical functionality.
    • Rather than combining independent functionalities, this approach forces each object variation to be a specialized object, that is forced in a complex hierarchical relation.
  • This is due to tight coupling / loose cohesion.
  • Too limited encapsulation
    • Not more than hiding data / methods in daughter classes
  • Does not adequately use association and containment

TLDR limitations; specialization instead of localization of variability; uses tight coupling/loose cohesion; limited encapsulation; underuse of association and containment.

Enter: Design Patterns

Elements of a design pattern: Name, purpose, solution framework (diagram, participants, relations), "forces" (constraints and consequences))

The main intention is not the primary modeling of the domain of the software application. First model, then review your needs, and restructure with design pattern.

Old vs new view on OO

  • Objects: smart data with methods vs entities with responsibities
    • Object may delegate execution of responsibilities, but remain responsible
  • Encapsulation: hide data vs hide anything
    • In particular, encapsulation should hide variation as much as possible.
  • Inheritance: used for variation vs used for classification
    • Using combinations of variation instead through containment
    • Re-use with decoupling and encapsulation
    • Inheritance is only used to classify variation.

Q: What is meant by saying that inheritance should only be used to classify variation?

Pattern thinking key phrases

Design to interfaces: concerns abstract structure, the internals of objects are an implementation and not a design matter.

Favour containment over inheritance: Association/Containment keeps objects hierarchically independent and makes independent specialization possible. So rather than A is a type of B (hierarchy), favour B uses A.

Q: Why is containment favoured over inheritance?

Find and encapsulate variation where it occurs (so localize it). Requires Communality and variability analysis.

Encapsulating Variation

Communality analysis: where do object vary (i.e. where are they the same)? Defines abstract classes.

Variability analysis: how do they vary? Defines derivations from abstract classes (and with patterns: a common functional specification on how to derive them).

Polymorphism

Specific types can be hidden under a more general type. You can use the general type without being concerned about the specific type that it also is.

E.g. a class calls a draw function on a "shape" object, but does not know whether the shape is a square or a circle, and neither does that matter. Each figure despite having multiple forms, can be drawn.

Low coupling/high cohesion

Versus aforementioned high coupling/low cohesion.

Weak coupling:

  • Independent object responsibilities
  • Changing one class, minimal impact on other classes

High cohesion: follows from weak coupling

  • Objects have a dedicated responsibility (or a few related ones), as much independent as possible
  • Similar objects should do similar things
  • Strong related responsibilities should be closer connected
    • In particular: objects should connect to object, modules to modules, but not objects to modules etc. i.e. interactions should have a clearly defined and separated scope.

Example: 8 queens problem

Each queen has a dedicated column, and needs to be in a row such that none of the other queens can attack her.

Naive solution: Treat the chess board as a data structure, and manipulate the data (e.g. search) until a solution is found. Just making the queens and the board objects is not yet a pure OO solution, because these objects would in this case still not have responsibilities, there a merely passive placeholders for data.

Objects without responsibility are no pure OO yet.

How to convert to a pure OO solution?

1) Give each object a specific independent responsibility (weak coupling). Each queen can be identified by her id number. The only responsibility she has is to find an appropriate row (which she has to ability to change). 2) Each queen only has to communicate with the immediate left neighbour. For queen n, assuming that the previous queens [1..n] already have been placed, her task is to find a row such that her left neighbour does not attack her. She can ask her left neighbour if her current position is safe, and her left neighbour can ask its left neighbour again recursively. 3) If no safe row can be found, the left neighbour needs to change its position, and continue the process from there etc. 4) Solution is found by asking the most right queen to place herself in a row, which starts a recursive communication process with the other queens.

Q implement an object oriented solution to the 8-queens problem.

Summary

  • More cohesion: encapsulated code that is easier to test
  • Loose coupling/encapsulated code: minimal interactions between code fragments, easier to maintain
  • Minimal redundancy: re-use through aggregation/containment, not inheritance
  • More readable: conceptually clear.

Lecture 7: Facade, Adapter, Proxy, Bridge, Strategy

@facade @adapter @proxy @bridge @strategy

Relation between Facade, Adapter, Proxy

All centered about one single specialized object only.

Facade and adapter have similar responsibilities: they are interfacers between other classes, translating messages.

  • Facade: provide a simplified/restricted interface
  • Adapter: make a fit/connection between** two existing interfaces**.

Proxy is different.

  • Proxy: add / change functionality of an existing interface.

Facade pattern

Facade pattern


Problem: you have an existing complex system that you need to access only in a particular way, or you need to simplify its use because it's badly designed.

Intent: Simplify use of the system by defining your own interface

Solution: Facade object

Participants: Facade object, client object, the existing system.

"Forces": simplified/restricted use of the of the system gives restricted functionality obviously.


Remarks:

1) Facade is not intended to make involved decisions itself, but ... 2) Facade may merge calls to the system in a single ordered call sequence/message 3) Facade may add default non-essential aspects, such as setting up a context

Variations:

  • Reduce number of collaborator classes client needs to deal with, even is a system is not complex.
  • Serve as an interface to several clients (and their joint needs).
  • Offer extension of missing functionality in the system
  • Encapsulate the whole system: decoupling + simplification.
  • Enforce one access route (handy for monitoring access).

Adapter Pattern

Adapter pattern


Problem: The client requires a particular interface (target), but the required functionality is already implemented in an existing class that unfortunately implements another interface. N.B. only one interface can be implemented at a time.

Intent: Match an object beyond your control to an existing interface. Convert one interface to another.

Solution: Adapter object wraps with the correct interface. The adapter implements the target interface, but it's method() call redirect to an existing function of the adaptee class, that uses another interface.

Participants: Adapter, adaptee, target with target interface, client.

Forces: Allows pre-existing objects to fit in imposed class hierarchies.


Proxy pattern


Problem: Offer an object to client without given direct access to it.

Intent: Control access

Solution: Provide a proxy objects as a surrogate stand-in for the actual object.

Participants: Proxy, real object, proxy and target (with target interface), client.


Proxy pattern

Similarity and difference with Adapter pattern?:

  • realObject is of the same interface as proxy.
  • There is thus no need to "adapt" one interface to another, such as in Adapter
  • And both proxy and realObject call the same method();

Remarks:

  • But although both proxy and realObject implement the same interface, the client only communicates with the proxy.
  • Proxy may replace some methods where a call to realObject is not necessary or possible.
  • Proxy may control/limit access to realObject
  • Proxy may add functionality to realObject.

Q: Can you draw UML diagram's of the Facade, Adapter and Proxy pattern?

Facade, Adapter, Proxy; remarks

These patterns are simple, but their differences are subtle, and they may be combined.

E.g. what is an object that translates between two existing interfaces (Adapter), but of which one interface is more simple (proxy?).

Bridge Pattern

Gang of four: "Decouple an abstraction from its implementation so that the two may very independently"

Deriving subclasses from parents using inheritance works, but the amount of classes explodes and it is hard to maintain.

So bridge pattern is useful when both an abstract classes responsibilities (abstraction) and what it actually does (implementation level) change often.


Problem: Derivations of an abstract class must use varying implementations but without class explosion.

Intent: Decouple set of implementations from set of objects using them.

Solution: Define an interface for all implementations. All derivations from the abstract class use that interface.

Participants:

1) Abstraction: defines interface for conceptual variations, maintains Implementor (interface) reference. 2) Implementor: defines interface of specific implementations 3) refinedAbstractions: derived from abstraction 4) concreteImplementors: the actual implementations.

Forces:

1) RefinedAbstraction objects use concreteImplementor objects without knowing which one. (Polymorphism?) 2) RefinedAbstraction objects are not aware of implementation issues 3) The use of decoupling increases extensibility.


Bridge Pattern

Remarks:

  • It does not really matter if an interface or abstract class is used for the abstraction.
  • Note that the use/containment relationship in the pattern is indicated between abstract classes. This is because all daughter classes have this relationship. So remember that the actual relationship is between objects of concrete classes, not the abstract classes.
  • When an abstraction, e.g. a shape "circle" is instantiated, its implementor object is assigned to it (composition).
  • But that object is not aware at all of what implementor version it uses.
  • Bridge is not perfect: it is possible that new refinedAbstractions violate the existing interface. The pattern assumes that each concrete implementation is contained in a concrete refined abstraction class. Moreover, they need to match: the refined abstraction class explicitly calls functionality of a particular implementation class (that might not be the current function?). (DOES THIS REASONING HOLD?)

Variations:

  • Can be used well with Adapters / Facade Q: How?
  • One conreteImplementation object might be shared by multiple refinedAbstraction objects, instead of being strictly contained by a refinedAbstraction object. This variation uses aggregration (the Wikipedia page assumes this in the first place).

Q: Why is the Bridge pattern often confused with the Adapter pattern?

A: I guess because it looks like two interfaces are linked, and the client only has access to the one. However, it is not the case that one interface merely is a link to another. There is a real separation of concerns between refinedAbstractions and implementations.

Bridge pattern Example Walkthrough (see my design pattern git repo for the example)

1) A client only has access to refinedAbstractions that extend the abstract class. This example has one: abstract class ShapeAbstraction, with draw() and resize() abstract voids. 2) Composition Each ShapeAbstraction has a final reference, received upon instantiation, to the Implementor interface. 3) The Implementor draws circles. That's just what it does and how it thinks of implementing shapes. 4) But it does not tell how to draw a circle (concrete implementation), that is defined in two different DrawingAPIs, 1 and 2. 5) On the highest abstraction level we have a Shape. Now we refine that abstraction by extending on Shape, and defining a CircleShape class. 6) Each refinedAbstraction is called with a final DrawImplementor drawingAPI, and calls super(drawingAPI) on instantiation, so that the abstract class has a reference to an implementor. This is required at the abstract Implementor level. 7) The client instantiates refinedAbstractions, registering them with a concreteImplementor. 8) The client calls for example the draw() function on whatever ShapeAbstraction object. It does need to know exactly which refinedAbstraction it calls, as they all have the draw function. 9) The draw function (cf. operation()) calls the intended operation of the associated concreteImplementor.

Code snippet:

/** "Client" */
class BridgePattern {
    public static void main(final String[] args) {
        ShapeAbstraction[] shapes = new ShapeAbstraction[] {
            new CircleShape(1, 2, 3, new DrawingAPI1()),
            new CircleShape(5, 7, 11, new DrawingAPI2())
        };

        for (ShapeAbstraction shape : shapes) {
            // operation done on abstract level, i.e. the same for all implementations
            shape.resizeByPercentage(2.5); 
            shape.draw();
        }
    }
}

Strategy Pattern

Goal: encapsulate variation in reasoning / algorithms.

When you design an algorithm and you see yourself doing if-else case distinctions to slightly change some logic (while the basic algorithm stays the same): then you can probably apply the strategy pattern. Make separate "Strategy" classes for those tactics, and have a Strategy object in your algorithm object.


Problem: A part of the logic of an algorithm depends on context. Pick the right logic for a given context, without making separate classes for context+logic variations.

Intent: Use different logic / algorithm depending on context.

Solution: Decouple algorithm selection from algorithm implementation. This selection is dependent on context.

Participants:

1) strategy: interface specifying the common part of different algorithms. 2) concreteStrategy: implements the Strategy interface with a specific strategy 3) context: uses a specific concreteStrategy through strategy interface. 4) client: initializes the context.

Forces:

1) The common Strategy interface defines a family of more specific algorithms. 2) This pattern eliminates switches and conditionals. 3) Concrete strategies must receive necessary information or be able to get it from somewhere. This is not directly part of the pattern.


Strategy Pattern

Remarks:

  • In my practice example, the situation is very simply so there is no bigger "context" class calling the strategies. But normally you have a problem doing something, with some class requiring the strategy and calling it.
  • Context may have various strategies. Context may call different concrete strategies at the same time, or one context may have a dedicated concrete strategy. The client sets up the context according to the client's own preferences.

Application to the car example: combining Bridge - Facade - Adapter

Requirements:

  • Have different types of remotes
  • Future remotes may have new functionality, code should be maintainable and extendable.
  • Different car brands implement remotes differently. These are incompatible.
  • New implementations are likely.

So two sources of variability: car manufacturer, remote implementations.

Car Example with patterns

1) Each CarModel has a Remote. 2) impCar is the implementor of the CarModel with the Remote (Bridge). Relation is composition. 3) Remote is an abstract class (Bridge): various remotes possible, each remote has a impCar reference (Composition). 4) Concrete remote types (Door, Alarm, Ignition) are refined abstractions from Remote. They are instantiated with a impCar: super(BMW, VW). 5) The BMW-modules are very complex apparently, so whatever action the remote does on a BMW, it will go through a Facade class (Facade pattern). 6) I think VM-remote applies the adapter pattern. Apparently the predefined VW class did not suit the needs of Volkswagen. Therefore they use the VW class (still abstract, I assume) as the adapter class, and VW-remote as the adaptee. (Adapter pattern?) 7) And... what does the CarModel class do?

Lecture 8: Factory Patterns

@factory

Abstract Factory Pattern

Consider the bridge factory and the issue that refined abstraction classes need to be matched up with an concrete implementation class. I.e. the bridge pattern requires 1) the creation of objects and 2) their correct use. And something can go wrong in their instantiation, so that their use is impacted. Solution: Create an appropriate factory!

Factories instantiate objects dependent on context.

1) Which concrete class to be instantiated? 2) Which specific initialization (out of possible) of an object? 3) BRIDGE: Consistent object sets that can work together. 4) Multiple instantiations vs sharing a single instance.

They decouple: factories only concern object creation, and not their use.

The fact that factories deal with creation does not mean that you design the factory before the objects; the opposite in fact!

Example situation: A system has various types of drivers. But due to capacity differences of systems, it depends on the capacity of the machine (context!) which quality of drivers needs to be used (high res vs. low res).

Important here is that although the actual drivers (high vs. low res) differ, their use should be the same in every system independent of their resolution.

Q: What pattern can be used to make the use of drivers uniform?

A: Facade, or Adapter.

Another way of saying that the use must be uniform, is that polymorphism must be used, the system works with driver types, despite their version / actual resolution.


Problem: Families of related objects needs to be instantiated.

Intent: Create sets of objects suitable for particular contexts

Solution: Take instantiation of objects away from the client, and put them in dedicated creation objects.

Participants:

1) abstractFactory: defines interface for family creation 2) concreteFactories create specific families 3) client asks abstractFactory for adequate object family and only uses this family / does not instantiate anything else himself.

Forces: Isolates rules of creation from rules of use.


Abstract Factory Pattern

The client only deals with product creation and usage on an abstract level.

The user asks the AbstractFactory for products. A concrete factory creates two products, one of the abstract type AbstractProductA, and one of the abstract type AbstractProductB. The client deals with products of "type A", without knowing if it's product A1 or A2 necessarily.

Abstract Factory Sequence Diagram

Remarks:

  • Is called abstract because the client only sees abstractions of classes, not because the factory pattern has an abstract mother class. Other factory patterns also have abstract classes.
  • Standard abstract factory does not take care of family selection. Typically, a configuration file is used for initialization of correct factories on system startup.

From Wikipedia:

The client doesn't know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.[1] This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

Variations:

  • A variation that does reason about family selection is possible.
    • Does not offer derived Factories, because that assumes fixed families
    • So objects have to be created in the general factory itself
    • Dynamic, but introduces tight coupling (why?)

Walkthrough Wikipedia Example (see my Design Patterns repo)

1) User only deals with abstract factory. 2) Family selection is in this case taken care of by a random process, randomly choosing between "OSX" or "Windows"-style buttons. 3) This context-dependent process selects a concrete factory. 4) Any function specified in the abstract factory can be called by the client

But the client thus has no knowledge of 1) which factory was selected, 2) or which specific object he is dealing with.

public class AbstractFactoryPattern {

    public static void main(final String[] arguments) throws Exception {
        GUIAbstractFactory factory = null;

        final String appearance = randomAppearance();   // Current operating system

        if (appearance.equals("OSX")) {
            factory = new OSXFactory();
        } else if(appearance.equals("Windows")) {
            factory = new WinFactory();
        } else {
            throw new Exception("No such operating system");
        }

        final Button button = factory.createButton();

        button.paint();
    }

Singleton pattern

  • Private constructor
  • Contains single instance of its own type
  • public getInstance() method

With lazy evaluation:

public class Singleton {
    public static getInstance() {
        if(instance==null)
            instance = new Singleton();
        return instance;
    }
}

Object pool pattern


Problem: Manage re-use of limited set of object instances

Solution: Client requests resource from the object pool. Object-pool returns a reference to the resource if one is free. Otherwise, put client on hold and notify later when a resource has become available.


Object Pool Pattern

Remarks:

  • The pool must be a singleton

Prototype pattern


Problem: Objects must be created by cloning instead of construction (either its data is needed again, or object creation is expensive etc.)

Solution: Offer interface for abstract clone method. The prototype is a cloneable class, implementing the clone interface. The client has a polymorph set of prototypes. Call to prototype.clone() returns reference to new clone.


Prototype pattern

N.B. In Java there is a predefined interface Cloneable, can be used instead of Prototype.

Builder pattern


Problem: Complex object creation must be decoupled from specification (?). Metaphor: there are basic requirements for building a house, and different types of houses can be built that conform to those specifications.

Participants:

1) Director: manages sequence of object creation, by receiving concrete builders and letting them do their job; returns finished object. 2) Builder: interface for building part of an object; returns finished object. 3) Concrete builder: specification-dependent implementation for Builder.


Builder Pattern

Lecture 9: Strategy Relatives: Decorator, Template Method, Factory Method

@decorator @template

Decorator Pattern

Goal is to dynamically extend object functionality. Example application: see the "billing" example as I implemented it in my repo.

Decorator pattern


Problem: You have a object with a basic functionality, but may (later) need to add functionality before or after this function.

Intent: Add extra responsibilities depending on the context

Solution: Do not subclass but chain modules instead. Select the chain based on context (in whatever order).

Participants:

1) concreteComponent: contains kernel functionality 2) concreteDecorator: wrap around kernel to add functionality 3) decorator: abstract class defining the call chain (with successor reference) 4) component: common interface for using the whole chain

Forces:

1) Client only knows the overall functionality, not constituent components 2) The chaining of decorators is a layering, not a sequence. See the figure with the "recursive" setup. 3) Order of selection between decorators is free, but the function sequence of "before and after" decorators is not free. 4) Factory or alike needed to set up the whole chain of decorators.


Differences with Strategy- and Decorator pattern

The strategy pattern specifies alternate behavior at fixed points, at any place in the algorithm, and each alternate behavior consists of exactly one variation.

On the other hand, with the decorator you can vary the amount and sequence of added behavior, but not at any place; constraint is that it must be before or after a kernel algorithm. Whereas strategy has one "slot" per added behavior, decorator an combine various added behaviors.

How does the decorator pattern work?

N.B. Similar to recursion:

  • Have a kernel functionality ("base case")
  • and encapsulate all added functionality is separate concrete "decorator" classes.
  • Each decorator calls next decorator
  • Except the last one: calls the basic kernel.

The "outermost" decorator is the first object in the decorator chain, and the last object is the "innermost" kernel.

That means that the calling order in the chain is not equal to execution order of functionality. See figure.

The creational order is: from inside to outside, so starts with the kernel functionality, then creates the wrappers.

The calling order starts with the outer wrapper, performing the pre-command, until the basic functionality is reached. After that, if necessary, all wrappers can still perform some clean up / set up, whatever.

Decorator "recursive" structure

Decorator calling order

Requirements and design

1) Encapsulate decorator and kernel modules

Solution: make them all separate classes.

2) Have a way to chain decorators and kernel together, in whatever order (but kernel last).

Each concrete decorator should be derived from an abstract class that has an embedded successor object. The kernel should have no successor. There must thus also be a general class-type for both decorator and kernel functionality (Component in the UML).

3) A common interface to call the chain

This is provided by the abstract class generalizing both decorator and kernel functionality.

4) The kernel functionality must be usable on its own

The restriction that there can be only one kernel. So by definition it must be called, even without decorators.

5) Hide from clients how the basic functionality is decorated

Use polymorphism to access the objects on an abstract level.

Remarks and variations

  • The cursive call off the next component is done by a decorator, i.e. each concreteDecorator calls its successor indirectly via super.operation()
    • See VARIATION below
  • Decorator is an example of localized sequential control
    • Meaning, I assume, that the chaining is done by decorators themselves (i.e. the "recursive" strategy) rather than by an overarching class imperatively declaring the steps.
  • It is allowed to add a state to a decorator, if this is for example needed by both the before and after operations
  • The "before" and "after" functionality can also be pre- and post-tests. So decorator can be useful for testing untrusted objects.
  • VARIATION: you could let concrete decorators themselves take care of doing the work for their parent (parentComponent.someFunction()), instead of indirectly calling super(thisComponent) and then execute functionality in the abstract class. This requires then of course the component of the parent abstract class to be defined protected instead of private.
    • This is less safe: daughter classes can mess with the parent component, and mess up the pattern
    • Tight coupling: All your code now has an explicit reference to the component name as defined in the abstract decorator class. This means that if that name changes, you need to refactor all concrete decorators...
    • So although it is more straightforward conceptually, maybe do not do it...

Template pattern

Pattern for when a procedure is the same every time, but not the code itself. E.g. connecting to a database. Always: 1) Construct connect command, 2) Send the command, 3) Construct select command, 4) Send select command, 5) Return.

But for different SQL types, the actual code will be different, although the backbone procedure is exactly the same.

Neither Bridge, nor Strategy, nor Decorator applies:

  • No Bridge: there is no "abstract" side with polymorphic concepts with varying implementations. E.g. the "connect" step in the example procedure in all cases correspond to a single concrete command that is just slightly different.
  • No strategy: There are no freely switchable strategies. There usually is tight coupling naturally in these problems. Let's say apply the template for SQLite: then all steps in the template will be in the SQLite dialect. You cannot use regular SQL for one step, and then SQLite for the other. In other words: this coupling is normal in this case. This is why the template pattern is based on inheritance, rather than containment (like strategy).
    • So steps do not vary independently, but are dependent on the template choice. If they do vary independently, use strategy pattern.
  • No decorator: there are no additions to the procedure, simply different variations in its execution.

Problem: Common procedure for multiple processes, but individual steps differ in execution.

Intent: Define overall and shared backbone of algorithms in a general class, and defer differing details to subclasses.

Solution: Backbone defined in abstract class, varying steps in concrete subclasses.

1) abstractClass: defines basic template method and declares abstract methods for all steps in the template that might differ for subclasses 2) concreteClass: implements varying steps. 3) client: calls the template method without having to deal with details.

Forces:

  • Avoids code redunancy
  • Platform for code reuse
  • Ensures all steps are implemented
  • Step variations are bound within the same concrete class (again no independent variation of individual steps, like with strategy)
  • Pattern does not prescribe what concrete class to use, that is e.g. up to the client to decide.

Template pattern

Factory method pattern

Template method used as a factory, where some of the template steps produce objects.


Problem: A class needs to instantiate a derivation of another class (?) but does not know which derivation. E.g. we have products, but some are shipped over sea and others over land, and this requires slightly different properties from them.

Intent: Define an interface for creating an object, but let subclasses decide which concrete class to instantiate and how to initialize the object.

Solution: Abstract class contains the abstract creation method, derived classes redefine / refine / define the creation method. (Template!)

1) Creator: interface for object creation 2) concreteCreator: contains actual object code 3) Product: interface for the type of object created 4) concreteProduct: concrete class that is instantiated

Forces: Client of some factory has to establish which concrete creator to be used.


Factory Method Pattern

Remarks:

  • Heavily used in libraries
  • E.g. Java iterator() method of Collections: 1) Abstract iterator() in interface Collection returns generic iterator 2) Actual iterator is created by specific collection type (derived class). 3) Client uses this specific actual iterator as created by the generic interface.
  • As compared to the abstract factory class, there is a little less emphasis on actually creating objects. The object creation logic is often already present in pre-existing "creator" classes.
  • Note that the factoryMethod must return something of the type product. The return of the creator template has to be of type Product, whatever concreteCreator is used.

Lecture 10: Library and Multithreading patterns: Observer - Iterator - Multithreading

@library @multithreading @observer @iterator

Observer pattern

Situation: various classes must be up to date about changes in some class. This class must "broadcast" its changes to classes "observing" it. This is especially handy for decentralized control regimes where different classes must stay up to date after events in some class (but can of course also still be used with centralized control).

An example of such an event-driven control regime is a GUI: After a user action, all graphical objects must be notified of the user event. (Observer natively works best with MVP).

In this pattern, responsibility for 1) being notified by registering themselves with the observable, and 2) what actions are then required all lies with the observer, and not with the observed class.

Observer pattern


Forces:

1) observable subject is only responsible for event detection and broadcasting / notifying 2) it is possible that concreteObservers are notified of events they don't care about 3) If concreteObservers require more information they need to request it 4) Adapters may be needed to make concreteObservers conform to the common interface, i.e. the observer interface. I guess when the observer is already a pre-written class that implements another interface.


Remarks:

  • Observer not appropriate for any 1:n dependency. Only use it when the set of dependents is not fixed or context-dependent. Otherwise you can just use fixed containment.

Variations:

  • Filter out irrelevant info. The observable subject can filter out irrelevant info in its updates, but the observer needs to communicate what is irrelevant first.
    • For this the observable can use the strategy pattern: then the observer can simply pass an appropriate strategy for itself when attaching to the observable.
  • Subject may also by default pass extra information in update calls. Again the strategy pattern can be used by observers to filter out information they do not need.

Iterator pattern

Relation with factory method pattern?


Problem: Perform similar operations on various collection types. You do not want to rewrite similar code for each collection type (e.g. array, vs list).

Intent: Access a collection object without exposition underlying representation.

Solution:

1) Encapsulate access methods in concrete iterator objects, instead of being a method of the concrete collection object itself 2) Provide general interfaces Collection and Iterator. 3) Let the client only use the general iterator interface.

Participants:

1) Collection: general interface that references to a usable iterator 2) concreteCollection: contains the actual collection data and knows which type of concreteIterator to make. 3) Iterator: general interface for operations on collections 4) concreteIterator: performs actual operations on concreteCollection.

Forces:

  • Client does not need to know specific collection type, can just use iterator on whatever type because the concreteCollection knows what iterator to use.
  • Client is limited to operations that are valid for all collections due to the shared interface design.
  • concreteCollections must create concreteIterator objects.

Iterator pattern

Remarks:

  • Adding elements to a collection is not the task of the iterator but should be done in the abstract Collection class itself. Problem: adding an element invalidates all existing iterators.
  • Some Iterator implementations (e.g. in Java) can remove elements from a collection; this will not invalidate the iterator.

Variations:

  • Collections can be used with more iterators
  • There might be different levels of generalisations between iterators and collections, e.g. one iterator with functionality that collections A-M share, and another for collections N-Z that share more extensive functionality.
    • But.. now the client needs to know about the type of iterator/collection.
    • Ugly fix: define all functionality of all possible iterators in abstract base class, and let them all throw an exception. In derived concreteIterator classes, you override the functions you want to enable.

Multithreading

In Java, use the Runnable interface with run() method, for classes that can be run in parallel. The Thread class can be instantiated with a Runnable, and the thread can be started with thread.start(). However, usually an ExecutorService is used to manage Runnables, as such:

    import java.util.concurrent.Executors
    import java.util.concurrent.ExecutorService

    public class MyExecutor {
        public static void main( String[] args ) {
            MyRunnableClass task1 = new MyRunnableClass();
            MyRunnableClass task2 = new MyRunnableClass();
            ExecutorService MyThrRunner = Executors.CachedNewThreadPool();
            MyThrRunner.execute( task1 ); // start task1 & continue
            MyThrRunner.execute( task2 ); // start task2 & continue
            MyThrRunner.shutdown(); // stop accepting new tasks
                                    // (but started tasks keep running)
    } // end main
    } // end class

Thread states

Thread states: New, Runnable, Waiting, Timed waiting, Blocked, Terminated.

  • Waiting: thread.wait()
    • Activate again with notify() or notifyAll()
  • Timed waiting: same, but with max time to wait
    • thread.wait(
  • Blocked
    • by another thread in a synchronized method, or synchronized code block.

Synchronization

Important detail: when a synchronized method is reached, every synchronized method in that object is blocked for other threads, not only that method. I.e. the object is locked, not only the method.

This means that a synchronized static method will lock the entire class object, since it concerns the access of the class as such irregardless of a particular instance of that class.

This can cause significant decrease in performance.

You can also synchronize only a block of code instead of a whole method, for performance reasons. The following are equivalent (since there is no unsynchronized code outside the code block in this case):

public class MyClass {

    public synchronized void log1(String msg1, String msg2){
       log.writeln(msg1);
       log.writeln(msg2);
    }


    public void log2(String msg1, String msg2){
       synchronized(this){
          log.writeln(msg1);
          log.writeln(msg2);
       }
    }
  }

A thread is locked on a particular object, which in case of the code block is made explicit. Because the code block is synchronized on this instance, a thread in this instance can not run in these two methods as the same time. If log1 would be a static method, it would lock the class object, and the synchronized block should then be locked on the class MyClass.class as well. (Is that really required? Maybe it is implied.)

Moreover, deadlock can occur.

Deadlock and Guarded Suspension

Situation: synchronized method A tries to get an element from an empty stack. Synchronized method B tries to push an element onto the stack, but is blocked by method A. Result: Deadlock, because method A will never succeed and allow B to push, while clearly the push of B would solve the deadlock.

Guarded suspension:

W.r.t. the previous example, the solution would be to make thread A wait if the object state is not suitable to pull. Thread A should however be awoken from its waiting state after object state has changed into the proper one, which in this case is when B pushes something on the stack.

class GuardedSuspension {
    public synchronized void pullFromStack(){
        while(stack.isEmpty()){
            wait();
        }

    public synchronized void pushOnStack(){
        stack.push(something);
        notifyAll();
    }
    }
}

The method notify() awakes one arbitrary thread, whereas notifyAll() awakes all threads that all may acquire the lock; OS takes care of priority/ordering.

When does guarded suspension fail?

If the guarded synchronized methods are themselves called from a synchronized method in the same "calling object", which would be the class instance I suppose. In that case method B, although guarded, can still not be called because the whole instance owns the lock now.

Balking

Do not wait for a process if any thread is already doing it. This is only appropriate if is it no problem to do nothing in an incorrect state. This avoid waiting unnecessarily, by never trying to perform a non-sensible task in the first place.

boolean busy;

int doIt() {
    synchronized( this ) {
        if( busy )
            return 0; // meaning “balked”
        busy = true;
        }
    // code to make doIt happen goes here
    busy = false;
return 1; // meaning “has executed”
}

The crux is in the busy check: if another thread is already performing this, the instance boolean will be set to true, and the other thread will simply skip that step.

N.B. if the inappropriate action consist in something other than the fact that it is already occupied by another thread doing that same task, the entire method should be synchronized. Why exactly?

Producer-consumer

Goal: coordinate asynchronous production and consumption of data. E.g. it should be able to enter a print job even if prints are busy. The printer will print the print job later when it has time.

Basically: the concurrent buffer I implemented in the Object Orientation course. Three ingredients:

1) Synchronized buffer: push/pull clashes need to be prevented. 2) If buffer full, production threads wait, and consumption thread notifies. 3) If buffer is empty, the consumption thread waits, and the production thread notifies.

Two-phase termination

Do not directly terminate threads, but allow them to do some clean up in an orderly way before terminating.

Solution:

1) Use a interruptedRequest boolean in the thread. 2) Instead of hard closing the thread, request interruption 3) The thread regularly checks if the boolean thread is set 4) If it set, the thread cleans up resources etc. and closes itself.

Thread.sleep in Java e.g. throws an InterruptedException: you can catch this for clean up tasks.

History · 9 changes since 2019-01-21

Full changelog