Html/Javascript widget

Saturday 24 September 2022

Visitor

The visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures. It is one way to follow the open/closed principle.
In essence, the visitor allows adding new virtual functions to a family of classes, without modifying the classes. Instead, a visitor class is created that implements all of the appropriate specialisations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.

Overview

    What problems can the Visitor design pattern solve?
  • It should be possible to define a new operation for (some) classes of an object structure without changing the classes.
  • When new operations are needed frequently and the object structure consists of many unrelated classes, it's inflexible to add new subclasses each time a new operation is required because "[..] distributing all these operations across the various node classes leads to a system that's hard to understand, maintain, and change."

      What solution does the Visitor design pattern describe?
    1. Define a separate (visitor) object that implements an operation to be performed on elements of an object structure.
    2. Clients traverse the object structure and call a dispatching operation accept (visitor) on an element — that "dispatches" (delegates) the request to the "accepted visitor object". The visitor object then performs the operation on the element ("visits the element").

This makes it possible to create new operations independently from the classes of an object structure by adding new visitor objects.

Template method

The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.

Overview

This pattern has two main parts:

The "template method" is implemented as a method in a base class (usually an abstract class). This method contains code for the parts of the overall algorithm that are invariant. The template ensures that the overarching algorithm is always followed. In the template method, portions of the algorithm that may vary are implemented by sending self messages that request the execution of additional helper methods. In the base class, these helper methods are given a default implementation, or none at all (that is, they may be abstract methods).
Subclasses of the base class "fill in" the empty or "variant" parts of the "template" with specific algorithms that vary from one subclass to another. It is important that subclasses do not override the template method itself.
At run-time, the algorithm represented by the template method is executed by sending the template message to an instance of one of the concrete subclasses. Through inheritance, the template method in the base class starts to execute. When the template method sends a message to self requesting one of the helper methods, the message will be received by the concrete sub-instance. If the helper method has been overridden, the overriding implementation in the sub-instance will execute; if it has not been overridden, the inherited implementation in the base class will execute. This mechanism ensures that the overall algorithm follows the same steps every time, while allowing the details of some steps to depend on which instance received the original request to execute the algorithm.

Strategy

The strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
Strategy lets the algorithm vary independently from clients that use it. Strategy is one of the patterns included in the influential book Design Patterns by Gamma et al. that popularized the concept of using design patterns to describe how to design flexible and reusable object-oriented software. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.
For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known until run-time and may require radically different validation to be performed. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.

State

The state pattern is a behavioral software design pattern Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.
The state pattern is used in computer programming to encapsulate varying behaviour for the same object , based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.
    The state pattern is set to solve two main problems:
  1. An object should change its behavior when its internal state changes.
  2. State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states.

Implementing state-specific behavior directly within a class is inflexible because it commits the class to a particular behavior and makes it impossible to add a new state or change the behavior of an existing state later, independently from the class, without changing the class.

    In this, the pattern describes two solutions:
  • Define separate (state) objects that encapsulate state-specific behavior for each state. That is, define an interface (state) for performing state-specific behavior, and define classes that implement the interface for each state.
  • A class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly.

This makes a class independent of how state-specific behavior is implemented. New states can be added by defining new state classes. A class can change its behavior at run-time by changing its current state object.

Friday 23 September 2022

Observer pattern

The observer pattern is a behavioral software design pattern Chain of responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template method Visitor in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes , usually by calling one of their methods.

Which problems can the Observer design pattern solve?


    The Observer pattern addresses the following problems:
  1. A one-to-many dependency between objects should be defined without making the objects tightly coupled.
  2. It should be ensured that when one object changes state, an open-ended number of dependent objects are updated automatically.
  3. It should be possible that one object can notify an open-ended number of other objects.
Defining a one-to-many dependency between objects by defining one object (subject) that updates the state of dependent objects directly is inflexible because it couples the subject to particular dependent objects. Still, it can make sense from a performance point of view or if the object implementation is tightly coupled (think of low-level kernel structures that execute thousands of times a second). Tightly coupled objects can be hard to implement in some scenarios, and hard to reuse because they refer to and know about (and how to update) many different objects with different interfaces. In other scenarios, tightly coupled objects can be a better option since the compiler will be able to detect errors at compile-time and optimize the code at the CPU instruction level.
    What solution does the Observer design pattern describe?
  • Define Subject and Observer objects.
  • so that when a subject changes state, all registered observers are notified and updated automatically (and probably asynchronously).
The sole responsibility of a subject is to maintain a list of observers and to notify them of state changes by calling their update() operation. The responsibility of observers is to register (and unregister) themselves on a subject (to get notified of state changes) and to update their state (synchronize their state with the subject's state) when they are notified.

Thursday 22 September 2022

Memento

The memento pattern is a behavioural design pattern Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor that exposes the private internal state of an object. One example of how this can be used is to restore an object to its previous state (undo via rollback), another is versioning, another is custom serialization.
The memento pattern uses three objects: the originator, a caretaker and a memento. The originator is some object with an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources—the memento pattern operates on a single object.
    What problems can the Memento design pattern solve?
  1. The internal state of an object should be saved externally so that the object can be restored to this state later.
  2. The object's encapsulation must not be violated.

The problem is that a well designed object is encapsulated so that its representation (data structure) is hidden inside the object and can't be accessed from outside the object.

    What solution does the Memento design pattern describe? Make an object (originator) itself responsible for
  • saving its internal state to a (memento) object and
  • restoring to a previous state from a (memento) object.

Only the originator that created a memento is allowed to access it.

A client (caretaker) can request a memento from the originator (to save the internal state of the originator) and pass a memento back to the originator (to restore to a previous state).

Monday 19 September 2022

Mediator

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioural pattern Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template, method, Visitor due to the way it can alter the programme's running behavior.
With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling.

Overview

    What problems can the Mediator design pattern solve?
  1. Tight coupling between a set of interacting objects should be avoided.
  2. It should be possible to change the interaction between a set of objects independently.
Defining a set of interacting objects by accessing and updating each other directly is inflexible because it tightly couples the objects to each other and makes it impossible to change the interaction independently from (without having to change) the objects. And it stops the objects from being reusable and makes them hard to test.
    What solution does the Mediator design pattern describe?
  • Define a separate (mediator) object encapsulating the interaction between a set of objects.
  • Objects delegate their interaction to a mediator object instead of interacting with each other directly.
The objects interact with each other indirectly through a mediator object that controls and coordinates the interaction. This makes the objects loosely coupled. They only refer to and know about their mediator object and have no explicit knowledge of each other.

Saturday 17 September 2022

Iterator

The iterator pattern is a behavioural design pattern Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers.
For example, the hypothetical algorithm SearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows SearchForElement to be used on any container that supports the required type of iterator.

Overview

    What problems can the Iterator design pattern solve?
  1. The elements of an aggregate object should be accessed and traversed without exposing its representation.
  2. New traversal operations should be defined for an aggregate object without changing its interface.
    What solution does the Iterator design pattern describe?
  • Define a separate (iterator) object that encapsulates accessing and traversing an aggregate object.
  • Clients use an iterator to access and traverse an aggregate without knowing its representation.

Different iterators can be used to access and traverse an aggregate in different ways.

Tuesday 13 September 2022

Interpreter

The interpreter pattern is a behavioural design pattern Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialised computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.

Overview

    What problems can the Interpreter design pattern solve?
  1. A grammar for a simple language should be defined
  2. so that sentences in the language can be interpreted.

When a problem occurs very often, it could be considered to represent it as a sentence in a simple language (Domain Specific Languages) so that an interpreter can solve the problem by interpreting the sentence.

    What solution does the Interpreter design pattern describe?
  • Define a grammar for a simple language by defining an Expression class hierarchy and implementing an interpret() operation.
  • Represent a sentence in the language by an abstract syntax tree (AST) made up of Expression instances.
  • Interpret a sentence by calling interpret() on the AST.

The Interpreter pattern doesn't describe how to build an abstract syntax tree. This can be done either manually by a client or automatically by a parser.

Command

In object-oriented programming, the command pattern is a behavioral design pattern Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.
Four terms always associated with the command pattern are command, receiver, invoker and client. A command object knows about the receiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command. The receiver object to execute these methods is also stored in the command object by aggregation. The receiver then does the work when the execute() method in command is called. An invoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about the command interface. Invoker object(s), command objects and receiver objects are held by a client object, the client decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.

Overview

    Using the command design pattern can solve these problems:
  1. Coupling the invoker of a request to a particular request should be avoided. That is, hard-wired requests should be avoided.
  2. It should be possible to configure an object (that invokes a request) with a request.

Implementing (hard-wiring) a request directly into a class is inflexible because it couples the class to a particular request at compile-time, which makes it impossible to specify a request at run-time.

    Using the command design pattern describes the following solution:
  • Define separate (command) objects that encapsulate a request.
  • A class delegates a request to a command object instead of implementing a particular request directly.

This enables one to configure a class with a command object that is used to perform a request. The class is no longer coupled to a particular request and has no knowledge of how the request is carried out.

Sunday 11 September 2022

Proxy

The proxy pattern is a strucutral patternadapter, bridge, composite, decorator, facade, flyweight, proxy , where a class functions as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.
    What problems can the Proxy design pattern solve?
  1. The access to an object should be controlled.
  2. Additional functionality should be provided when accessing an object.

When accessing sensitive objects, for example, it should be possible to check that clients have the needed access rights.

    What solution does the Proxy design pattern describe?
  • Define a separate Proxy object that
  • can be used as substitute for another object (Subject) and
  • implements additional functionality to control the access to this subject.

This makes it possible to work through a Proxy object to perform additional functionality when accessing a subject. For example, to check the access rights of clients accessing a sensitive object.

To act as substitute for a subject, a proxy must implement the Subject interface. Clients can't tell whether they work with a subject or its proxy.

Flyweight

The flyweight software design pattern is a structural pattern adapter, bridge, composite, decorator, facade, flyweight and proxy that refers to an object that minimises memory usage by sharing some of its data with other similar objects.

Overview

The flyweight pattern is useful when dealing with large numbers of objects with simple repeated elements that would use a large amount of memory if individually stored. It is common to hold shared data in external data structures and pass it to the objects temporarily when they are used.
A classic example are the data structures used representing characters in a word processor. Naively, each character in a document might have a glyph object containing its font outline, font metrics, and other formatting data. However, this would use hundreds or thousands of bytes of memory for each character. Instead, each character can have a reference to a glyph object shared by every instance of the same character in the document. This way, only the position of each character needs to be stored internally.
    As a result, flyweight objects can:
  1. store intrinsic state that is invariant, context-independent and shareable (for example, the code of character 'A' in a given character set)
  2. provide an interface for passing in extrinsic state that is variant, context-dependent and can't be shared (for example, the position of character 'A' in a text document)

Clients can reuse Flyweight objects and pass in extrinsic state as necessary, reducing the number of physically created objects.

Saturday 10 September 2022

the Facade design pattern

The facade pattern (or façade) is a structural pattern Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy analogous to a facade in architecture; an object that serves as a front-facing interface masking more complex underlying or structural code. A facade can:
  • improve the readability of a library by masking interaction with more complex components behind a single API
  • provide a context-specific interface to more generic functionality
  • serve as a launching point for a broader refactor of monolithic or tightly-coupled systems in favor of more loosely-coupled code
Developers often use the facade design pattern when a system is very complex or difficult to understand because the system has many interdependent classes or because its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class that contains a set of members required by the client.

Overview

Problems can the Facade design pattern solves

  1. To make a complex subsystem easier to use, a simple interface should be provided for a set of interfaces in the subsystem.
  2. The dependencies on a subsystem should be minimised.
A Facade is used when an easier or simpler interface to an underlying object is desired. Alternatively, an adapter can be used when the wrapper must respect a particular interface and must support polymorphic behaviour.

Friday 9 September 2022

Decorator

The decorator pattern is a structural pattern Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern. Decorator use can be more efficient than subclassing, because an object's behaviour can be augmented without defining an entirely new object.

Overview

    What problems can it solve?
  • Responsibilities should be added to (and removed from) an object dynamically at run-time.
  • A flexible alternative to subclassing for extending functionality should be provided.
    Define Decorator objects that
  1. implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it
  2. perform additional functionality before/after forwarding a request.
This allows working with different Decorator objects to extend the functionality of an object dynamically at run-time.

Wednesday 7 September 2022

Composite

The composite pattern is a partitioning design pattern, describing a group of objects that are treated the same way as a single instance of the same type of object . The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Overview

    What problems can the Composite design pattern solve?
  • A part-whole hierarchy should be represented so that clients can treat part and whole objects uniformly.
  • A part-whole hierarchy should be represented as tree structure.
    What solution does the Composite design pattern describe?
  1. Define a unified Component interface for both part (Leaf) objects and whole (Composite) objects.
  2. Individual Leaf objects implement the Component interface directly, and Composite objects forward requests to their child components.

This enables clients to work through the Component interface to treat Leaf and Composite objects uniformly: Leaf objects perform a request directly, while Composite objects forward the request to their child components recursively downwards the tree structure. This makes client classes easier to implement, change, test and reuse.

Tuesday 6 September 2022

Bridge Pattern

The bridge pattern is a design pattern used meant to "decouple an abstraction from its implementation so that the two can vary independently" . The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class and what it does vary often. The class itself can be thought of as the abstraction and what the class can do as the implementation. The bridge pattern can also be thought of as two layers of abstraction.

A Variant of this pattern is an implementation that can be decoupled even more by deferring the presence of the implementation to the point where the abstraction is utilized.

Overview

    problems that the Bridge design pattern can solve
  • An abstraction and its implementation should be defined and extended independently from each other.
  • A compile-time binding between an abstraction and its implementation should be avoided so that an implementation can be selected at run-time.
    What solution does the Bridge design pattern describe?
  1. Separate an abstraction (Abstraction) from its implementation (Implementor) by putting them in separate class hierarchies.
  2. Implement the Abstraction in terms of (by delegating to) an Implementor object.

Monday 29 August 2022

Adapter

The adapter pattern is a structural pattern Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface.
    The adapter design pattern solves problems like:
  • How can a class be reused that does not have an interface that a client requires?
  • How can classes that have incompatible interfaces work together?
  • How can an alternative interface be provided for a class?
    The adapter design pattern describes how to solve such problems:
  1. Define a separate adapter class that converts the (incompatible) interface of a class (adaptee) into another interface (target) clients require.
  2. Work through an adapter to work with (reuse) classes that do not have the required interface.

The key idea in this pattern is to work through a separate adapter that adapts the interface of an (already existing) class without changing it.

Sunday 28 August 2022

Singleton

The singleton creational pattern Abstract factory, Builder, Factory method, Prototype, Singleton restricts the instantiation of a class to one "single" instance so only one object is needed to coordinate actions across the system.

Overview

The singleton design pattern is one of the twenty-three well-known "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software with the aim of making it easier to implement, change, test, and reuse objects.
    The singleton design pattern solves problems by allowing it to:
  1. Ensure that a class only has one instance
  2. Easily access the sole instance of a class
  3. Control its instantiation
  4. Restrict the number of instances
  5. Access a global variable
    The singleton design pattern describes how to solve such problems:
  • Hide the constructors of the class.
  • Define a public static operation (getInstance()) that returns the sole instance of the class.
In essence, the singleton pattern forces it to be responsible for ensuring that it is only instantiated once. A hidden constructor-declared private or protected- ensures that the class can never be instantiated from outside the class. The public static operation can be accessed by using the class name and operation name, e.g., Singleton.getInstance().

Saturday 27 August 2022

Prototype

The prototype pattern is a creational design pattern Builder, Abstract factory, Factory method, Prototype, Singleton used when the type of objects to create is determined by a prototypical instance, cloned to produce new objects. This pattern is used to avoid subclasses of an object creator in the client application, like the factory method pattern does and to avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

To implement the pattern, the client declares an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.

The mitotic division of a cell - resulting in two identical cells - is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.

Overview

    The prototype design pattern solves problems like:
  • How can objects be created so that which objects to create can be specified at run-time?
  • How can dynamically loaded classes be instantiated?

Creating objects directly within the class that requires the objects is inflexible because it commits the class to particular objects at compile-time and makes it impossible to specify which objects to create at run-time.

    The prototype design pattern describes how to solve such problems:
  1. Define a Prototype object that returns a copy of itself.
  2. Create new objects by copying a Prototype object.

This enables configuration of a class with different Prototype objects, which are copied to create new objects. Prototype objects can be added and removed at run-time.

Friday 26 August 2022

Factory Method

Factory method is a abstract factory, builder, factory method, prototype and singleton. creational pattern that uses factory methods to creat objects without specifying the exact class of the object being created. This is done by creating objects by calling a factory method- either specified in an interface and implemented by child classes or implemented in a base class and optionally overridden by derived classes- rather than by calling a constructor.

The Factory Method design pattern solves problems like:

  • How can an object be created so that subclasses can redefine which class to instantiate?
  • How can a class defer instantiation to subclasses?

The Factory Method design pattern describes how to solve such problems:

  • Define a separate operation (factory method) for creating an object.
  • Create an object by calling a factory method.

This enables writing of subclasses to change the way an object is created.

Definition

Defines an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses.

The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.

Thursday 25 August 2022

Builder

The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming.

The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.

Overview

The Builder design pattern solves problems like:

  • How can a class create different representations of a complex object?
  • How can a class that includes creating a complex object be simplified?
Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class.

The Builder design pattern describes how to solve such problems:

  • Encapsulate creating and assembling the parts of a complex object in a separate Builder object.
  • A class delegates object creation to a Builder object instead of creating the objects directly.

A class can delegate to different Builder objects to create different representations of a complex object.

Wednesday 24 August 2022

Abstract Factory

The abstract factory pattern allows to encapsulate a set of individual factories with a common theme without specifying their concrete classes.

The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes.


The client software would usually create a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only their generic interfaces. 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.

A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes. This allows for new derived types to be introduced with no change to the code that uses the base class.

Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime.

The Abstract Factory design pattern solves problems like:

  • How can an application be independent of how its objects are created?
  • How can a class be independent of how the objects it requires are created?
  • How can families of related or dependent objects be created?

The Abstract Factory design pattern describes how to solve such problems:

Encapsulate object creation in a separate (factory) object. That is, define an interface (AbstractFactory) for creating objects, and implement the interface.

A class delegates object creation to a factory object instead of creating objects directly.

Tuesday 23 August 2022

Chain of Responsibility

In design pattern, chain-of-responsibility pattern is a behavioral design pattern consisting of command objects and processing objects, each logic defining the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also adds new processing objects to the end of this chain.

This pattern promotes the idea of loose coupling.

The chain-of-responsibility pattern is nearly identical to the decorator pattern, the difference being that for the decorator, all classes handle the request, while for the chain of responsibility, exactly one of the classes in the chain handles the request .

Overview

The Chain of Responsibility design pattern is one of the twenty-three well-known GoF design patterns that describe common solutions to recurring design problems when designing flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

What problems can the Chain of Responsibility design pattern solve?

  • Coupling the sender of a request to its receiver should be avoided.
  • It should be possible that more than one receiver can handle a request.
Implementing a request directly within the class that sends the request is inflexible because it couples the class to a particular receiver and makes it impossible to support multiple receivers.

The solution that the Chain of Responsibility design pattern describes is for defining a chain of receiver objects having the responsibility, depending on run-time conditions, to either handle a request or forward it to the next receiver on the chain.

This enables us to send a request to a chain of receivers without having to know which one handles the request. The request gets passed along the chain until a receiver handles the request. The sender of a request is no longer coupled to a particular receiver.

Friday 19 August 2022

Observer

The observer pattern is a software design pattern in which an object, the subject,keeps a list of its dependents, called observers, notifying them automatically of any state changes, usually by calling one of their methods.

It is mainly used for implementing distributed event handling systems, in "event driven" software, where the subject is usually named a "stream of events" or "stream source of events", while the observers are the "sinks of events". This pattern then perfectly suits any process where data arrives from some input that is not available to the CPU at startup, but instead arrives "at random" (HTTP requests, GPIO data, user input from keyboard/mouse/..., distributed databases and blockchains, ...). While not mandatory, most 'observers' implementations would use background threads listening for subject-events and other support mechanisms provided by the kernel (Linux epoll, ...).

Overview

The Observer design pattern is a behavioural pattern, among the twenty-three well-known "Gang of Four" design patterns describing how to solve recurring design challenges in order to design flexible and reusable object-oriented software, i.e. objects which are easier to implement, change, test, and reuse.

Which problems can the Observer design pattern solve?

The Observer pattern addresses the following problems:

A one-to-many dependency between objects should be defined without making the objects tightly coupled.

It should be ensured that when one object changes state, an open-ended number of dependent objects are updated automatically.

It should be possible that one object can notify an open-ended number of other objects.


Defining a one-to-many dependency between objects by defining one object (subject) that updates the state of dependent objects directly is inflexible because it couples the subject to particular dependent objects. Still, it can make sense from a performance point of view or if the object implementation is tightly coupled. Tightly coupled objects can be hard to implement in some scenarios, and hard to reuse because they refer to and know about (and how to update) many different objects with different interfaces. In other scenarios, tightly coupled objects can be a better option since the compiler will be able to detect errors at compile-time and optimize the code at the CPU instruction level.

Thursday 4 August 2022

Regressive Testing

Regression testing (rarely, non-regression testing) is re-running functional and non-functional tests to ensure that previously developed and tested software still performs after a change. If not, that would be called a regression.

Changes that may require regression testing include bug fixes, software enhancements, configuration changes, and even substitution of electronic components. As regression test suites tend to grow with each found defect, test automation is frequently involved. Sometimes a change impact analysis is performed to determine an appropriate subset of tests (non-regression analysis).

Tuesday 26 July 2022

Strategy

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

Strategy lets the algorithm vary independently. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.

For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, its source, user choice or other factors. These factors are not known until run-time and may require radically different validation to be performed. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.


Typically, the strategy pattern stores a reference to some code in a data structure and retrieves it. This can be achieved by the native function pointer, the first-class function, classes or class instances in object-oriented programming languages or accessing the language implementation's internal storage of code via reflection.

Friday 22 July 2022

Iterator

An iterator is an object that enables traversa of a container, mostly lists. Iterators are often provided via a container's interface. Though the interface and is fixed, iterators are often implemented in terms of the structures underlying a container implementation and are often tightly coupled to the container to enable the operational semantics of the iterator.

Internal iterators are higher order functions (often taking anonymous functions, but not necessarily) such as map(), reduce() etc., implementing the traversal across a container, applying the given function to every element in turn. An example might be Python's map function:

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

squared_digits = map(lambda x: x**2, digits) # Iterating over this iterator would result in 0, 1, 4, 9, 16, ..., 81.

An external iterator may be thought of as a pointer with two primary operations: referencing one particular element in the object collection (called element access) and modifying itself so it points to the next element (called element traversal).There must also be a way to create an iterator so it points to some first element as well as some way to determine when the iterator has exhausted all of the elements in the container.

The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list. An iterator class is usually designed in tight coordination with the corresponding container class. Usually, the container provides the methods for creating iterators.

One way of implementing iterators is to use a restricted form of coroutine, known as a generator. By contrast with a subroutine, a generator coroutine can yield values to its caller multiple times, instead of returning just once. Most iterators are naturally expressible as generators, but because generators preserve their local state between invocations, they're particularly well-suited for complicated, stateful iterators, such as tree traversers. There are subtle differences and distinctions in the use of the terms "generator" and "iterator", which vary between authors and languages. In Python, a generator is an iterator constructor: a function that returns an iterator. An example of a Python generator returning an iterator for the Fibonacci numbers using Python's yield statement follows:

def fibonacci(limit):
a, b = 0, 1
for _ in range(limit):
yield a
a, b = b, a + b
for number in fibonacci(100): # The generator constructs an iterator
print(number)

Wednesday 20 July 2022

Dependency Injection

In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function which wants to use a given service should not have to know how to construct those services. Instead, the receiving 'client' (object or function) is provided with its dependencies by external code (an 'injector'), which it is not aware of. Dependency injection helps by making implicit dependencies explicit and helps solve the following problems: How can a class be independent from the creation of the objects it depends on? How can an application, and the objects it uses support different configurations? How can the behavior of a piece of code be changed without editing it directly? Fundamentally, dependency injection consists of passing parameters to a method. Because the client does not build or find the service itself, it typically only needs to declare the interfaces of the services it uses, rather than their concrete implementations. This makes it easier to change which services are actually used at runtime, especially in statically-typed languages where changing the underlying objects would otherwise require re-compiling the source code.

Monday 18 July 2022

Multithreading

In computer architecture, multithreading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, which differs from multiprocessing. Threads use the memory of the process they belong to. Inter-process communication is slow as processes have different memory addresses. Inter-thread communication can be faster than inter-process communication because threads of the same process share memory with the process they belong to.

 Where multiprocessing systems include multiple complete processing units in one or more cores, multithreading aims to increase utilization of a single core by using thread-level parallelism, as well as instruction-level parallelism. As the two techniques are complementary, they are combined in nearly all modern systems architectures with multiple multithreading CPUs and with CPUs with multiple multithreading cores.

If a thread gets a lot of cache misses, the other threads can continue taking advantage of the unused computing resources, which may lead to faster overall execution, as these resources would have been idle if only a single thread were executed. Also, if a thread cannot use all the computing resources of the CPU (because instructions depend on each other's result), running another thread may prevent those resources from becoming idle.

Downside is that multiple threads can interfere with each other when sharing hardware resources such as caches or translation lookaside buffers (TLBs). As a result, execution times of a single thread are not improved and can be degraded, even when only one thread is executing, due to lower frequencies or additional pipeline stages that are necessary to accommodate thread-switching hardware.

shared resources (Tanenbaum):

among processes among threads
Address space; global variables; open files; child processes; pending alarms; signals and signal handlers; accounting info; programme counter; registers; stack; state;



From the software standpoint, hardware support for multithreading is more visible to software, requiring more changes to both application programs and operating systems than multiprocessing. Hardware techniques used to support multithreading often parallel the software techniques used for computer multitasking. Thread scheduling is also a major problem in multithreading. 

Threads use the memory of the process they belong to. Inter-process communication is slow as processes have different memory addresses. Inter-thread communication can be faster than inter-process communication because threads of the same process share memory with the process they belong to.



Monday 4 July 2022

NPIV

 NPIV or N_Port ID Virtualisation is a Fibre Channel feature, consisting of several Fibre Channel node port (N_Port) IDs sharing a single physical N_Port, which lets multiple Fibre Channel initiators occupy a single physical port. This isolates the virtual server's storage from other virtual servers' storage. 

 

N_Port initialization with and without NPIV

Normally N_Port initialisation goes like this:

1- N_Port sends FLOGI to address 0xFFFFFE to obtain a valid address
2- N_Port sends PLOGI to address 0xFFFFFC to register this address with the name server
3- N_Port sends SCR to address 0xFFFFFD to register for state change notifications

When NPIV enters the picture it may proceed like this:

4- N_Port sends FDISC to address 0xFFFFFE to obtain an additional address
5- N_Port sends PLOGI to address 0xFFFFFC to register this additional address with the name server
6- N_Port sends SCR to address 0xFFFFFD to register for state change notifications.


7- ... (repeat FDISC/PLOGI/SCR for next address)

FDISC is an abbreviation for Fabric Discovery, or "Discover Fabric Service Parameters", which is a misnomer. It behaves just like FLOGI.

Sunday 3 July 2022

Cohesion - a simple explanation

 Cohesion in Java is the Object-Oriented principle that a class should be designed with a single, well-defined purpose. The more focused a class is, the more is the cohesiveness of that class. Having high cohesion ensures that classes are easier to maintain, requiring fewer changes than low-cohesion classes. It also ensure a higher degree of reusability than classes with low cohesion.

example of class without cohesion:

public class Worker (){
String name;
double [] pay;

public void setName (String name){
this.name = name;
}

public String getName(){
return name;
}

public void setPay(double[] pay){
this.pay = pay;
}

public double calculateMeans(){
return means;
}

}

//

The same class with improved cohesion:

public class Worker (){
String name;
double [] pay;

public void setName (String name){
this.name = name;
}

public String getName(){
return name;
}

public class Pay {
Worker worker;
double [] pay;
public Pay (Worker, worker){
this.worker = worker;
}

}



public void setPay(double[] pay){
this.pay = pay;
}

public double calculateMeans(){
return means;
}

}

 

 

Notice the addition of the class Pay, improving the focus of the code and making it more cohesive. 

Monday 27 June 2022

OAuth

 OAuth ("Open Authorization") is an open standard for access delegation, commonly used as a way for internet users to grant websites or applications access to their information on other websites but without giving them the passwords. This mechanism is used by companies such as Amazon,Google, Facebook, Microsoft, and Twitter to permit the users to share information about their accounts with third-party applications or websites.

Generally, OAuth provides clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without providing credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server. In particular, OAuth 2.0 provides specific authorization flows for web applications, desktop applications, mobile phones, and smart devices.


OAuth 2.0 has been analyzed using formal web protocol analysis. This analysis revealed that in setups with multiple authorization servers, one of which is behaving maliciously, clients can become confused about the authorization server to use and may forward secrets to the malicious authorization server (AS Mix-Up Attack).This prompted the creation of a new best current practice internet draft that sets out to define a new security standard for OAuth 2.0. Assuming a fix against the AS Mix-Up Attack in place, the security of OAuth 2.0 has been proven under strong attacker models using formal analysis.

Typescript

TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, adding optional static typing to the language. It is designed for the development of large applications and transpiles to JavaScript.
It may be used to develop JavaScript applications for both client-side and server-side execution (as with Node.js or Deno). Multiple options are available for transpilation. The default TypeScript Compiler can be used, or the Babel compiler can be invoked to convert TypeScript to JavaScript.

TypeScript provides static typing through type annotations to enable type checking at compile time. This is optional and can be ignored to use the regular dynamic typing of JavaScript.

function add(left: number, right: number): number {
    return left + right;
}

The annotations for the primitive types are number, boolean and string. Typescript also supports data types with the following annotations: Array, Enums and void.

Additional data types are: Tuple, Union, never and any. An array with predefined data types at each index is Tuple type. A variable that holds more than one type of data is Union type. When you are sure that something is never going to occur you use never type. Weakly- or dynamically-typed structures are of any type. 

Tuesday 14 June 2022

understanding how JSON handles integers and strings

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON values cannot be one of the following data types:

  • a function
  • a date
  • undefined

 

Strings in JSON must always be in double quotes.
Example
{"name":"John"}


Numbers can be either an integer or a floating point.
Example
{"age":30}


JSON also supports objects, following the JSON syntax:

"obj name": {"field":value}

if value is a string, must be between double quotes.


"obj name": {"field":"string Value"}

 

The following is an example to illustrate both integers and strings

<!DOCTYPE html>
<html>
<body>
<p id="test"> </p>

<script>
var mytxt='{"emp":[' +
'{"name":"paul","surname":"smith","age":25,
"admission":2015},'+
'{"name":"maria","surname":"sheeva","age":20,
"admission":2016},'+
'{"name":"jon","surname":"shiv","age":27,
"admission":2012}]}';

