Visitor pattern implementation in case of source code un-availability

前端 未结 6 1608
旧时难觅i
旧时难觅i 2021-01-04 21:48

One of the reasons to consider the Visitor_pattern:

A practical result of this separation is the ability to add new operations to existing object structu

6条回答
  •  旧时难觅i
    2021-01-04 22:20

    First I had to made a few assumptions about the legacy code, since you didn't provide much details about it. Let's say I need to add a new method to Legacy without reimplementing everything. This is how I'll do it:

    public interface LegacyInterface {
        void A();
    }
    
    public final class LegacyClass implements LegacyInterface {
        @Override
        public void A() {
            System.out.println("Hello from A");
        }
    }
    

    First extends the "contract"

    public interface MyInterface extends LegacyInterface {
        void B();
    }
    

    And implement it in a "decorated" way

    public final class MyClass implements MyInterface {
        private final LegacyInterface origin;
    
        public MyClass(LegacyInterface origin) {
            this.origin = origin;
        }
    
        @Override
        public void A() {
            origin.A();
        }
    
        @Override
        public void B() {
            System.out.println("Hello from B");
        }
    }
    

    The key point is MyInterface extends LegacyInterface: this is the guarantee the implementations will benefit from both the services from the legacy code and your personnal addings.

    Usage

    MyInterface b = new MyClass(new LegacyClass());
    

提交回复
热议问题