e2

滴滴侠,fai抖

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
package model2;

import java.lang.reflect.Constructor;
import java.util.Enumeration;
import java.util.Vector;

public abstract class Trash {

    private double weight;
    
    public Trash() {
    }
    
    Trash(double weight) {
        this.weight=weight;
    }

    public abstract double value();
    
    public double weight(){
        return weight;
    }
    
    public static void sumValue(Vector bin){
        Enumeration e = bin.elements();
        double val = 0.0f;
        while(e.hasMoreElements()){
            Trash t = (Trash)e.nextElement();
            val += t.weight() * t.value();
            System.out.println(t.getClass().getName()+"="+t.weight());
        }
        System.out.println("Total value="+val);
    }
    
    public static class PrototypeNotFoundException extends Exception{//...
    }
    
    public static class CannotCreateTrashException extends Exception{//...
    }
    
    private static Vector trashTypes = new Vector();
    
    public static Trash factory(Info info) throws PrototypeNotFoundException,CannotCreateTrashException{
        //take
        for(int i=0;i<trashTypes.size();i++){
            Class tc = (Class)trashTypes.elementAt(i);
            if (tc.getName().indexOf(info.className) !=-1) {
                try {
                    Constructor ctor = tc.getConstructor(new Class[]{double.class});
                    Trash trash =(Trash)ctor.newInstance(new Object[]{new Double(info.data)});
                    return trash;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new CannotCreateTrashException();
                }
            }
        }
        //add
        try {
            trashTypes.addElement(Class.forName(info.className));
        } catch (Exception e) {
            e.printStackTrace();
            throw new PrototypeNotFoundException();
        }
        //back
        return factory(info);
    }
    
    public static class Info{
        public String className;
        public double data;
        public Info(String className,double data){
            this.className = className;
            this.data = data;
        }
    }
    
}

 

 

 

 

posted on 2017-04-21 21:20  纯黑Se丶  阅读(109)  评论(0编辑  收藏  举报