• 利用泛型接口实现生成器


    生成器是一种专门负责创建对象的类,实际上这是工厂方法设计模式的一种应用, 当时用生成器创建对象时,它不需要任何参数,而工厂方法一般需要参数。

    import java.util.Iterator;
    import java.util.Random;
    
    //一般来说一个生成器只定义一个方法,该方法用以产生新的对象
    interface Generator<T> {
    	public T next();
    }
    
    //一个继承体系
    class Coffee {
    	private static long counter = 0;
    	private final long id = counter++;
    	
    	@Override
    	public String toString() {
    		return getClass().getName() + " " + id;
    	}
    }
    class Latte extends Coffee{}
    class Macha extends Coffee{}
    class Breve extends Coffee{}
    
    
    //生成器类
    public class CoffeeGenerator implements Generator<Coffee>, Iterable<Coffee>{
    	
    	private int size;
    	private Class[] types = {Latte.class, Macha.class, Breve.class};
    	private static Random random = new Random(47);
    	
    	public CoffeeGenerator() {}
    	public CoffeeGenerator(int size) {
    		this.size = size;
    	}
    	
    	//实现Iterable 重写Iterator方法,是的我们可以利用foreach语法访问
    	class CoffeeIterator implements Iterator<Coffee> {
    		int count = size;
    		@Override
    		public boolean hasNext() {
    			return count > 0;
    		}
    
    		@Override
    		public Coffee next() {
    			count--;
    			return CoffeeGenerator.this.next();
    		}
    
    		@Override
    		public void remove() {
    			// TODO Auto-generated method stub
    			
    		}
    	}
    	
    	@Override
    	public Iterator<Coffee> iterator() {
    		// TODO Auto-generated method stub
    		return new CoffeeIterator();
    	}
    
    	
    	//重写生成器的next方法
    	@Override
    	public Coffee next() {
    		Coffee result = null;
    		try {
    			result = (Coffee)types[random.nextInt(types.length)].newInstance(); //利用Class对象随机生成Coffee对象
    		} catch (InstantiationException | IllegalAccessException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return result;
    	}
    	
    	public static void main(String[] args) {
    		CoffeeGenerator generator = new CoffeeGenerator();
    		
    		for (int i = 0; i < 5; ++i) {
    			System.out.println(generator.next());
    		}
    				
    		System.out.println("------------分割---------------");
    		
    		for (Coffee c : new CoffeeGenerator(5)) {
    			System.out.println(c);
    		}
    	}
    }
    
    输出:
    Breve 0
    Breve 1
    Macha 2
    Breve 3
    Macha 4
    ------------分割---------------
    Breve 5
    Macha 6
    Breve 7
    Latte 8
    Macha 9
    

      

  • 相关阅读:
    设计模式(六)Prototype Pattern 原型模式
    设计模式(五)Builder Pattern建造者模式
    Linux安装软件
    日志技术及JUL入门
    IDEA推出新字体,极度舒适
    HDFS的API操作
    Apollo的灰度发布
    Apollo整合SpringBoot开发
    Apollo配置发布原理
    Apollo应用配置
  • 原文地址:https://www.cnblogs.com/E-star/p/3436435.html
Copyright © 2020-2023  润新知