var obj = eval ("(" + mytxt + ")");
document.getElementById("test").innerHTML =
obj.emp[1].name+ " " + obj.emp[1].surname + " " +
obj.emp[1].age + obj.emp[1].admission;
document.getElementById("test").innerHTML =
obj.emp[0].age + obj.emp[1].age + " " +
obj.emp[2].age;
document.getElementById("test").innerHTML =
obj.emp[2].admission + obj.emp[0].admission +
obj.emp[1].admission;


</script>

</body>


</html>


The output of the code above will be 6043, since document.getElementById receives whatever the containers obj.emp[2].admission, obj.emp[0].admission and obj.emp[1].admission hold, adding up the integer values passed in the parameters (2015+2016+2012)



Friday 13 May 2022

PROFIT, BILLING AND PROFITABILITY: CONCEPTS AND DIFFERENCES

 Despite being commonly associated as synonyms, the words invoicing and monetization do not have the same meaning. Most authors tend to present the concepts of profitability and monetization, as a comparison between a company's profits and its sales revenue. Revenue is the "total sum of a company's sales", in a certain period, from its commercial activity. In that sense, billing is one of the main indicators used to measure the size of a business. Unlike billing, which is all the money that
goes into a company, profit is all the money that is left after deducting all expenses and costs.

Profitability is as a vital force for the organisation and it is the expression of the economic result which is the company-wide goal. Profitability is a
operational efficiency indicator that indicates what is the gain that the company manages to generate. The greater the profitability and turnover, the better the profitability of the company and the shareholders.

Considering that profitability also measures efficiency, it is also understood as the measure of financial return on an investment

Profitability, also expressed as the rate of return, is the profit to investment ratio. Determining the return on investment lets is see if it was consistent
with what had been planned. From the analysis of this indicator, it is possible to assess the organization's final performance, in addition to making it possible to analyse the causes of the problems about profitability. Based on the present considerations, it is important to know the main profitability indexes, since they provide the analyst with an assessment of the company's earnings.

Thursday 12 May 2022

Marketing Information System

Marketing information system is defined by some as a structure of interaction between people, machines, methods and controls, in order to create an information flow capable of providing the basis for decision making in marketing. The information itself does not lead to the decision; it is necessary to choose a course of action that helps identify problems and opportunities and that indicates paths that reduce uncertainty. It is worth noting that not all companies have exclusive departments for information handling. Generally, it is found in companies, mainly small and medium-sized, sectors such as commercial/sales, logistics that make projections based on sales data, or on small marketing research, which is rarer. An information system can bring different types of advantages for the company in general, not just for the marketing sector. 

 It as a system in which marketing data is formally gathered, stored, analysed and distributed to managers in accordance with their informational needs on a regular basis.Furthermore, an overall Marketing Information System can be defined as a set structure of procedures and methods for the regular, planned collection, analysis and presentation of information for use in making marketing decisions. A marketing information system, which continuously collects the initial, routine and systematic data, is not only used for one particular topic but is designed for monitoring the degree of the marketing success to ensure the achievable of the operation as well. Internal database is a part of the most marketing information systems. In addition, it's relatively convenient to access and retrieve information. A databases allow marketers to tap into an abundance of information useful in making marketing decisions: internal sales reports, newspaper articles, company news releases, government economic reports, bibliographies, and more, often accessed through a computer system.

