Skip to content

Instantly share code, notes, and snippets.

@xujiaji
Last active May 14, 2018 02:03
Show Gist options
  • Select an option

  • Save xujiaji/02bdfdcef389e6ecf3a39b3c364a91d2 to your computer and use it in GitHub Desktop.

Select an option

Save xujiaji/02bdfdcef389e6ecf3a39b3c364a91d2 to your computer and use it in GitHub Desktop.
Java编程思想:17.4【用适配器仿真潜在类型机制】,填充
public interface Addable<T> { void add(T t); }
public class Fill
{
public static <T> void fill(Collection<T> collection, Class<? extends T> classToken, int size)
{
for (int i = 0; i < size; i++)
{
try
{
collection.add(classToken.newInstance());
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
}
public class Fill2
{
public static <T> void fill(Addable<T> addable, Class<? extends T> classToken, int size)
{
for (int i = 0; i < size; i++)
{
try
{
addable.add(classToken.newInstance());
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
public static <T> void fill(Addable<T> addable, Generator<T> generator, int size)
{
for (int i = 0; i < size; i++)
{
addable.add(generator.next());
}
}
}
@xujiaji
Copy link
Author

xujiaji commented May 14, 2018

Fill2 的使用

Fill2对Collection的要求与Fill不同,它只需要实现Addable的对象,它是帮帮助我们创建潜在类型的一种体现。

class AddableCollectionAdapter<T> implements Addable<T>
{
    private Collection<T> c;

    public AddableCollectionAdapter(Collection<T> c)
    {
        this.c = c;
    }

    @Override
    public void add(T t)
    {
        c.add(t);
    }
}

/**
 * 通过泛型方法,辅助创建AddableCollectionAdapter
 */
class Adapter
{
    public static <T> Addable<T> collectionAdapter(Collection<T> c)
    {
        return new AddableCollectionAdapter<T>(c);
    }
}
/**
 * 只要实现了Addable接口即可,使用Fill2
 */
class AddableSimpleQueue<T> extends SimpleQueue<T> implements Addable<T>
{
    @Override
    public void add(T t)
    {
        super.add(t);
    }
}

class Fill2Test
{
    public static void main(String[] args)
    {
        List<Coffee> carrier = new ArrayList<>();
        Fill2.fill(new AddableCollectionAdapter<>(carrier), Coffee.class, 3);
        Fill2.fill(Adapter.collectionAdapter(carrier), Latte.class, 2);
        for (Coffee c : carrier)
        {
            print(c);
        }
        print("-------------------------------------");
        AddableSimpleQueue<Coffee> coffeeQueue = new AddableSimpleQueue<>();
        Fill2.fill(coffeeQueue, Mocha.class, 4);
        Fill2.fill(coffeeQueue, Latte.class, 2);
        for (Coffee c : coffeeQueue)
        {
            print(c);
        }

    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment