且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:委托模式和受保护的方法

更新时间:2023-02-18 21:08:32

Access Levels
Modifier    Class   Package Subclass    World
public      Y          Y        Y         Y
protected   Y          Y        Y         N
no modifier Y          Y        N         N
private     Y          N        N         N

protected has package access,你看到任何具体问题吗?

protected has package access too, do you see any specific issue with this:

class Base {
        public void foo(){};

        protected void bar(){}; // Newly added
    }

    class MyWrapper  {
        private Base delegate;

        public MyWrapper(Base delegate) {
            this.delegate = delegate;
        }

        public void foo() {
            delegate.foo();
        }

        protected void bar() {
            // Don't know what to do
            delegate.bar(); //since its in same package, it can be referenced, do you expect compile time error?
        }
    }

进一步使用委托者模式为什么包装类扩展 Base class,我没有看到具体的需要,因为你已经有一个 Base 的实例。对我而言似乎更像是装饰师。

Further while using delegator pattern why wrapper class extends Base class, I don't see specific need since you already have an instance of Base. To me it seems more of an decorator.