Using Guava's Forwarding Decorators to create

2019-09-02 09:07发布

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条回答
一夜七次
2楼-- · 2019-09-02 09:49

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

查看更多
登录 后发表回答