简体   繁体   中英

What is the pattern used in this class?

I wonder what is the patten in this code.

I was analyzing a library called web3j.

Here is the code for this source:

public interface FilterTopic<T>
{
    @JsonValue
    T getValue();
}

public static class SingleTopic implements FilterTopic<String>
{
    private String topic;

    public SingleTopic()
    {
        this.topic = null;
    }
    public SingleTopic(String topic)
    {
        this.topic = topic;
    }

    @Override
    public String getValue() {
        // TODO Auto-generated method stub
        return topic;
    }

}

public static class ListTopic implements FilterTopic<List<SingleTopic>>
{
    private List<SingleTopic> topics;

    public ListTopic(String… optionalTopics)
    {
        topics = new ArrayList<>();
        for(String topic : optionalTopics)
        {
            if(topic != null) topics.add(new SingleTopic(topic));
            else topics.add(new SingleTopic());
        }
    }

    @Override
    public List<SingleTopic> getValue() {
        // TODO Auto-generated method stub
        return topics;
    }   
}

You can see the FilterTopic interface. And it has several return values using the static class. What pattern is this like?

If you want to see the full code, look here https://github.com/KoangHoYeom/Ethereum-JSONRPC-With-Java-Ex/blob/master/src/main/java/org/BlockChainService/domain/dto/Filter.java

Thank you for reading!

It's just a normal Object Oriented code and is using a simple inheritance. But if you mean how it can have different return values for the same method definition, then you need to take a look at a tutorial about Generics in Java.

As a short answer, the original method accepts a type as a parameter inside a pair of < and > ( FilterTopic<T> ). This T can be any type (eg Object, String, List, etc.), and you can see that the getValue() method also returns the same type (the T). You can use any character or name instead of T, it's just a placeholder (like a variable name).

Then each child class while implementing this interface, specifies the exact type name for this parameter. This means that the getValue() method of that class should return the exact same type. So the SingleTopic is defined using <String> then its getValue() method should return String . The ListTopic is defined using a list of SingleTopic items, then its getValue() must return a such a list.

You can read more about generics in java at following links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM