Files
java-design-patterns/servant
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
..
2019-12-07 18:03:49 +02:00
2024-05-23 18:40:52 +03:00
2024-06-08 19:54:44 +03:00

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Servant Pattern in Java: Facilitating Rich Interactions with Servant Helpers Servant Explore the Servant design pattern in Java, an essential technique for decoupling operations from object classes. Learn how this pattern facilitates reusable and efficient code management through our detailed examples and explanations. Structural en
Decoupling
Interface
Messaging
Object composition
Resource management

Also known as

  • Helper

Intent of Servant Design Pattern

The Servant pattern is used to perform specific operations for a group of objects without changing the classes of the elements on which it operates.

Detailed Explanation of Servant Pattern with Real-World Examples

Real-world example

In a restaurant, a waiter (Servant) serves multiple tables (objects) by taking orders, delivering food, and handling payments. The waiter provides these common services without altering the fundamental nature of the tables or customers, allowing the restaurant to efficiently manage customer service while keeping the roles of the tables and customers unchanged.

In plain words

The Java Servant pattern effectively centralizes common functionality for multiple classes, enabling decoupled and reusable operations in software development without altering the original classes, promoting efficient Java design practices.

Wikipedia says

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 (or even just class) provides methods that take care of a desired service, while objects for which (or with whom) the servant does something, are taken as parameters.

Programmatic Example of Servant Pattern in Java

The Servant design pattern is a behavioral design pattern that defines a class that provides some sort of service to a group of classes. This pattern is particularly useful when these classes lack some common functionality that can't be added to the superclass. The Servant class brings this common functionality to a group of classes.

In the provided code, we have a Servant class that provides services to the Royalty class. The Servant class has methods like feed(), giveWine(), and giveCompliments() which are services provided to the Royalty class.

Here is the Servant class:

public class Servant {

    public String name;

    public Servant(String name) {
        this.name = name;
    }

    public void feed(Royalty r) {
        r.getFed();
    }

    public void giveWine(Royalty r) {
        r.getDrink();
    }

    public void giveCompliments(Royalty r) {
        r.receiveCompliments();
    }

    public boolean checkIfYouWillBeHanged(List<Royalty> tableGuests) {
        return tableGuests.stream().allMatch(Royalty::getMood);
    }
}

The Royalty class is an interface that is implemented by the classes that use the services of the Servant. Here is a simplified version of the Royalty interface:

public interface Royalty {
    void getFed();

    void getDrink();

    void receiveCompliments();

    void changeMood();

    boolean getMood();
}

The App class uses the Servant to provide services to the Royalty objects. Here is a simplified version of the App class:

public class App {

    private static final Servant jenkins = new Servant("Jenkins");
    private static final Servant travis = new Servant("Travis");

    public static void main(String[] args) {
        scenario(jenkins, 1);
        scenario(travis, 0);
    }

    public static void scenario(Servant servant, int compliment) {
        var k = new King();
        var q = new Queen();

        var guests = List.of(k, q);

        servant.feed(k);
        servant.feed(q);
        servant.giveWine(k);
        servant.giveWine(q);
        servant.giveCompliments(guests.get(compliment));

        guests.forEach(Royalty::changeMood);

        if (servant.checkIfYouWillBeHanged(guests)) {
            LOGGER.info("{} will live another day", servant.name);
        } else {
            LOGGER.info("Poor {}. His days are numbered", servant.name);
        }
    }
}

Running the application produces:

09:10:38.795 [main] INFO com.iluwatar.servant.App -- Jenkins will live another day
09:10:38.797 [main] INFO com.iluwatar.servant.App -- Poor Travis. His days are numbered

In this example, the Servant class provides services to the Royalty objects. The Servant class doesn't know about the specific implementation of the Royalty objects, it only knows that it can provide certain services to them. This is a good example of the Servant design pattern.

When to Use the Servant Pattern in Java

  • Use the Servant pattern when you need to provide a common functionality to a group of classes without polluding their class definitions, perfect for enhancing Java application architecture.
  • Suitable when the operations performed on the objects are not the primary responsibility of the objects themselves.

Real-World Applications of Servant Pattern in Java

  • In GUI applications to handle operations like rendering or hit-testing which are common across different UI components.
  • In games where various entities (like players, enemies, or items) need common behavior such as movement or collision detection.
  • Logging or auditing functionalities that are required across multiple business objects.

Benefits and Trade-offs of Servant Pattern

Benefits:

  • Promotes code reuse and separation of concerns by decoupling the operations from the objects they operate on.
  • Reduces code duplication by centralizing the shared functionality.

Trade-offs:

  • Can lead to an increase in the number of classes, potentially making the system harder to understand.
  • May introduce tight coupling between the Servant and the classes it serves if not designed carefully.
  • Adapter: The Servant pattern is similar to the Adapter pattern in that both provide a way to work with classes without modifying them, but the Servant pattern focuses on providing additional behavior to multiple classes rather than adapting one interface to another.
  • Facade: Both patterns provide a simplified interface to a set of functionalities, but the Servant pattern is typically used for adding functionalities to a group of classes, while the Facade pattern hides the complexities of a subsystem.
  • Strategy: The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The Servant pattern can be used in conjunction with the Strategy pattern to define operations that apply to multiple classes.
  • View Helper: The View Helper pattern is related as it also centralizes common functionality, but it focuses on separating presentation logic from business logic in web applications.

References and Credits