공장 등록

8609 단어 공장 등록
우리 가 무 작위 로 여러 개의 서로 다른 부류 의 자 류 를 만 들 려 고 할 때 우 리 는 공장 방법 으로 디자인 모델 을 결합 하여 범 형 으로 실현 할 수 있다.코드 예:
public interface Factory<T> { T create(); } 
class Part {
      public String toString() {
        return getClass().getSimpleName();
      }
      //      
      static List<Factory<? extends Part>> partFactories =
        new ArrayList<Factory<? extends Part>>();   
      static {

        partFactories.add(new FuelFilter.Factory());
        partFactories.add(new AirFilter.Factory());
        partFactories.add(new CabinAirFilter.Factory());
        partFactories.add(new OilFilter.Factory());
        partFactories.add(new FanBelt.Factory());
        partFactories.add(new PowerSteeringBelt.Factory());
        partFactories.add(new GeneratorBelt.Factory());
      }
      private static Random rand = new Random(47);
      //      
      public static Part createRandom() {
        int n = rand.nextInt(partFactories.size());
        return partFactories.get(n).create();
      }
    }   

    class Filter extends Part {}

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

    class AirFilter extends Filter {
      public static class Factory implements beyondboy.Factory<AirFilter> {
        public AirFilter create() { return new AirFilter(); }
      }
    }   

    class CabinAirFilter extends Filter {
      public static class Factory implements beyondboy.Factory<CabinAirFilter> {
        public CabinAirFilter create() {
          return new CabinAirFilter();
        }
      }
    }

    class OilFilter extends Filter {
      public static class Factory implements beyondboy.Factory<OilFilter> {
        public OilFilter create() { return new OilFilter(); }
      }
    }   

    class Belt extends Part {}

    class FanBelt extends Belt {
      public static class Factory implements beyondboy.Factory<FanBelt> {
        public FanBelt create() { return new FanBelt(); }
      }
    }

    class GeneratorBelt extends Belt {
      public static class Factory implements beyondboy.Factory<GeneratorBelt> {
        public GeneratorBelt create() {
          return new GeneratorBelt();
        }
      }
    }   

    class PowerSteeringBelt extends Belt {
      public static class Factory implements beyondboy.Factory<PowerSteeringBelt> {
        public PowerSteeringBelt create() {
          return new PowerSteeringBelt();
        }
      }
    }   

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

실행 결과: Generator Belt CabinAirFilter Generator Belt AirFilter PowerSteeringBelt CabinAirFilter FuelFilter PowerSteeringBelt PowerSteeringBelt FuelFilter

좋은 웹페이지 즐겨찾기