有没有办法在实例化对象时隐藏/显示某些方法?

use*_*875 3 c# java oop

当我编写一个迭代列表的类时会想到这个问题,方法next()和previous()会不断循环(例如,如果在最后一个对象,返回它,然后将index重置为0)

在构造函数中,我正在考虑添加一个布尔变量,如果为true,它就像一个只有next()方法且没有循环的常规迭代器.在这种情况下,使用上一个()方法是没有意义的.所以我很好奇,在这种情况下是否可以隐藏previous()方法.是否有可能以某种方式在Java或C#中实现这一点?

其他语言怎么样?

Jon*_*Jon 6

C#

可以通过使两个方法成为两个不同接口的一部分,并将对象转换为两个接口之一.例如:

interface ILoopingIterator
{
    void Next();
    void Previous();
}

interface INonLoopingIterator
{
    void Next();
}

class PlaysItBothWays : ILoopingIterator, INonLoopingIterator
{
    void ILoopingIterator.Next()
    {
         this.NextCore();
    }

    void ILoopingIterator.Previous()
    {
         // since this code will never be shared anyway, put it here
    }

    void INonLoopingIterator.Next()
    {
         this.NextCore();
    }

    private void NextCore()
    {
        // do stuff here; this method only exists so that code can be shared
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我已经使类明确地实现了两个接口; 这样,实例的用户被迫选择他们想要使用哪个"模式".您可以只显式地实现一个接口(提供可以更改的"默认"模式).

现在:

var looping = (ILoopingIterator) new PlaysItBothWays(); // selects mode A
var nonLooping = (INonLoopingIterator) new PlaysItBothWays(); // selects mode B
Run Code Online (Sandbox Code Playgroud)

当然,如果他们愿意,这并不会阻止任何人将实例转换为"其他"接口,但如果程序员想要破坏他们自己的代码,他们也可以使用允许更多的反射.

Java的

在Java中,以上是不可能的.您可以通过让类公开返回两个接口之一的实例的方法,并使用返回的值来实现.当然,对象实际上是工厂而不是服务提供商,所以这就像是在欺骗这个问题.

class PlaysItBothWays
{
    public ILoopingIterator asLooping() { return /* something */ }
    public INonLoopingIterator asNonLooping() { return /* something else */ }
}
Run Code Online (Sandbox Code Playgroud)