Marker interface pattern
From Free net encyclopedia
The marker interface pattern is a design pattern in computer science.
This pattern allows a class to implement a marker interface, which exposes some underlying semantic property of the class that cannot be determined solely by the class' methods. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used.
An example of the application of marker interfaces is the Java programming language. The Template:Javadoc:SE interface should be implemented by a class if it fully supports the Template:Javadoc:SE method. Every class in Java has the Template:Javadoc:SE class at the root of its inheritance hierarchy and so every object instantiated from any class has an associated clone()
method. However, developers should only call clone()
on objects of classes which implement the Cloneable
interface, as it indicates that the cloning functionality is actually supported in a proper manner.
Unfortunately there is a problem with this example, namely that in Java you cannot "unimplement" an interface. So if you subclass a class that implements Cloneable
, and then do something in your subclass that means it can't be cloned properly, your subclass will still be marked as a Cloneable
whether you want it or not. One way out is to throw an Exception (a Template:Javadoc:SE is a good idea) in the clone()
method, but then you are missing the whole point of the marker interface.
Still, this is generally a good idea, as subclasses usually do inherit behaviors from their parents and should inherit the marker interfaces as well.
Critique
The implementation of this pattern presented above is rather specific to Java. Other object models support rich ways of quickly querying static data. For example, .NET supports attributes that can be used to associate any type of data with a class or with its members. As of J2SE 5.0, Java supports reflective annotations that can be used to associate attributes with classes, interfaces, methods, constructors, fields and Java packages. Annotation allow a rich and fine-grained association of metadata to program elements.
Marker interface patterns in PHP 5
Although often shoved to the back of the pile in terms of OOP capabilities, PHP 5 provides an excellent level of Object functionality for a dynamically typed language. Although in most cases not neccesarry, you could recreate the Java example above like so:
<?php interface Cloneable {} class MyClass implements Cloneable {} ?>
See also
- Design markers for an expansion of this pattern.