美文网首页
用于匿名内部类的泛型

用于匿名内部类的泛型

作者: 呆呆李宇杰 | 来源:发表于2017-09-10 19:01 被阅读118次

    匿名内部类

    泛型还可以使用于内部类和匿名内部类。

    class Customer {
        private static long counter = 1;
        private final long id = counter++;
    
        private Customer() {
    
        }
    
        public String toString() {
            return "Customer " + id;
        }
    
        public static Generator<Customer> generator() {
            return new Generator<Customer>() {
                @Override
                public Customer next() {
                    return new Customer();
                }
            };
        }
    }
    
    class Teller {
        private static long counter = 1;
        private final long id = counter++;
    
        private Teller() {
        }
    
        public String toString() {
            return "Teller " + id;
        }
    
        public static Generator<Teller> generator = new Generator<Teller>() {
            @Override
            public Teller next() {
                return new Teller();
            }
        };
    }
    
    
    public class BankTeller {
        public static void serve(Teller t, Customer c) {
            System.out.println(t + " serves " + c);
        }
    
        public static void main(String[] args) {
            Random rand = new Random(47);
            Queue<Customer> line = new LinkedList<>();
            Generators.fill(line, Customer.generator(), 15);
            List<Teller> tellers = new ArrayList<>();
            Generators.fill(tellers, Teller.generator, 4);
            for (Customer c : line) {
                serve(tellers.get(rand.nextInt(tellers.size())), c);
            }
        }
    }
    
    // Outputs
    Teller 3 serves Customer 1
    Teller 2 serves Customer 2
    Teller 3 serves Customer 3
    Teller 1 serves Customer 4
    Teller 1 serves Customer 5
    Teller 3 serves Customer 6
    Teller 1 serves Customer 7
    Teller 2 serves Customer 8
    Teller 3 serves Customer 9
    Teller 3 serves Customer 10
    Teller 2 serves Customer 11
    Teller 4 serves Customer 12
    Teller 2 serves Customer 13
    Teller 1 serves Customer 14
    Teller 1 serves Customer 15
    

    上面的CustomerTeller都通过使用匿名内部类实现了Generator接口,并且他们都只有private的构造器,这就意味着要想创建这两个类的对象,必须使用generator方法。其中,Customer类的generator()方法每次调用都会返回一个新的Generator<Customer>对象,但我们其实并不需要多个Generator对象。这时,就可以像Teller类一样,只创建一个publicgenerator对象。在main方法中,这两种创建Generator对象的方法在fill()中都用到了。

    由于Customer中的generator()方法,以及Teller中的Generator对象都声明成static,所以它们都无法作为接口的一部分,因此不能用接口这种特定的惯用法来泛化这两者。尽管如此,它们在fill()方法中都工作得很好。(//TODO 看不懂)

    相关文章

      网友评论

          本文标题:用于匿名内部类的泛型

          本文链接:https://www.haomeiwen.com/subject/orstsxtx.html