Internal data is a part of the data that is needed to be collect and handled by the marketing information system. But getting the information that is really needed from a marketing information system depends on what the information is and how it is used. The following internal operating data are essential:

 - Sales data, presented in a graphic format, can provide regular sales trend information and highlight whether certain customer types need to be targeted or focused.


- Price information by product line, comparison with competitors, can monitor market trends; analysed by customer type, it can check price trends in customer groups.


- Stock level data and trends in key accounts or distributors, focusing on whether different outlets need support; provide market share information.


- Market support information, coordinating the effects of marketing promotions, through advertising, direct marketing, trade incentives, consumer competitions and so on; helps to determine whether decisions are being made effectively.


- Competitive information, reviewing competitors' promotions and communications to see if the company is doing it better or worse than competitors, can improve market targeting.

Marketing managers use marketing information systems to develop short-term and long-term plans that outline product sales, profits and growth targets. Information systems facilitate the analysis and monitoring of performance against the objectives of each area of the marketing function. Information marketing systems support models and expert systems are also used to examine the results of various marketing plans.

New Digital Markets

 The recurring changes brought about by technological evolution have impacted societies and markets. Consumer culture has been changing gradually. With the increase in mobility and connectivity, consumers now have limited time to examine and evaluate brands. In a fast-paced world,our attention span tends to go down; people find it increasingly difficult to concentrate. Yet, across multiple channels—online and offline alike— consumers remain exposed to an excess of everything: product features, brand promises and sales pitches. Confused by advertising messages that are too good to be true, customers often overlook them, preferring to turn to more reliable sources of information: their social circle of friends and immediate family. 

 The change in comsumer behaviour in different societies and social groups has directly influenced the market as a whole, pressing it to meet their demands, hitherto repressed, and making it present in the most varied media and platforms. There is virtually no doubt that the digital revolution is one of the most significant influences on consumer behaviour and that the web's impact will continue to expand as more and more people around the world turn to the online world for information and services. Many of us are eager to browse the internet, and it's hard to imagine a time when texting, tweeting, using Facebook, or pinpointing interests on Pinterest wasn't part of our daily lives. In view of the above, the importance of the internet and its influence in the current global market and its social context is undeniable.

 According to a report by We Are Social (2021), web platforms are present in the daily lives of 59.5% of the world population, that is, the internet today has more than 4.5 billion connected users. In this sense, the need for companies to understand that more points of contact and higher volume in messages do not necessarily translate into greater influence. More than that, you need to stand out from the crowd and meaningfully connect with consumers at just a few crucial points of contact. One of the first business models that relate the market to the internet is the well-known e-commerce, the process of buying and selling products by electronic means, such as mobile and Internet applications, both for the retail and online shopping sector, as well as electronic transactions. With the advent of globalisation, commerce is no longer limited to going to the physical store of your choice to choose a product; with one click we can check competing offers, choose brands, see what other buyers say about the product, all in real time. The growing success of commercial transactions of this type is due to the fact that online retailers can predictably provide convenient, informative and personalised experiences for quite different types of consumers and businesses. 

 We can distinguish between entirely virtual companies, which started with a website, with no previous existence as a physical company, and virtual and real companies (brick-and-click), companies that have added an informational website and/or e-commerce option to their operations.

