public Interface factory<T>{
T create();
}
package chapter14.factory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Part{
public String toString(){
return getClass().getSimpleName();
}
static List<Factory<? extends Part>> partFactory =
new ArrayList<Factory<? extends Part>>();
static{
partFactory.add(new FuelFillter.Factory());
partFactory.add(new OilFillter.Factory());
partFactory.add(new CabinFillter.Factory());
partFactory.add(new AxBlet.Factory());
partFactory.add(new BxBlet.Factory());
}
public static Random rand = new Random(47);
public static Part createRandom(){
int n = rand.nextInt(partFactory.size());
return partFactory.get(n).create();
}
}
class Fillter extends Part{}
class FuelFillter extends Fillter{
public static class Factory
implements chapter14.factory.Factory<FuelFillter>{
public FuelFillter create(){ return new FuelFillter();}
}
}
class AirFillter extends Fillter{
public static class Factory
implements chapter14.factory.Factory<AirFillter>{
public AirFillter create(){ return new AirFillter();}
}
}
class CabinFillter extends Fillter{
public static class Factory
implements chapter14.factory.Factory<CabinFillter>{
public CabinFillter create(){ return new CabinFillter();}
}
}
class OilFillter extends Fillter{
public static class Factory implements chapter14.factory.Factory<OilFillter>{
@Override
public OilFillter create() {
// TODO Auto-generated method stub
return new OilFillter();
}
}
}
class Blet extends Part{}
class AxBlet extends Part{
public static class Factory
implements chapter14.factory.Factory<AxBlet>{
@Override
public AxBlet create() {
return new AxBlet();
}
}
}
class BxBlet extends Part{
public static class Factory
implements chapter14.factory.Factory<BxBlet>{
@Override
public BxBlet create() {
return new BxBlet();
}
}
}
public class RegisteredFactory {
public static void main(String[] args){
for(int i=0;i<10;i++){
System.out.println(Part.createRandom());
}
}
}
Java注册工厂模式案例
最新推荐文章于 2022-07-16 10:48:24 发布