【问题标题】:How do restrict access to a class property to only within the same namespace如何将对类属性的访问限制为仅在同一命名空间内
【发布时间】:2009-10-23 14:49:08
【问题描述】:

如何限制对同一个命名空间内的类属性的访问?考虑下面的课程。 Content 类不能发布本身,而是 ContentService 类 在将状态更改为已发布之前会做一些事情。

public class Content : Entity, IContent
    {
        public string Introduction { get; set; }

        public string Body { get; set; }

        public IList<Comment> Comments { get; set; }

        public IList<Image> Images { get; private set; }

        public State Status { get; } 
    }

public class ContentService
    {
        public IContent Publish(IContent article)
        {
            //Perform some biz rules before publishing   
            article.Status = State.Published;
            return article;
        }
    }

我怎样才能做到只有 ContentService 类可以改变文章的状态?

是否有任何设计模式可以帮助我处理这个问题?

【问题讨论】:

  • 我不确定我是否明白这一点:您是否在寻求一种方法来保护实现免受您自己使用不当?我一定是错过了什么......

标签: dns domain-driven-design


【解决方案1】:

您可以使用“内部”访问修饰符,这样只有同一个程序集中的类才能修改 Content 类的 State 成员(但即使在其他程序集中的每个人都可以获取该值)。

公共状态状态{获取;内部集; }

所以现在 ContentService 可以设置状态,因为它在同一个程序集中,但外部调用者只能获取状态(他们不允许设置它)。

【讨论】:

    【解决方案2】:

    Java 有“包可见”或“包私有”的概念。这实际上是您未指定可见性(privatepublic)的任何内容的默认设置。由于某种原因,几乎没有人使用它。

    【讨论】:

      【解决方案3】:

      将 ContentService 声明为 friend?

      另外,Java 有一个access modifier,相当于“包私有”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        相关资源
        最近更新 更多