使用Guava的转发装饰器来创建特定的集合 [英] Using Guava's Forwarding Decorators to create specific collections

查看:346
本文介绍了使用Guava的转发装饰器来创建特定的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个使用多个Collection参数的方法。



我想让事情更具体,所以我想使用转发装饰器



第一个问题是:




  • 这是一个过度使用转发Decoartor,我缺少一个更简单的
    ,我的意思是非常简单感谢Guava
    但仍然?



如果转发装饰器是正确的路径,



到目前为止看起来很好,但是我不确定的是我如何获得基本集合(在这种情况下为ImmutableSet)?


  1. 我只是创建一个返回
    delegate的新方法(在界面和类中)?




代码:



接口:

在下面的代码中,我将一个ImmutableSet保存为setA。 / p>

  package com.ps.experiment.forwarding; 

import java.util.Collection;

public interface ISetA extends Set< String> {}

/ p>

  package com.ps.experiment.forwarding; 

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

public class SetA extends ForwardingSet< String>实现ISetA
{
final ImmutableSet< String>代表; // backing list

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

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

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


解决方案

你写的代码是正确的方法。如果您要访问后端集合,只需使 delegate() public ,而不是 protected


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);
        }
    }

解决方案

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

这篇关于使用Guava的转发装饰器来创建特定的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