object-private Vs class-private

时间:2009-12-28 16:54:26

标签: ruby oop private encapsulation smalltalk

在任何OOP语言中是否存在 object-private 的概念?我的意思是比经典的私人访问更具限制性?

Private (or class-private) restricts the access to the class itself. Only methods that are part of the same class can access private members.

object-private:限制对对象本身的访问。只有可以访问成员的方法对象才能编写:

public class Person {

private String secret;
public String othersSecret;

public void snoop(Person p) {
    othersSecret = p.secret; //will be prohibited by the compiler
}

编辑:

如果它存在,你可以给我一些例子......如果不是,你认为拥有这种功能是否有趣?是否可以在其他OOP语言中模拟它?

编辑2: 谢谢你们,所有答案都很有启发性......

到目前为止,暂时的结论

instance-private概念以2种语言存在:

经过数小时的谷歌搜索后,

1 - Smalltalk :)我找到了这个概念背后的语言!!

The state an object holds is always private to that object. Other objects can query or change that state only by sending requests (messages) to the object to do so.

2 - Ruby ,感谢 Logan

One person summed up the distinctions by saying that in C++, “private” means “private to this class”, while in Ruby it means “private to this instance”. What this means, in C++ from code in class A, you can access any private method for any other object of type A. In Ruby, you can not: you can only access private methods for your instance of object, and not for any other object instance (of class A).

7 个答案:

答案 0 :(得分:3)

在ruby中,per-object private是唯一的私有(你必须使用protected来获得类私有行为)。

E.g。 foo.rb:

 class A
    private
    def a=(x)
            @a=x
    end
    public
    def a
            @a
    end

    def b(c)
            c.a = 2
    end
 end

 a1 = A.new
 a2 = A.new
 a1.b(a2)

运行它,我们得到

 foo.rb:12:in `b': private method `a=' called for #<A:0xb7c9b6e0> (NoMethodError)
    from foo.rb:18

当然有很多方法可以解决这个问题,但几乎总是存在。

答案 1 :(得分:2)

我认为你想要的功能可以用比喻来实现,不允许人们直接沟通。 要以最小的努力实现这一目标,您可以引入一个界面,该界面无法访问您想要保密的内容。

public interface IPerson
{
    void communicateFormally();
}

public class Person : IPerson 
{
    private String secret;
    public String othersSecret;

    public void snoop(IPerson p) {
      othersSecret = p.secret; //will be prohibited by the compiler
    }
    ...
}

现在,这可能被一个丑陋的演员“黑客攻击”,但我认为这是黑客攻击的问题。

答案 2 :(得分:2)

答案 3 :(得分:1)

在Java中,您正在编写的内容,“私有”意味着类私有。没有办法强制对象私有模式。原因是“私有”是一种强制执行封装的方式,而不是安全

答案 4 :(得分:0)

我不认为类和对象private的这种区别对于最常见的语言OO存在,例如C#,C ++,Python,Java,Objective-C ......为了公平我可以'记住一种实际上具有此功能的语言。

答案 5 :(得分:0)

是的,您可以在Java中创建包含该接口的其他实例无法看到的实例变量的对象。琐碎的例子:

class Secretive { }
Secretive s = new Secretive() {
    int unknowable = 42;
};
Secretive t = new Secretive() {
    String unfathomable = "banana";
};

答案 6 :(得分:0)

    public class Person
    {
        private String privateSecret;
        public String PublicInformation;

        public void Snoop(Person p)
        {
            // will be allowed by the .NET compiler
            p.PublicInformation = p.privateSecret;
        }
    }

只需使用属性 readonly 字段来强制执行安全性

您还可以使用内部访问者在课堂上封装您的课程。

你也可以使用一些Deny技术,如this one

相关问题