Twin pattern

Last updated

In software engineering, the Twin pattern is a software design pattern that allows developers to model multiple inheritance in programming languages that do not support multiple inheritance. This pattern avoids many of the problems with multiple inheritance. [1]

Contents

Definition

Instead of having a single class which is derived from two super-classes, have two separate sub-classes each derived from one of the two super-classes. These two sub-classes are closely coupled, so, both can be viewed as a Twin object having two ends. [1]

Applicability

The twin pattern can be used:

Structure

There will be two or more parent classes which are used to be inherited. There will be sub-classes each of which is derived from one of the super-classes. The sub-classes are mutually linked via fields, and each sub-class may override the methods inherited from the super-class. New methods and fields are usually declared in one sub-class. [1]

The following diagram shows the typical structure of multiple inheritance:

Typical multiple inheritance Tobbszoros orokles (iker minta nelkul).png
Typical multiple inheritance

[1]

The following diagram shows the Twin pattern structure after replacing the previous multiple inheritance structure:

Twin pattern Iker minta.png
Twin pattern

[1]

Collaborations

Each child class is responsible for the protocol inherited from its parent. It handles the messages from this protocol and forwards other messages to its partner class. [1]

Clients of the twin pattern reference one of the twin objects directly and the other via its twin field. [1]

Clients that rely on the protocols of parent classes communicate with objects of the respective child class. [1]

Sample code

The following code is a sketched implementation of a computer game board with moving balls.

Class for the game board:

publicclassGameboardextendsCanvas{publicintwidth,height;publicGameItemfirstItem;}

[1]

Code sketch for GameItem class:

publicabstractclassGameItem{Gameboardboard;intposX,posY;GameItemnext;publicabstractvoiddraw();publicabstractvoidclick(MouseEvente);publicabstractbooleanintersects(GameItemother);publicabstractvoidcollideWith(GameItemother);publicvoidcheck(){GameItemx;for(x=board.firstItem;x!=null;x=x.next)if(intersects(x))collideWith(x);}publicstaticBallItemnewBall(intposX,intposY,intradius){//method of GameBoardBallItemballItem=newBallItem(posX,posY,radius);BallThreadballThread=newBallThread();ballItem.twin=ballThread;ballThread.twin=ballItem;returnballItem;}}

[1]

Code sketch for the BallItem class:

publicclassBallItemextendsGameItem{BallThreadtwin;intradius;intdx,dy;booleansuspended;publicvoiddraw(){board.getGraphics().drawOval(posX-radius,posY-radius,2*radius,2*radius);}publicvoidmove(){posX+=dx;posY+=dy;}publicvoidclick(){if(suspended)twin.resume();elsetwin.suspend();suspended=!suspended;}publicbooleanintersects(GameItemother){if(otherinstanceofWall)returnposX-radius<=other.posX&&other.posX<=posX+radius||posY-radius<=other.posY&&other.posY<=posY+radius;elsereturnfalse;}publicvoidcollideWith(GameItemother){Wallwall=(Wall)other;if(wall.isVertical)dx=-dx;elsedy=-dy;}}

[1]

Code sketch for BallThread class:

publicclassBallThreadextendsThread{BallItemtwin;publicvoidrun(){while(true){twin.draw();/*erase*/twin.move();twin.draw();}}}

[1]

Implementation of the Twin pattern

The following issues should be considered:

See also

Related Research Articles

Eiffel is an object-oriented programming language designed by Bertrand Meyer and Eiffel Software. Meyer conceived the language in 1985 with the goal of increasing the reliability of commercial software development; the first version becoming available in 1986. In 2005, Eiffel became an ISO-standardized language.

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

In object-oriented programming, the decorator pattern is a design pattern 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 as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.

In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.

Multiple dispatch or multimethods is a feature of some programming languages in which a function or method can be dynamically dispatched based on the run-time (dynamic) type or, in the more general case, some other attribute of more than one of its arguments. This is a generalization of single-dispatch polymorphism where a function or method call is dynamically dispatched based on the derived type of the object on which the method has been called. Multiple dispatch routes the dynamic dispatch to the implementing function or method using the combined characteristics of one or more arguments.

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. Function objects are often called functors.

<span class="mw-page-title-main">ActionScript</span> Object-oriented programming language created for the Flash multimedia platform

ActionScript is an object-oriented programming language originally developed by Macromedia Inc.. It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript, though it originally arose as a sibling, both being influenced by HyperTalk. ActionScript code is usually converted to byte-code format by the compiler.

In computer programming, specifically object-oriented programming, a class invariant is an invariant used for constraining objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once.

<span class="mw-page-title-main">Multiple integral</span> Generalization of definite integrals to functions of multiple variables

In mathematics (specifically multivariable calculus), a multiple integral is a definite integral of a function of several real variables, for instance, f(x, y) or f(x, y, z). Integrals of a function of two variables over a region in (the real-number plane) are called double integrals, and integrals of a function of three variables over a region in (real-number 3D space) are called triple integrals. For multiple integrals of a single-variable function, see the Cauchy formula for repeated integration.

An interface in the Java programming language is an abstract type that is used to declare a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations. All methods of an Interface do not contain implementation as of all versions below Java 8. Starting with Java 8, default and static methods may have implementation in the interface definition. Then, in Java 9, private and private static methods were added. At present, a Java interface can have up to six different types.

The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

The circle–ellipse problem in software development illustrates several pitfalls which can arise when using subtype polymorphism in object modelling. The issues are most commonly encountered when using object-oriented programming (OOP). By definition, this problem is a violation of the Liskov substitution principle, one of the SOLID principles.

In software engineering, the servant pattern defines an object used to offer some functionality to a group of classes without defining that functionality in each of them. A Servant is a class whose instance provides methods that take care of a desired service, while objects for which the servant does something, are taken as parameters.

Join-patterns provides a way to write concurrent, parallel and distributed computer programs by message passing. Compared to the use of threads and locks, this is a high level programming model using communication constructs model to abstract the complexity of concurrent environment and to allow scalability. Its focus is on the execution of a chord between messages atomically consumed from a group of channels.

A bitwise trie is a special form of trie where each node with its child-branches represents a bit sequence of one or more bits of a key. A bitwise trie with bitmap uses a bitmap to denote valid child branches.

References

  1. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Mössenböck, H., Twin - A Design Pattern for Modelling Multiple Inheritance, University of Linz, Institute for System Software
  2. Stroustrup, B. (May 1989), Multiple Inheritance for C++, Helsinki: Proceeding EUUG Spring Conference