组合模式和泛型模式

package p1;

public class B {
	public static void main(String[] args) {
		Holder1<? extends Fruit> h1 = new Holder1<Apple>();
		h1.set(new Fruit());  // 编译报错
		Fruit f1 = h1.get();
		
		Holder1<? super Fruit> h2 = new Holder1<Fruit>();
		h2.set(new Apple());
		h2.get(); // 获取的是Object类型
		
		Holder1<Apple> h3 = new Holder1<Apple>();
		h3.set(new Apple());
		h3.get();
		
		Holder1<Orange> h4 = new Holder1<Orange>();
		h4.set(new Orange());
		h4.get();
		
		Holder2 h5 = new Holder2();
		h5.set(new Apple());
		h5.get();
}

// 泛型模式
class Holder1<T> {
	private T value;
	
	public void set(T val) {
		value = val;
	}
	
	public T get() {
		return value;
	}
}

// 组合模式
class Holder2 {
	private Fruit value;
	
	public void set(Fruit val) {
		value = val;
	}
	
	// 协变类型(value实际可能是Fruit的子类)
	public Fruit get() {
		return value;
	}
}


class Fruit {
	
}

class Apple extends Fruit {
	
}

class Orange extends Fruit {
	
}

组合模式和泛型模式,各有千秋,欢迎一起讨论

你可能感兴趣的:(Java)