Using Guava's Forwarding Decorators to create specific collections

99封情书 提交于 2020-01-06 07:34:30

问题


I have multiple methods that use multiple Collection parameters.

I wanted to make things more specific so I thought using Forwarding Decorator

The first question that comes to mind is:

  • Is it an overkill to use the Forwarding Decoartor, am I missing a something more simpler , I mean this is very simple thanks to Guava but still?

If Forwarding Decorator is the right path then

It seems fine so far, but one thing I am not sure of is how do I get the base collection(ImmutableSet in this case) back?

  1. Do I just create a new method (in interface and class) that returns "delegate" ? (If so what would be a good method name?)
  2. or is there something more ?

In the following code I am saving a ImmutableSet as setA.

The Code:

Interface:

package com.ps.experiment.forwarding;

import java.util.Collection;

public interface ISetA extends Set<String>{}

Class:

package com.ps.experiment.forwarding;

import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableSet;

    public class SetA extends ForwardingSet<String> implements ISetA
    {
        final ImmutableSet<String>  delegate;   // backing list

        @Override
        protected ImmutableSet<String> delegate()
        {
            return this.delegate;
        }

        private SetA(final ImmutableSet<String> strings)
        {
            this.delegate = strings;
        }

        public static ISetA of(final ImmutableSet<String> strings)
        {
            return new SetA(strings);
        }
    }

回答1:


The code you wrote is the correct way. If you want to access the back-end collection, simply make delegate() public instead of protected.



来源:https://stackoverflow.com/questions/15140195/using-guavas-forwarding-decorators-to-create-specific-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!