Note that there are some explanatory texts on larger screens.

plurals
  1. PODecorator for Java class with final methods
    text
    copied!<p>I have a (Java) class, WindowItem, that has a problem: One of the methods is not thread-safe. I can't fix WindowItem, because it's part of an external framework. So I figured I implement a Decorator for it, that has a "synchronized" keyword on the method in question.</p> <p>The Decorator extends WindowItem and will also contain WindowItem. Following the Decorator pattern, I create methods in the Decorator that call the WindowItem it contains.</p> <p>However, WindowItem has a few final methods, that I cannot override in the Decorator. That breaks the transparency of the Decorator. Let's make this explicit:</p> <pre><code>public class WindowItem { private List&lt;WindowItem&gt; windows; public Properties getMethodWithProblem() { ... } public final int getwindowCount() { return windows.size(); } } public class WindowItemDecorator extends WindowItem { private WindowItem item; public WindowItemDecorator(WindowItem item) { this.item = item; } # Here I solve the problem by adding the synchronized keyword: public synchronized Properties getgetMethodWithProblem() { return super.getMethodWithProblem(); } # Here I should override getWindowCount() but I can't because it's final } </code></pre> <p>In my own code, whenever I have to pass a WindowItem somewhere, I wrapped it in a decorator first: new WindowItemDecorator(item) -- and the thread-safety problem disappears. However, if my code calls getwindowCount() on a WindowItemDecorator, it will always be zero: It executes getWindowCount() on the superclass instead of the "item" member.</p> <p>So I would say the design of WindowItem (the fact that it has public final methods) makes it impossible to create a Decorator for this class.</p> <p>Is that correct, or am I missing something?</p> <p>In this case I might be able to keep a copy of the list of windows in the decorator, and keep it in sync, and then the result of getWindowCount() would be correct. But in that case, I prefer to fork and patch the framework...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload