JAVA 注册工厂 模板 <<Thinking in Java>> 随笔

注册工厂的好处就是类的创建过程由类本身完成

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
interface Factory<T>{
	T create();
}

class Filter extends Part{
	
}

class FuelFilter extends Filter{
	public static class thisFactory implements Factory<FuelFilter>{
		public FuelFilter create() {
			return new FuelFilter();
		}
	}
}

class CabinFilter extends Filter{
	public static class thisFactory implements Factory<CabinFilter>{
		public CabinFilter create() {
			return new CabinFilter();
		}
	}
}


class Part{
	public String toString() {
		return getClass().getSimpleName();
	}
	static List<Factory<? extends Part>> partFactories =
		new ArrayList<Factory<? extends Part>>();
	static {
		partFactories.add(new FuelFilter.thisFactory());
		partFactories.add(new CabinFilter.thisFactory());
	}
	public static Random random = new Random(47);
	public static Part createRandom() {
		int n = random.nextInt(partFactories.size());
		return partFactories.get(n).create();
	}
}

public class Test {
	public static void main(String[] args) throws Exception {
		for(int i=0;i<2;i++) {
			System.out.println(Part.createRandom());
		}
	}
}

  

posted @ 2018-09-11 20:23  zz2108828  阅读(444)  评论(0编辑  收藏  举报