Tuesday 10 May 2022

Young people are trendsetters

Young people are trendsetters. They are consumers of Generation Right Now, demanding everything right away. When it comes to trends,they are so quick to spot and follow them that marketers often cannot keep up with them. The positive aspect is that these professionals can quickly identify patterns that will influence the market in the near future .

Despite this definition, it is still necessary to understand that many of the trends adopted by the younger consumer public generally turn out to be an ephemeral fad, while a few manage to evolve, evolving to a megatrend, and even reaching the predominant culture.

Friday 22 April 2022

AIX Operating System

 The AIX (Advanced Interactive eXecutive) operating system is a series of proprietary Unix operating systems by IBM. It's based on UNIX System V with 4.3BSD-compatible extensions and was the first operating system to have a journaling file system, with continuous enhanced features such as processor, disk and network virtualization, dynamic hardware resource allocation, and reliability engineering. The Common Desktop Environment (CDE) is AIX's default graphical user interface, with open-source KDE Plasma Workspaces and GNOME desktop also available.

SMIT is the System Management Interface Tool for AIX. It allows a user to navigate a menu hierarchy of commands, rather than using the command line. The F6 function key generates the command line that SMIT will invoke to complete it, while the smit.script file automatically records the commands with the command flags and parameters used, being useful to rerun system configuration tasks.

