Java:委托模式和受保护的方法 [英] Java: Delegation Pattern and Protected Methods

查看:167
本文介绍了Java:委托模式和受保护的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用委托模式来包装工厂在第三方库中创建的对象。最近,库在基类中添加了一个protected方法,我的包装类不再工作。有没有人有一个很好的解决方案,而不诉诸反思?

I have been using delegation pattern to wrap an object created by a factory in a 3rd party library. Recently, the library added a protected method in the base class and my wrapper class doesn't work any longer. Does anyone have a good solution without resorting to reflection?

这是在第三方图书馆和他们的包,

This is in 3rd party library and in their package,

public class Base {
    public void foo();

    protected void bar(); // Newly added
}

这是我自己的包,

public class MyWrapper extends Base {
    private Base delegate;

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

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

    protected void bar() {
        // Don't know what to do
    }
}

编辑我原来的帖子还不清楚这两个课程有不同的包。

My original post wasn't clear. These 2 classes are in different packages.

回答我为什么需要委派的问题。这是授权/包装器模式的典型用例,我无法在几行代码中显示。该库暴露了Base类,但它们工厂中的实际对象是Base的派生类。实际的类根据配置而改变。所以我不知道代表是什么。因此,直接继承模式在这里不起作用。

To answer the question why I need delegation. This is a typical use-case of Delegation/Wrapper pattern and I can't show it here in a few lines of code. The library exposes Base class but the actual object from their factory is a derived class of Base. The actual class changes depending on configuration. So I don't know what delegate is. Therefore straight inheritance pattern doesn't work here.

推荐答案

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.

这篇关于Java:委托模式和受保护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