Java泛型 创建实例

  1. 工厂模式在泛型中创建实例
    interface FactoryI {
    	T create();
    }
    
    class Foo {
    	private T x;
    
    	public > Foo(F factory) {
    		x = factory.create();
    	}
    }
    
    // 对于不是自己定义的Java对象创建
    class IntegerFactory implements FactoryI {
    
    	@Override
    	public Integer create() {
    		return new Integer(0);
    	}
    }
    
    // 自定义的对象可以添加内部工厂方法或者内部工厂类
    class Widget {
    	public static class Factory implements FactoryI {
    
    		@Override
    		public Widget create() {
    			return new Widget();
    		}
    
    	}
    }
    
    public class FactoryConstraint {
    	public static void main(String[] args) {
    		new Foo(new IntegerFactory());
    		new Foo(new Widget.Factory());
    	}
    }
     
  2. 模板方法方式
    abstract class GenericWithCreate {
    	final T element;
    
    	public GenericWithCreate() {
    		element = create();
    	}
    
    	abstract T create();
    }
    
    class X {
    
    }
    
    class Creator extends GenericWithCreate {
    	@Override
    	X create() {
    		return new X();
    	}
    
    	void f() {
    		System.out.println(element.getClass().getSimpleName());
    	}
    
    }
    
    public class CreatorGeneric {
    	public static void main(String[] args) {
    		Creator creator = new Creator();
    		creator.f();
    	}
    }
    
     

 

你可能感兴趣的:(Java基础)