Smitty also refers to the same program, though it invokes the text-based version, while smit will bring up an X Window System based interface by searching for the DISPLAY variable. Failure to fire up the x window system will instead present the text interface.

Object Data Manager (ODM) is a database of system information integrated into AIX, akin to the registry in Microsoft Windows. Data managed in ODM is stored as objects with associated attributes. Command-line utilities such us odmshow, odmget, odmadd, odmchange and odmdelete allow for interaction with ODM. ODM is stored on disk using Berkeley DB files.

Friday 15 April 2022

running red lights is now rampant

I have noticed that reckless/murderous driving is at an all-time high. During March 2020-late 2021, driving where I live ebbed, and when people drove in that period they quickly got used to clog-free roads with no coppers on them and drove accordingly. Now that traffic is back to normal, they have not tightened up their driving and are running red lights, impatiently making right turns without looking and ignoring pedestrians crossing, doing U turns dangerously everywhere all the time, cutting corners by driving through gas stations at high speed, etc. It got so bad I started over the last few weeks seriously looking at who is doing this in my neighbourhoods. Most have tinted windows, so those are the usual suspects. They drive like fiends. This is a big deal for me because I don't own a car and walk on heavily travelled streets and roads every day. There have been times in the past where cars hit me but they were slowgoing and low-prowed and I rode up on the hood with no injury or police-legal-hospital-insurance involvement. The vehicles now are tank sized with like 4 or 5 feet grilles and they drive them like they're sports cars and they'll roll over me without the driver even knowing.