代码之家  ›  专栏  ›  技术社区  ›  Elist

Java-OOP-在编译时强制特定的实现

  •  0
  • Elist  · 技术社区  · 8 年前

    我的代码有一套“工厂”( IfaceProducerProcessor Iface ). 这些工厂以后也应该能够在他们生产的实例上执行一些处理,但不能在其他的实现上执行 .

    伊法斯 例如,它只能将其单独传递给其原始生产者进行处理。

    interface Iface {
        void foo();
    }
    
    interface IfaceProducerProcessor {
        Iface produceIface();
        void processIface(Iface iface);
    }
    
    class A implements IfaceProducerProcessor {
        Iface produceIface() {
            return new AIfaceImpl();
        }
    
        void processIface(Iface iface) {
            // How to enforce AIfaceImpl in compile-time?
            if (!(iface instanceof AIfaceImpl)) {
                throw IlleagalArgumentException("Expected instanceof AIfaceImpl.");
            }
    
            ...
    
            ((AIfaceImpl)iface).bar();
    
            ...
        }
    
        class AIfaceImpl implements Iface {
            // implementation of foo() ...
    
            void bar() {
    
            }
        }
    }
    
    class B implements IfaceProducerProcessor {
    
        ...
    
        class BIfaceImpl implements Iface {
    
            ...
    
        }
    }
    
    ...
    

    如果很明显,我有一个设计缺陷,我会很高兴听到它是什么,以及如何纠正它,但请记住,这是一个简化的例子,我的代码,和具体的细节,我不能进入引导我到给定的设计。。。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Lino    8 年前

    您对泛型的猜测可能最有效,请考虑对 IfaceProducerProcessor . 注意泛型参数 I Iface 仅限于:

    interface IfaceProducerProcessor<I extends Iface> {
        I produceIface();
        void processIface(I iface);
    }
    

    那我们班呢 A

    class A implements IfaceProducerProcessor<AIfaceImpl>{
         public AIfaceImpl produceIface(){
             /* ... */
         }
    
         public void processIface(AIfaceImpl iface){
             /* ... */
         }
    }
    

    这样,您就可以通过只想使用的编译器强制执行 AIfaceImpl 在这个特定的 如果生产者处理器 .

    同样的方法也适用于 如果生产者处理器

    class B implements IfaceProducerProcessor<BIfaceImpl>{
        /* ... */
    }
    

    等等。