Files
java-design-patterns/marker-interface/README.md
T
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00

6.5 KiB

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Marker Interface Pattern in Java: Defining Behavior Through Empty Interfaces Marker Interface Explore the Marker Interface pattern in Java, its benefits, real-world examples, and common uses. Learn how to use marker interfaces for metadata and special class behaviors. Structural en
Encapsulation
Interface
Polymorphism

Also known as

  • Marker
  • Tagging Interface

Intent of Marker Interface Design Pattern

The Marker Interface pattern in Java is used to convey metadata about a class in a type-safe manner. Interfaces in Java that have no method declarations are known as marker interfaces. They are used to indicate that a class implementing such an interface possesses some special behavior or capability.

Detailed Explanation of Marker Interface Pattern with Real-World Examples

Real-world example

Consider a scenario in a Java library system where certain books are rare and need special handling procedures, such as restricted check-outs or specific storage conditions. Analogous to the Marker Interface pattern, we could have a marker interface called RareBook. Books in the library catalog that implement this interface are flagged as requiring special treatment but don't necessarily have different methods from other books.

When a library staff member processes transactions or handles storage, the system checks if a book implements the RareBook interface. If it does, the system automatically enforces rules like "Do not allow check-outs for more than three days" or "Store in a temperature-controlled environment." This use of the marker interface effectively communicates special requirements without altering how books are generally managed, serving simply as a marker for special conditions.

In plain words

The Marker Interface design pattern in Java uses empty interfaces to signal or define certain properties and behaviors of objects in a type-safe way, without requiring specific method implementations.

Wikipedia says

The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.

To use this pattern, a class implements a marker interface (also called tagging interface) which is an empty interface, and methods that interact with instances of that class test for the existence of the interface. 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.

Programmatic Example of Marker Interface Pattern in Java

The Marker Interface design pattern is a design pattern in computer science that is used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.

In the given Java code example, the Permission interface acts as a marker interface. Classes that implement this interface are marked as having special permissions. Let's break down the code to understand how this pattern is implemented.

First, we define the Permission interface. This interface doesn't have any methods, making it a marker interface.

public interface Permission {
  // This is a marker interface and does not contain any methods
}

Next, we have two classes Guard and Thief that represent different types of characters in our application. The Guard class implements the Permission interface, indicating that objects of this class have special permissions.

public class Guard implements Permission {
  public void enter() {
    // Implementation of enter method
  }
}

On the other hand, the Thief class does not implement the Permission interface, indicating that objects of this class do not have special permissions.

public class Thief {
  public void steal() {
    // Implementation of steal method
  }

  public void doNothing() {
    // Implementation of doNothing method
  }
}

In the main method of the App class, we create instances of Guard and Thief. We then use the instanceof operator to check if these objects implement the Permission interface. If an object implements the Permission interface, it is allowed to perform certain actions. If not, it is restricted from performing those actions.

public class App {
  public static void main(String[] args) {
    final var logger = LoggerFactory.getLogger(App.class);
    var guard = new Guard();
    var thief = new Thief();

    if (guard instanceof Permission) {
      guard.enter();
    } else {
      logger.info("You have no permission to enter, please leave this area");
    }

    if (thief instanceof Permission) {
      thief.steal();
    } else {
      thief.doNothing();
    }
  }
}

In this way, the Marker Interface pattern allows us to associate metadata (in this case, special permissions) with a class in a type-safe manner.

When to Use the Marker Interface Pattern in Java

Marker interfaces are applicable in scenarios where you want to impose a special behavior or capability on a class, but don't want to force the class to define specific methods. This pattern is commonly used to indicate that a class conforms to a particular contract without needing to implement methods.

Real-World Applications of Marker Interface Pattern in Java

  • java.io.Serializable: Classes that implement this interface are capable of being serialized by the Java runtime.
  • java.lang.Cloneable: Classes that implement this interface can be cloned using the clone method in Java.

Benefits and Trade-offs of Marker Interface Pattern

Benefits:

  • Enables type checking at compile time, allowing developers to use polymorphism to write cleaner and more flexible code.
  • Allows the addition of metadata to classes without altering their actual behavior.

Trade-offs:

  • Can lead to empty interfaces in the codebase, which some may consider as not clean or clear in purpose.
  • Does not enforce any method implementations, which can lead to runtime errors if not properly handled.

References and Credits